tla-ts 0.0.3-dev.bffbba3 → 0.0.3-dev.c949d82

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/parser.ts CHANGED
@@ -22,7 +22,7 @@ import type {
22
22
  StepBody,
23
23
  UseOrHide,
24
24
  } from "./ast";
25
- import { TlaSyntaxError } from "./errors";
25
+ import { createSanyError, formatRange, TlaSyntaxError } from "./errors";
26
26
  import { getNumeralValue, tokenize, type Token } from "./lexer";
27
27
 
28
28
  interface InfixOperator {
@@ -631,11 +631,15 @@ const parse = (source: string, isTlapm: boolean): Module => {
631
631
  return parseExpression();
632
632
  };
633
633
 
634
+ const lastArguments: { range: SourceRange | undefined } = { range: undefined };
635
+
634
636
  const parseArguments = () =>
635
637
  withoutOffside(() => {
638
+ const start = cursor.index;
636
639
  expect("(");
637
640
  const args = parseSeparated(parseArgument);
638
641
  expect(")");
642
+ lastArguments.range = getRange(start);
639
643
  return args;
640
644
  });
641
645
 
@@ -856,7 +860,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
856
860
  const args = hasArguments ? parseArguments() : [];
857
861
  if (!isSelectorAhead()) {
858
862
  return hasArguments
859
- ? { kind: "Apply", operator: name, args, location }
863
+ ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
860
864
  : { kind: "Identifier", name, location };
861
865
  }
862
866
  const instance = openModules
@@ -885,9 +889,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
885
889
  const argumentCounts = selectors.map((selector) =>
886
890
  "args" in selector ? selector.args.length : 0,
887
891
  );
892
+ const argumentsRange = lastArguments.range;
888
893
  return argumentCounts.slice(0, -1).some((count) => count > 0)
889
- ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, location }
890
- : { kind: "Apply", operator, args: qualifiedArgs, location };
894
+ ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, argumentsRange, location }
895
+ : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
891
896
  }
892
897
  if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
893
898
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
@@ -1423,11 +1428,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
1423
1428
  location: getLocation(keyword),
1424
1429
  };
1425
1430
  const invalid =
1426
- use.kind === "Hide" && !isTlapm ? use.facts.find((fact) => !isHideFact(fact)) : undefined;
1427
- if (invalid) {
1428
- throw createError(
1429
- "The only expression allowed as a fact in a HIDE is the name of a theorem, assumption, or step",
1430
- invalid.location,
1431
+ use.kind === "Hide" && !isTlapm ? use.facts.filter((fact) => !isHideFact(fact)) : [];
1432
+ if (invalid.length > 0) {
1433
+ throw createSanyError(
1434
+ invalid.map((fact) => ({
1435
+ location: formatRange(fact.location.range ?? getRange(start)),
1436
+ message:
1437
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1438
+ })),
1431
1439
  );
1432
1440
  }
1433
1441
  return withRange(use, start);
package/src/resolve.ts CHANGED
@@ -13,9 +13,10 @@ import {
13
13
  type Proof,
14
14
  type ProofStep,
15
15
  type SourceLocation,
16
+ type SourceRange,
16
17
  type Theorem,
17
18
  } from "./ast";
18
- import { TlaSyntaxError } from "./errors";
19
+ import { createSanyError, createSemanticError, formatRange, TlaSyntaxError } from "./errors";
19
20
 
20
21
  export interface ModuleSymbol {
21
22
  key: string;
@@ -103,6 +104,21 @@ const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
103
104
  : unit.imported.get(name);
104
105
  };
105
106
 
107
+ // SANY reports a name at the range of its text.
108
+ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
109
+ module: location.range?.module ?? "",
110
+ start: location,
111
+ end: { line: location.line, column: location.column + name.length - 1 },
112
+ });
113
+
114
+ // SANY reports an operator symbol applied to operands as one it cannot resolve.
115
+ const getFixity = (expression: Expression) => {
116
+ if (expression.kind !== "Apply") return undefined;
117
+ if (expression.args.length === 2) return "infix";
118
+ if (expression.args.length !== 1) return undefined;
119
+ return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
120
+ };
121
+
106
122
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
107
123
  const isOperatorSymbol = (name: string) =>
108
124
  name[0].toLowerCase() === name[0].toUpperCase() &&
@@ -135,7 +151,7 @@ const getSymbolArity = (
135
151
  }
136
152
  // A name such as Inv!P1 selects the label P1 of a definition or theorem, which takes its own
137
153
  // arguments.
138
- const prefix = name.slice(0, name.indexOf("!"));
154
+ const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
139
155
  const isSelected =
