tla-ts 0.0.3-dev.33ae522 → 0.0.3-dev.367c92f

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.33ae522",
3
+ "version": "0.0.3-dev.367c92f",
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
@@ -72,6 +72,7 @@ import { createCounterExample } from "./tlc-ext";
72
72
  import { getFingerprintTrace, valueSources } from "./value-sources";
73
73
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
74
74
  import {
75
+ assertFingerprintable,
75
76
  combineHash,
76
77
  createModelValue,
77
78
  formatState,
@@ -1130,12 +1131,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1130
1131
  failure: { ...result.failure, replay: { output: replayed, ...replayedStack, isBeforeError } },
1131
1132
  };
1132
1133
  };
1133
- // TLC fingerprints a state outside CallStackTool, so a failure leaves the stack empty.
1134
+ // TLC fingerprints a state outside CallStackTool, so a failure of a value with a source leaves
1135
+ // the stack empty. Any other failure keeps the stack of the initial predicate.
1134
1136
  const fingerprintReplayed = (state: Value[], traced: Environment) => {
1135
1137
  try {
1136
1138
  getStateHash(getFingerprintState(state));
1137
1139
  } catch (error) {
1138
- if (traced.trace) traced.trace.length = 0;
1140
+ if (traced.trace && getFingerprintTrace(error)) traced.trace.length = 0;
1139
1141
  throw error;
1140
1142
  }
1141
1143
  };
@@ -1388,6 +1390,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1388
1390
  let hash = 0x811c9dc5;
1389
1391
  for (let index = 0; index < state.length; index++)
1390
1392
  hash = combineHash(hash, getValueHash(state[index]));
1393
+ assertFingerprintable(state);
1391
1394
  return hash & 0x3fffffff;
1392
1395
  };
1393
1396
  const isSameState = (stored: Value[], state: Value[]) => {
@@ -244,6 +244,7 @@ export const createEnvironment = (
244
244
  const createName = (name: string) => `${name}#${copyCount.value++}`;
245
245
  const instanceChecks: InstanceCheck[] = [];
246
246
  const instanceActions = new Map<string, InstanceAction>();
247
+ const qualifiedNames = new Map<string, string>();
247
248
 
248
249
  const addStandardModule = (name: string): Symbols | undefined => {
249
250
  const cached = standardExports.get(name);
@@ -429,6 +430,7 @@ export const createEnvironment = (
429
430
  if (declarations.length > 0) {
430
431
  instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
431
432
  }
433
+ qualifiedNames.set(key, `${instance.name}!${name}`);
432
434
  symbols.set(`${instance.name}!${name}`, {
433
435
  key,
434
436
  arity: symbol.arity + instance.params.length,
@@ -755,6 +757,7 @@ export const createEnvironment = (
755
757
  constants: new Set(constants.map((constant) => constant.name)),
756
758
  variables: new Set(variables),
757
759
  getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
760
+ getQualifiedName: (symbol) => qualifiedNames.get(visible.get(symbol)?.key ?? symbol),
758
761
  });
759
762
  const linked = {
760
763
  module,
package/src/evaluate.ts CHANGED
@@ -35,6 +35,7 @@ import {
35
35
  getDomain,
36
36
  getFunctionDomain,
37
37
  getIntervalElements,
38
+ getLazySubsets,
38
39
  getSequenceElements,
39
40
  getValueHash,
40
41
  isFunctionValue,
@@ -342,9 +343,8 @@ export const getEnumeratedElements = (set: Value, expression: Expression) => {
342
343
  : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
343
344
  );
344
345
  }
345
- return typeof set === "object" && set.kind === "Interval"
346
- ? getIntervalElements(set)
347
- : toFiniteSet(set).elements;
346
+ if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
347
+ return getLazySubsets(set) ?? toFiniteSet(set).elements;
348
348
  };
349
349
 
350
350
  export const forEachBinding = (
@@ -1,4 +1,4 @@
1
- import { getValueFingerprint, getValueHash, type Value } from "./values";
1
+ import { assertFingerprintable, getValueFingerprint, getValueHash, type Value } from "./values";
2
2
 
3
3
  const EMPTY = 0;
4
4
  const INITIAL_CAPACITY = 1 << 12;
@@ -20,6 +20,7 @@ export const writeStateFingerprint = (state: Value[], fingerprint: Int32Array) =
20
20
  first = Math.imul(first ^ getValueHash(state[index]), 0x01000193);
21
21
  second = Math.imul(second ^ getValueFingerprint(state[index]), 0x5bd1e995);
22
22
  }
23
+ assertFingerprintable(state);
23
24
  fingerprint[0] = mix(first) || 1;
24
25
  fingerprint[1] = mix(second);
25
26
  };
package/src/levels.ts CHANGED
@@ -33,6 +33,7 @@ interface LevelContext {
33
33
  constants: Set<string>;
34
34
  variables: Set<string>;
35
35
  getDefinition: (name: string) => Definition | undefined;
36
+ getQualifiedName?: (name: string) => string | undefined;
36
37
  }
37
38
 
38
39
  type ScopeEntry =
@@ -205,7 +206,13 @@ export const createLevelAnalyzer = (context: LevelContext) => {
205
206
  if (context.variables.has(name)) return { kind: "Declared", name, level: 1, arity: 0 };
206
207
  const definition = context.getDefinition(name);
207
208
  if (definition) {
208
- return { kind: "Defined", levels: analyzeDefinition(definition, new Map()) };
209
+ const levels = analyzeDefinition(definition, new Map());
210
+ // SANY names a definition of an instance by its qualified name, as in I!Foo.
211
+ const qualifiedName = context.getQualifiedName?.(name);
212
+ return {
213
+ kind: "Defined",
214
+ levels: qualifiedName ? { ...levels, name: qualifiedName } : levels,
215
+ };
209
216
  }
210
217
  const signature = CORE_SIGNATURES.get(name) ?? STANDARD_LEVELS.get(name);
211
218
  if (signature) return { kind: "Defined", levels: signature };
package/src/parser.ts CHANGED
@@ -628,9 +628,15 @@ const parse = (source: string, isTlapm: boolean): Module => {
628
628
  const body = parseExpression();
629
629
  return withRange({ kind: "Lambda", params, body, location: getLocation(token) }, start);
630
630
  }
631
- return parseExpression();
631
+ const argument = parseExpression();
632
+ // SANY reads an argument that only names an operator of a parameterized instance, such as
633
+ // I!Op, as that operator, which takes the arguments of the instance too.
634
+ if (argument.kind === "Identifier") missingArguments.delete(argument);
635
+ return argument;
632
636
  };
633
637
 
638
+ const missingArguments = new Map<Expression, { location: string; message: string }>();
639
+
634
640
  const lastArguments: { range: SourceRange | undefined } = { range: undefined };
635
641
 
636
642
  const parseArguments = () =>
@@ -830,7 +836,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
830
836
  };
831
837
 
832
838
  const parsePrimary = (): Expression => {
833
- const isFactStart = cursor.index === factStart.index;
839
+ const start = cursor.index;
840
+ const isFactStart = start === factStart.index;
834
841
  const token = advance();
835
842
  const location = getLocation(token);
836
843
  if (isTlapm && token.kind === "Keyword" && token.text === "LAMBDA") {
@@ -869,7 +876,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
869
876
  const instance = openModules
870
877
  .flatMap((module) => module.instances)
871
878
  .find((candidate) => candidate.name === name);
872
- if (instance && !isFactStart && !isTlapm && instance.params.length !== args.length) {
879
+ const isMissingArguments =
880
+ instance !== undefined &&
881
+ !isFactStart &&
882
+ !isTlapm &&
883
+ instance.params.length !== args.length;
884
+ if (isMissingArguments && args.length > 0) {
873
885
  throw createError(
874
886
  `The operator ${name} requires ${instance.params.length} arguments`,
875
887
  token,
@@ -883,19 +895,36 @@ const parse = (source: string, isTlapm: boolean): Module => {
883
895
  const names = selectors.flatMap((selector) =>
884
896
  selector.kind === "Name" ? [selector.name] : [],
885
897
  );
886
- if (names.length < selectors.length) return { kind: "Subexpression", selectors, location };
887
898
  const operator = names.join("!");
888
899
  const qualifiedArgs = selectors.flatMap((selector) =>
889
900
  "args" in selector ? selector.args : [],
890
901
  );
891
- if (qualifiedArgs.length === 0) return { kind: "Identifier", name: operator, location };
892
902
  const argumentCounts = selectors.map((selector) =>
893
903
  "args" in selector ? selector.args.length : 0,
894
904
  );
895
905
  const argumentsRange = lastArguments.range;
896
- return argumentCounts.slice(0, -1).some((count) => count > 0)
897
- ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, argumentsRange, location }
898
- : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
906
+ const reference: Expression =
907
+ names.length < selectors.length
908
+ ? { kind: "Subexpression", selectors, location }
909
+ : qualifiedArgs.length === 0
910
+ ? { kind: "Identifier", name: operator, location }
911
+ : argumentCounts.slice(0, -1).some((count) => count > 0)
912
+ ? {
913
+ kind: "Apply",
914
+ operator,
915
+ args: qualifiedArgs,
916
+ argumentCounts,
917
+ argumentsRange,
918
+ location,
919
+ }
920
+ : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
921
+ if (isMissingArguments) {
922
+ missingArguments.set(reference, {
923
+ location: formatRange(getRange(start)),
924
+ message: `The operator ${name} requires ${instance.params.length} arguments.`,
925
+ });
926
+ }
927
+ return reference;
899
928
  }
900
929
  if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
901
930
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
@@ -1716,6 +1745,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1716
1745
  end: { line: token.line, column: token.endColumn },
1717
1746
  };
1718
1747
  }
1748
+ if (missingArguments.size > 0) throw createSanyError([...missingArguments.values()]);
1719
1749
  openModules.pop();
1720
1750
  recursiveScopes.pop();
1721
1751
  return module;
@@ -135,8 +135,8 @@ export const CORE_OPERATORS: Builtin[] = [
135
135
  }),
136
136
  ...SET_OPERATORS.map((operator) =>
137
137
  defineOperator(operator, 2, (args) => {
138
- const left = getSet(args, 0, operator);
139
- const right = getSet(args, 1, operator);
138
+ const left = getValue(args, 0, operator);
139
+ const right = getValue(args, 1, operator);
140
140
  if (isReducible(left) && isReducible(right) && !isMixedSet(left) && !isMixedSet(right)) {
141
141
  if (operator === "\\cup" && isEmptySet(left)) return right;
142
142
  const merge =
@@ -1,5 +1,5 @@
1
1
  import type { Declaration, Definition, Expression, SourceLocation } from "./ast";
2
- import { TlaSyntaxError } from "./errors";
2
+ import { createSanyError, formatRange } from "./errors";
3
3
  import {
4
4
  createLevelAnalyzer,
5
5
  getArgumentKey,
@@ -108,10 +108,18 @@ export const checkInstances = (
108
108
  return levels;
109
109
  };
110
110
 
111
- const messages = new Set<string>();
111
+ const errors = new Map<string, { location: string; message: string }>();
112
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}`);
113
+ // SANY reports each error at the whole instance.
114
+ const location = formatRange(
115
+ check.location.range ?? {
116
+ module: check.instancer,
117
+ start: check.location,
118
+ end: check.location,
119
+ },
120
+ );
121
+ const addMessage = (message: string) =>
122
+ errors.set(`${location}\n${message}`, { location, message });
115
123
  const instancee = getModule(check.module);
116
124
  const levels = getModuleLevels(check.module);
117
125
  const analyzer = getAnalyzer(check.instancer);
@@ -141,14 +149,14 @@ export const checkInstances = (
141
149
  ];
142
150
  });
143
151
  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}`;
152
+ `Level error in instantiating module '${check.module}':\nThe level of the expression or operator substituted for '${name}' \nmust be at most ${level}.`;
145
153
  substituted.forEach((item) => {
146
154
  if (!levels.isConstant && item.level > item.maximumLevel) {
147
155
  addMessage(getLevelMessage(item.name, item.maximumLevel));
148
156
  }
149
157
  if (!item.isLeibniz) {
150
158
  addMessage(
151
- `Error in instantiating module '${check.module}': a non-Leibniz operator substituted for '${item.name}'`,
159
+ `Error in instantiating module '${check.module}':\n A non-Leibniz operator substituted for '${item.name}'.`,
152
160
  );
153
161
  }
154
162
  });
@@ -162,7 +170,7 @@ export const checkInstances = (
162
170
  const minimum = levels.argConstraints.get(getArgumentKey(item.name, index));
163
171
  if (minimum !== undefined && getMaxLevel(operator, index) < minimum) {
164
172
  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}`,
173
+ `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
174
  );
167
175
  }
168
176
  });
@@ -175,10 +183,10 @@ export const checkInstances = (
175
183
  const maximum = getMaxLevel(operator, parameter.index);
176
184
  if (argument.level > maximum) {
177
185
  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}`,
186
+ `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
187
  );
180
188
  }
181
189
  });
182
190
  });
183
- if (messages.size > 0) throw new TlaSyntaxError([...messages].join("\n"));
191
+ if (errors.size > 0) throw createSanyError([...errors.values()]);
184
192
  };
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++) {