140
156
  prefix !== "" &&
141
157
  (lookupLocal(scope, prefix) !== undefined ||
@@ -144,11 +160,23 @@ const getSymbolArity = (
144
160
  if (isSelected) {
145
161
  return expression.kind === "Apply" ? expression.args.length : 0;
146
162
  }
147
- const position = `at line ${location.line}, column ${location.column}`;
148
- throw new TlaSyntaxError(
149
- isOperatorSymbol(name)
150
- ? `Could not find declaration or definition of symbol '${name}' ${position}`
151
- : `Unknown operator: \`${name}' ${position}`,
163
+ const range = getNameRange(location, name === "-." ? "-" : name);
164
+ if (!isOperatorSymbol(name)) throw createSemanticError(`Unknown operator: \`${name}'.`, range);
165
+ const missing = {
166
+ location: formatRange(range),
167
+ message: `Could not find declaration or definition of symbol '${name}'.`,
168
+ };
169
+ const fixity = getFixity(expression);
170
+ throw createSanyError(
171
+ fixity && location.range
172
+ ? [
173
+ missing,
174
+ {
175
+ location: formatRange(location.range),
176
+ message: `Couldn't resolve ${fixity} operator symbol \`${name}'.`,
177
+ },
178
+ ]
179
+ : [missing],
152
180
  );
153
181
  };
154
182
 
@@ -235,13 +263,13 @@ const resolveApply = (
235
263
  scope: LocalName | undefined,
236
264
  unit: Unit,
237
265
  ) => {
238
- const callee = lookupLocal(scope, expression.operator)
239
- ? undefined
240
- : getVisibleDefinition(expression.operator, unit);
241
- const arity = getSymbolArity(expression, expression.operator, scope, unit);
266
+ const operator = expression.operator;
267
+ const callee = lookupLocal(scope, operator) ? undefined : getVisibleDefinition(operator, unit);
268
+ const arity = getSymbolArity(expression, operator, scope, unit);
242
269
  if (arity !== expression.args.length) {
243
- throw new TlaSyntaxError(
244
- `The operator ${expression.operator} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
270
+ throw createSemanticError(
271
+ `The operator ${operator} requires ${arity} arguments.`,
272
+ expression.argumentsRange ?? getNameRange(expression.location, operator),
245
273
  );
246
274
  }
247
275
  expression.args.forEach((arg, index) => {
@@ -275,10 +303,12 @@ const resolveExpression = (
275
303
  case "ExceptAt":
276
304
  return;
277
305
  case "Identifier": {
278
- const arity = getSymbolArity(expression, expression.name, scope, unit);
306
+ const name = expression.name;
307
+ const arity = getSymbolArity(expression, name, scope, unit);
279
308
  if (arity > 0) {
280
- throw new TlaSyntaxError(
281
- `The operator ${expression.name} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
309
+ throw createSemanticError(
310
+ `The operator ${name} requires ${arity} arguments.`,
311
+ getNameRange(expression.location, name),
282
312
  );
283
313
  }
284
314
  return;
package/src/run-cli.ts CHANGED
@@ -14,12 +14,14 @@ import type { CheckResult, CheckStatus, TraceStep } from "./check";
14
14
  import { defineCommand, type ParsedArgs } from "./cli-options";
15
15
  import { parseConfig } from "./config";
16
16
  import {
17
+ createSanyError,
17
18
  getErrorExitCode,
18
19
  TlaConfigError,
19
20
  TlaError,
20
21
  TlaEvaluationError,
21
22
  TlaProofError,
22
23
  TlaSyntaxError,
24
+ type SanyReport,
23
25
  } from "./errors";
24
26
  import { EXIT_STATUS } from "./exit-codes";
25
27
  import type { LineRange } from "./obligation-generate";
@@ -219,8 +221,14 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
219
221
  const fileName = basename(specPath, ".tla");
220
222
  const moduleName = parseModule(source).name;
221
223
  if (moduleName !== fileName) {
222
- throw new TlaSyntaxError(
223
- `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
224
+ throw createSanyError(
225
+ [
226
+ {
227
+ location: "Unknown location",
228
+ message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
229
+ },
230
+ ],
231
+ true,
224
232
  );
225
233
  }
226
234
  const configPath =
@@ -286,21 +294,32 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
286
294
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
287
295
  };
288
296
 
289
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
290
- const printError = (error: TlaError) => {
297
+ const formatSanyErrors = (report: SanyReport) =>
298
+ `*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
299
+
300
+ // TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
301
+ // others, such as a module it cannot parse.
302
+ const printError = (error: TlaError, path?: string) => {
291
303
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
292
304
  return console.log(`Error: ${error.message}`);
293
305
  }
294
- console.error(`${error.name}: ${error.message}`);
306
+ const report = error instanceof TlaSyntaxError ? error.sany : undefined;
307
+ if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
308
+ console.log(
309
+ report.isFatal
310
+ ? `\nFatal errors while parsing TLA+ spec in file ${basename(path, ".tla")}\n\n${report.errors.map((item) => `${item.location}\n\n${item.message}\n`).join("")}${formatSanyErrors(report)}\n`
311
+ : `Semantic errors:\n\n${formatSanyErrors(report)}`,
312
+ );
313
+ console.log("Error: Parsing or semantic analysis failed.");
295
314
  };
296
315
 
297
316
  // Prints a TlaError and returns its exit code.
298
- const reportErrors = async (run: () => number | Promise<number>) => {
317
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
299
318
  try {
300
319
  return await run();
301
320
  } catch (error) {
302
321
  if (!(error instanceof TlaError)) throw error;
303
- printError(error);
322
+ printError(error, path);
304
323
  return getErrorExitCode(error);
305
324
  }
306
325
  };
@@ -311,7 +330,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
311
330
  const exitCodes: number[] = [];
312
331
  for (const [index, path] of paths.entries()) {
313
332
  if (index > 0) console.log("");
314
- exitCodes.push(await reportErrors(() => runPath(path)));
333
+ exitCodes.push(await reportErrors(() => runPath(path), path));
315
334
  }
316
335
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
317
336
  };
@@ -7,13 +7,12 @@ import {
7
7
  } from "./ast";
8
8
  import type { ModelConfig } from "./config";
9
9
  import type { InstanceAction } from "./environment";
10
- import { TlaError } from "./errors";
10
+ import { formatRange, TlaError } from "./errors";
11
11
  import {
12
12
  bindDefinitions,
13
13
  bindOperatorArguments,
14
14
  evaluate,
15
15
  forEachBinding,
16
- formatRange,
17
16
  getDefinition,
18
17
  isConstantLevel,
19
18
  lookupScope,
package/src/successors.ts CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  type QuantifierExpression,
8
8
  } from "./ast";
9
9
  import { getReadVariables } from "./dependencies";
10
- import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
10
+ import { TlaEvaluationError, TlaIncompleteStateError } from "./errors";
11
11
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
12
12
  import {
13
13
  describeLocation,
@@ -89,14 +89,25 @@ const assign = (partial: State, index: number, value: Value) => {
89
89
  return copy;
90
90
  };
91
91
 
92
- const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
92
+ // TLC's Tool.getInitStates and Tool.getNextStates report a value where they expect a formula.
93
+ const expectFormula = (expression: Expression, value: Value, isInit: boolean) => {
93
94
  if (typeof value === "boolean") return value;
94
- try {
95
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
96
- } catch (error) {
97
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
98
- throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
95
+ throw new TlaEvaluationError(
96
+ `In computing ${isInit ? "initial" : "next"} states, TLC expected a boolean expression,\nbut instead found ${formatValue(value)}.\n${describeRange(expression)}`,
97
+ );
98
+ };
99
+
100
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
101
+ // TLC rejects a number in the next-state relation when it splits the relation into actions.
102
+ if (context.next !== undefined && expression.kind === "Number") {
103
+ throw setExitCode(
104
+ new TlaEvaluationError(
105
+ `The next state relation is not a boolean expression.\n${expression.text ?? expression.value}`,
106
+ ),
107
+ EXIT_STATUS.error,
108
+ );
99
109
  }
110
+ return expectFormula(expression, value, context.next === undefined);
100
111
  };
101
112
 
102
113
  const isAssignmentOperator = (operator: string) =>
@@ -391,10 +402,7 @@ const compileConjunction = (
391
402
  };
392
403
 
393
404
  const holdsInInit = (expression: Expression, context: Context) =>
394
- expectBoolean(
395
- evaluate(expression, context),
396
- `the initial predicate at ${describeLocation(expression)}`,
397
- );
405
+ expectFormula(expression, evaluate(expression, context), true);
398
406
 
399
407
  const compileGuard =
400
408
  (expression: Expression): Runner =>
@@ -419,7 +427,7 @@ const compileMembership = (
419
427
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
420
428
  if (!isEnumerable(value)) {
421
429
  throw new TlaEvaluationError(
422
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
430
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
423
431
  );
424
432
  }
425
433
  const elements = getStreamedElements(value);
@@ -866,7 +874,7 @@ const compileAction = (
866
874
  const body = arm?.body ?? other;
867
875
  if (!body)
868
876
  throw new TlaEvaluationError(
869
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
877
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
870
878
  );
871
879
  body(run, scope, partial, action, isFixed, onComplete);
872
880
  };
@@ -1057,8 +1065,10 @@ export const forEachSuccessor = (
1057
1065
  (partial, action) => {
1058
1066
  if (run.isStopped) return;
1059
1067
  if (!isComplete(partial)) {
1060
- throw new TlaEvaluationError(
1061
- `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1068
+ throw new TlaIncompleteStateError(
1069
+ partial,
1070
+ action,
1071
+ getMissingVariables(partial, environment).sort(),
1062
1072
  );
1063
1073
  }
1064
1074
  counter.successors++;
package/src/symmetry.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { TlaConfigError } from "./errors";
1
+ import { TlaConfigError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
2
2
  import { evaluate, type Environment } from "./evaluate";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  compareValues,
5
6
  createFunction,
@@ -47,9 +48,13 @@ const composePermutations = (first: Images, second: Images) => {
47
48
  return composed;
48
49
  };
49
50
 
50
- const toImages = (value: Value, name: string) => {
51
+ // TLC checks the symmetry set outside any phase that reports an error itself.
52
+ const createSymmetryError = (message: string) =>
53
+ setExitCode(new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${message}`), EXIT_STATUS.error);
54
+
55
+ const toImages = (value: Value) => {
51
56
  if (!isFunctionValue(value)) {
52
- throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
57
+ throw createSymmetryError("The symmetry values must be function records.");
53
58
  }
54
59
  const functionValue = toFiniteFunction(value);
55
60
  const permutation: Images = new Map();
@@ -65,8 +70,13 @@ const toImages = (value: Value, name: string) => {
65
70
 
66
71
  export const getSymmetryGroup = (name: string, environment: Environment): Permutation[] => {
67
72
  const definition = environment.definitions.get(name);
73
+ if (definition === undefined && !environment.constants.has(name)) {
74
+ throw new TlaConfigError(
75
+ `The symmetry function ${name} specified in the configuration file\nis not defined in the specification.`,
76
+ );
77
+ }
68
78
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
69
- throw new TlaConfigError(`The symmetry function ${name} must specify a set of permutations`);
79
+ throw createSymmetryError(`The symmetry function ${name} must specify a set of permutations.`);
70
80
  }
71
81
  const value = evaluate(definition.body, {
72
82
  environment,
@@ -75,9 +85,9 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
75
85
  next: undefined,
76
86
  });
77
87
  if (!isSetValue(value) || !isEnumerable(value)) {
78
- throw new TlaConfigError("The symmetry operator must specify a set of functions");
88
+ throw createSymmetryError("The symmetry operator must specify a set of functions.");
79
89
  }
80
- const permutations = toFiniteSet(value).elements.map((element) => toImages(element, name));
90
+ const permutations = toFiniteSet(value).elements.map(toImages);
81
91
  const isDisabled =
82
92
  definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
83
93
  if (isDisabled) return [];
package/src/tableau.ts CHANGED
@@ -289,7 +289,7 @@ const toDisjunctiveNormalForm = (expression: LiveExpression): LiveExpression =>
289
289
  total.value *= normal.operands.length;
290
290
  if (total.value > MAXIMUM_DISJUNCTS) {
291
291
  throw new TlaEvaluationError(
292
- "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form",
292
+ "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form.",
293
293
  );
294
294
  }
295
295
  }
package/src/tlc-module.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { TlaModuleError } from "./errors";
1
+ import { TlaEvaluationError, TlaModuleError } from "./errors";
2
2
  import { EXIT_STATUS } from "./exit-codes";
3
3
  import type { Builtin } from "./evaluate";
4
4
  import { prettyPrint } from "./pretty-print";
@@ -48,7 +48,7 @@ const getRuntimeValue = (
48
48
  state: (Value | undefined)[] | undefined,
49
49
  ) => {
50
50
  if (!runtime.isStarted && CHECKER_KEYS.has(key)) {
51
- throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
51
+ throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
52
52
  }
53
53
  const duration = Math.floor((Date.now() - runtime.startedAt) / 1000);
54
54
  switch (key) {
@@ -104,11 +104,11 @@ const getRuntimeValue = (
104
104
  }
105
105
  if (key.startsWith(NAMED_REGISTER_PREFIX)) {
106
106
  const value = getNamedRegisters(runtime).get(key);
107
- if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
107
+ if (value === undefined) throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
108
108
  return value;
109
109
  }
110
110
  if (key.startsWith("-D")) return rankString(runtime.properties.get(key.slice(2)) ?? key);
111
- throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
111
+ throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
112
112
  };
113
113
 
114
114
  const getPermutations = (elements: Value[]): Value[][] =>
@@ -197,11 +197,11 @@ export const createTlcOperators = (
197
197
  const key = getValue(args, 0, "TLCGet");
198
198
  if (typeof key === "number" && key >= 0) {
199
199
  const value = runtime.registers.get(key);
200
- if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
200
+ if (value === undefined) throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
201
201
  return value;
202
202
  }
203
203
  if (typeof key !== "string") {
204
- throw new TlaModuleError(
204
+ throw new TlaEvaluationError(
205
205
  `The argument of TLCGet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
206
206
  );
207
207
  }
@@ -1013,6 +1013,10 @@ export const TLC_JAVA_METHODS = new Map([
1013
1013
  "RandomElement",
1014
1014
  "public static tlc2.value.impl.Value tlc2.module.TLC.RandomElement(tlc2.value.impl.Value)",
1015
1015
  ],
1016
+ [
1017
+ "TLCGet",
1018
+ "public static tlc2.value.impl.Value tlc2.module.TLCGetSet.TLCGetEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
1019
+ ],
1016
1020
  [
1017
1021
  "TLCEval",
1018
1022
  "public static tlc2.value.impl.Value tlc2.module.TLCEval.tlcEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
package/src/tlc-order.ts CHANGED
@@ -278,9 +278,13 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
278
278
  (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
279
279
  };
280
280
 
281
- // The variables in the order TLC compares them: the reverse of the root module's context
282
- // enumeration, as ModuleNode.getVariableDecls returns them.
283
- export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): string[] => {
281
+ // The constants or variables in the order of ModuleNode.getConstantDecls or getVariableDecls: the
282
+ // reverse of the root module's context enumeration. TLC compares a state's variables in this order.
283
+ export const getTlcDeclarationOrder = (
284
+ source: string,
285
+ loadModule: ModuleLoader,
286
+ kind: "constant" | "variable",
287
+ ): string[] => {
284
288
  const getParsed = createModuleSet(source, loadModule);
285
289
  const getUnits = (unit: ParsedModule) => {
286
290
  const tokens = unit.tokens;
@@ -400,7 +404,7 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
400
404
  };
401
405
  return getContext(undefined)
402
406
  .enumerate()
403
- .filter((entry) => entry.kind === "variable")
407
+ .filter((entry) => entry.kind === kind)
404
408
  .map((entry) => entry.name)
405
409
  .reverse();
406
410
  };
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
 
@@ -87,11 +87,26 @@ export const getFingerprintDistance = (
87
87
  const probability = getOptimisticProbability(distinctStates, generatedStates);
88
88
  if (probability < ACTUAL_PROBABILITY_THRESHOLD) return undefined;
89
89
  const fingerprints = getFingerprints().sort();
90
- return fingerprints.reduce((distance, fingerprint, index) => {
91
- const previous = fingerprints[index - 1];
92
- const isSameSet = index > 0 && previous < 0n === fingerprint < 0n;
93
- return isSameSet && fingerprint - previous < distance ? fingerprint - previous : distance;
94
- }, 0x7fff_ffff_ffff_ffffn);
90
+ // The low and high words of each fingerprint. A gap whose high words differ by at most 2^20 is
91
+ // below 2^53, so a number holds it exactly and only wider gaps need a BigInt.
92
+ const words = new Int32Array(fingerprints.buffer);
93
+ const nearest = { narrow: Number.POSITIVE_INFINITY, wide: 0x7fff_ffff_ffff_ffffn };
94
+ for (let index = 1; index < fingerprints.length; index++) {
95
+ const high = words[2 * index + 1];
96
+ const previousHigh = words[2 * index - 1];
97
+ if (high < 0 !== previousHigh < 0) continue;
98
+ const highGap = high - previousHigh;
99
+ if (highGap <= 0x10_0000) {
100
+ const gap = highGap * 0x1_0000_0000 + (words[2 * index] >>> 0) - (words[2 * index - 2] >>> 0);
101
+ nearest.narrow = Math.min(nearest.narrow, gap);
102
+ } else {
103
+ const gap = fingerprints[index] - fingerprints[index - 1];
104
+ if (gap < nearest.wide) nearest.wide = gap;
105
+ }
106
+ }
107
+ if (nearest.narrow === Number.POSITIVE_INFINITY) return nearest.wide;
108
+ const narrow = BigInt(nearest.narrow);
109
+ return narrow < nearest.wide ? narrow : nearest.wide;
95
110
  };
96
111
 
97
112
  export const getOutDegreeSummary = (buckets: number[]) => {