tla-ts 0.0.10-dev.b4a856304 → 0.0.10-dev.f16792fed

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.
Files changed (72) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +34 -0
  3. package/dist/index.d.ts +34 -0
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +1 -1
  7. package/dist/prove.cjs +48 -48
  8. package/dist/prove.js +29 -29
  9. package/dist/run.cjs +40 -40
  10. package/dist/run.js +31 -31
  11. package/dist/transfer.cjs +36 -36
  12. package/dist/transfer.js +40 -40
  13. package/package.json +1 -1
  14. package/src/ast.ts +0 -5
  15. package/src/bags.ts +2 -5
  16. package/src/builtins.ts +1 -8
  17. package/src/check.ts +128 -193
  18. package/src/cli/options.ts +1 -1
  19. package/src/cli/run.ts +0 -2
  20. package/src/cli/runtime-invariants.ts +8 -7
  21. package/src/cli/shared.ts +0 -4
  22. package/src/cli/tlc-arguments.ts +24 -30
  23. package/src/cli/tlc-usage.ts +2 -3
  24. package/src/coverage.ts +3 -8
  25. package/src/evaluate.ts +26 -102
  26. package/src/java-hash.ts +7 -0
  27. package/src/java-overrides.ts +4 -9
  28. package/src/json-reader.ts +1 -2
  29. package/src/json.ts +4 -11
  30. package/src/levels.ts +7 -15
  31. package/src/lexer.ts +72 -83
  32. package/src/liveness-checker.ts +77 -106
  33. package/src/liveness.ts +10 -34
  34. package/src/parallel.ts +26 -33
  35. package/src/parser.ts +163 -226
  36. package/src/pcal/ast.ts +53 -65
  37. package/src/pcal/parse.ts +144 -191
  38. package/src/pcal/tokenize.ts +91 -115
  39. package/src/pcal/translate.ts +83 -98
  40. package/src/pcal/validate.ts +48 -50
  41. package/src/pretty-print.ts +6 -6
  42. package/src/randomization.ts +1 -4
  43. package/src/resolve.ts +12 -70
  44. package/src/runtime.ts +11 -18
  45. package/src/sany/builtins.ts +1 -3
  46. package/src/sany/generator.ts +74 -127
  47. package/src/sany/levels.ts +5 -9
  48. package/src/sany/lexer.ts +40 -44
  49. package/src/sany/linter.ts +0 -1
  50. package/src/sany/nodes.ts +4 -10
  51. package/src/search.ts +1 -1
  52. package/src/simulate.ts +50 -59
  53. package/src/spec-description.ts +23 -34
  54. package/src/standard-definitions.ts +0 -3
  55. package/src/standard-modules.ts +1 -12
  56. package/src/state-graph.ts +3 -15
  57. package/src/subexpressions.ts +38 -47
  58. package/src/successors.ts +14 -35
  59. package/src/symmetry.ts +4 -19
  60. package/src/tlc/fingerprint.ts +15 -21
  61. package/src/tlc/jar-data.ts +0 -1
  62. package/src/tlc/messages.ts +2 -21
  63. package/src/tlc/order.ts +22 -47
  64. package/src/tlc/random.ts +18 -30
  65. package/src/tlc/replay.ts +13 -33
  66. package/src/tlc/summary.ts +36 -45
  67. package/src/tlc/tlc-operators.ts +4 -14
  68. package/src/tlc/tlcext-operators.ts +11 -15
  69. package/src/tlc/trace-spec.ts +4 -9
  70. package/src/tlc/value-stream.ts +9 -13
  71. package/src/tlc/version.ts +0 -1
  72. package/src/values.ts +74 -186
@@ -23,13 +23,10 @@ type PcalValidationResult =
23
23
  // Java's \s, which unlike JavaScript's matches no Unicode spaces.
24
24
  const SPACE = "[ \\t\\n\\x0B\\f\\r]";
25
25
 
26
- // Validator.CHECKSUM_PATTERN, whose (?i) groups become character classes.
27
26
  const CHECKSUM_PATTERN = new RegExp(
28
27
  `\\\\\\* BEGIN TRANSLATION${SPACE}+\\(${SPACE}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${SPACE}*(=${SPACE}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${SPACE}*STRING)${SPACE}*\\/\\\\${SPACE}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${SPACE}*(=${SPACE}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${SPACE}*STRING)${SPACE}*\\)`,
29
28
  );
30
29
 
31
- // CRC32 in Long.toHexString's unpadded lowercase hex. Only a spec with PlusCal needs node:zlib,
32
- // so it loads then rather than at startup.
33
30
  const getChecksum = (text: string) =>
34
31
  process.getBuiltinModule("node:zlib").crc32(Buffer.from(text, "utf8")).toString(16);
35
32
 
@@ -44,7 +41,6 @@ const reportPcalError = (session: PcalSession, error: PcalError) =>
44
41
  : `${error.message}\n at ${getPcalLocation(error.node)}`,
45
42
  );
46
43
 
47
- // trans.removeTabs: tabs reach the next multiple of 8, and every line gets a trailing space.
48
44
  const removeTabs = (lines: string[]) =>
49
45
  lines.map(
50
46
  (line) =>
@@ -108,14 +104,14 @@ const findToken = (lines: string[], location: PcalSearchLocation, token: string)
108
104
  const reportCommandLineError = (session: PcalSession, message: string) =>
109
105
  reportUnrecoverableError(session, `Command-line error: ${message}`);
110
106
 
111
- // These options set the translator's options for the rest of SANY's run.
112
107
  const processOptionArguments = (session: PcalSession, args: string[]) => {
113
108
  const params = session.params;
114
- const fairness = { isFirst: true, isExplicitNof: false };
109
+ let isFirstFairness = true;
110
+ let isExplicitNof = false;
115
111
  const setFairness = (option: string) => {
116
- if (fairness.isFirst) {
112
+ if (isFirstFairness) {
117
113
  params.fairnessOption = "";
118
- fairness.isFirst = false;
114
+ isFirstFairness = false;
119
115
  }
120
116
  if (params.fairnessOption !== "") {
121
117
  reportCommandLineError(session, "Can only have one of -wf, -sf, -wfNext, and -nof options");
@@ -169,7 +165,7 @@ const processOptionArguments = (session: PcalSession, args: string[]) => {
169
165
  case "-nof":
170
166
  case "nof":
171
167
  if (!setFairness(option.replace(/^-/, ""))) return;
172
- if (option.endsWith("nof")) fairness.isExplicitNof = true;
168
+ if (option.endsWith("nof")) isExplicitNof = true;
173
169
  continue;
174
170
  case "-label":
175
171
  case "label":
@@ -213,7 +209,6 @@ const processOptionArguments = (session: PcalSession, args: string[]) => {
213
209
  continue;
214
210
  }
215
211
  case "-lineWidth":
216
- // PcalTLAGen's line width only shapes the translation's text.
217
212
  if (!/^[+-]?\d+$/.test(argument ?? "") || Number(argument) < 60) {
218
213
  reportCommandLineError(
219
214
  session,
@@ -231,7 +226,7 @@ const processOptionArguments = (session: PcalSession, args: string[]) => {
231
226
  return;
232
227
  }
233
228
  }
234
- if (params.checkTermination && params.fairnessOption === "" && !fairness.isExplicitNof) {
229
+ if (params.checkTermination && params.fairnessOption === "" && !isExplicitNof) {
235
230
  params.fairnessOption = "wf";
236
231
  }
237
232
  };
@@ -265,56 +260,56 @@ const processOptions = (session: PcalSession, lines: string[], location: PcalSea
265
260
  };
266
261
 
267
262
  const uncomment = (lines: string[], startLine: number, startColumn: number) => {
268
- const scan = { depth: 0, isDone: false, isInString: false };
269
- for (let index = startLine; !scan.isDone && index < lines.length; index++) {
263
+ let depth = 0;
264
+ let isDone = false;
265
+ let isInString = false;
266
+ for (let index = startLine; !isDone && index < lines.length; index++) {
270
267
  const line = lines[index];
271
268
  const start = index === startLine ? startColumn : 0;
272
269
  const output = [line.slice(0, start)];
273
- scan.isInString = false;
274
- for (let column = start; !scan.isDone && column < line.length; column++) {
270
+ isInString = false;
271
+ for (let column = start; !isDone && column < line.length; column++) {
275
272
  const char = line[column];
276
273
  const pair = line.slice(column, column + 2);
277
- if (pair === "(*" && !scan.isInString) {
278
- scan.depth += 1;
274
+ if (pair === "(*" && !isInString) {
275
+ depth += 1;
279
276
  output.push(" ");
280
277
  column += 1;
281
278
  continue;
282
279
  }
283
- if (pair === "*)" && !scan.isInString && scan.depth === 0) {
280
+ if (pair === "*)" && !isInString && depth === 0) {
284
281
  output.push(pair);
285
- scan.isDone = true;
282
+ isDone = true;
286
283
  continue;
287
284
  }
288
- if (pair === "*)" && !scan.isInString) {
289
- scan.depth -= 1;
285
+ if (pair === "*)" && !isInString) {
286
+ depth -= 1;
290
287
  output.push(" ");
291
288
  column += 1;
292
289
  continue;
293
290
  }
294
- if (scan.depth > 0) {
291
+ if (depth > 0) {
295
292
  output.push(" ");
296
293
  continue;
297
294
  }
298
- if (scan.isInString && char === "\\" && pair.length === 2) {
295
+ if (isInString && char === "\\" && pair.length === 2) {
299
296
  output.push(pair);
300
297
  column += 1;
301
298
  continue;
302
299
  }
303
- if (!scan.isInString && pair === "\\*") {
300
+ if (!isInString && pair === "\\*") {
304
301
  output.push(" ");
305
302
  break;
306
303
  }
307
- if (char === '"') scan.isInString = !scan.isInString;
304
+ if (char === '"') isInString = !isInString;
308
305
  output.push(char);
309
306
  }
310
- if (scan.isInString) return new PcalError(`Unterminated string in line ${index + 1}`);
307
+ if (isInString) return new PcalError(`Unterminated string in line ${index + 1}`);
311
308
  lines[index] = output.join("");
312
309
  }
313
310
  return undefined;
314
311
  };
315
312
 
316
- // Vector.get on an index out of its range, whose message names the vector's capacity: the 10 it
317
- // starts with, doubled as it grows.
318
313
  const throwIndexOutOfBounds = (index: number, size: number): never => {
319
314
  const capacity = 10 * 2 ** Math.max(0, Math.ceil(Math.log2(size / 10)));
320
315
  throw new PcalRuntimeError(
@@ -341,23 +336,22 @@ export const validatePcalModule = (
341
336
  break;
342
337
  }
343
338
  }
344
- const begin = { line: 0, column: -1, isFound: false, isFair: false };
345
- for (; begin.line < lines.length; begin.line++) {
346
- const line = lines[begin.line];
347
- // TLAConstants.MODULE_CLOSING_REGEX, which the trailing space removeTabs adds keeps from
348
- // matching.
339
+ let beginLine = 0;
340
+ let beginColumn = -1;
341
+ let isFair = false;
342
+ for (; beginLine < lines.length; beginLine++) {
343
+ const line = lines[beginLine];
344
+ // TLAConstants.MODULE_CLOSING_REGEX never matches: removeTabs adds a trailing space.
349
345
  if (/^=+$/.test(line)) break;
350
346
  const algorithmColumn = line.indexOf("--algorithm");
351
347
  const fairColumn = line.indexOf("--fair");
352
348
  if (algorithmColumn !== -1) {
353
- begin.column = algorithmColumn + "--algorithm".length;
354
- begin.isFound = true;
349
+ beginColumn = algorithmColumn + "--algorithm".length;
355
350
  break;
356
351
  }
357
352
  if (fairColumn !== -1) {
358
- begin.column = fairColumn + "--fair".length;
359
- begin.isFound = true;
360
- begin.isFair = true;
353
+ beginColumn = fairColumn + "--fair".length;
354
+ isFair = true;
361
355
  break;
362
356
  }
363
357
  }
@@ -367,26 +361,31 @@ export const validatePcalModule = (
367
361
  const endTranslationLine = findTokenPair(lines, translationLine + 1, "END", "TRANSLATION");
368
362
  if (endTranslationLine === -1) results.add("NO_TRANSLATION_EXISTS");
369
363
  if (translationLine === -1 && endTranslationLine === -1) return results;
370
- if (!begin.isFound) {
364
+ if (beginColumn === -1) {
371
365
  results.add("NO_PLUSCAL_EXISTS");
372
366
  return results;
373
367
  }
374
- const uncommentError = uncomment(lines, begin.line, begin.column);
368
+ const uncommentError = uncomment(lines, beginLine, beginColumn);
375
369
  if (uncommentError !== undefined) {
376
370
  reportPcalError(session, uncommentError);
377
371
  return new Set(["ERROR_ENCOUNTERED"]);
378
372
  }
379
- const parsed: { ast: PcalAlgorithm | undefined } = { ast: undefined };
373
+ let ast: PcalAlgorithm | undefined;
380
374
  // HACK: Validator reports the exceptions of ParseAlgorithm.getAlgorithm and PCalTLAGenerator
381
375
  // and goes on to compare the checksums.
382
376
  try {
383
377
  const result = parsePcalAlgorithm(
384
378
  session,
385
- createPcalCharReader(lines, begin.line, begin.column),
386
- begin.isFair,
379
+ createPcalCharReader(lines, beginLine, beginColumn),
380
+ isFair,
381
+ );
382
+ ast = result.ast;
383
+ translatePcalAlgorithm(
384
+ result.ast,
385
+ result.shouldOmitPC,
386
+ result.hasDefaultInitialization,
387
+ session.log,
387
388
  );
388
- parsed.ast = result.ast;
389
- translatePcalAlgorithm(result.ast, result.omitPC, result.hasDefaultInitialization, session.log);
390
389
  } catch (error) {
391
390
  if (!(error instanceof PcalError)) throw error;
392
391
  reportPcalError(session, error);
@@ -398,14 +397,13 @@ export const validatePcalModule = (
398
397
  return results;
399
398
  }
400
399
  const pcalChecksum = match.groups?.pcal;
401
- // The Java checksums the string "fair" for a --fair algorithm, unlike TLC 1.7.4's, and a failed
402
- // parse leaves an AST whose text, Object.toString's class name and hash code, matches no checksum.
400
+ // The Java checksums the string "fair" for a --fair algorithm, unlike TLC 1.7.4's.
403
401
  const algorithmText =
404
- begin.isFair && version !== "1.7.4"
402
+ isFair && version !== "1.7.4"
405
403
  ? "fair"
406
- : parsed.ast === undefined
404
+ : ast === undefined
407
405
  ? undefined
408
- : formatPcalNode(parsed.ast, session.params.inputVersionNumber, version);
406
+ : formatPcalNode(ast, session.params.inputVersionNumber, version);
409
407
  if (
410
408
  pcalChecksum !== undefined &&
411
409
  (algorithmText === undefined || pcalChecksum !== getChecksum(algorithmText))
@@ -78,9 +78,9 @@ const parsePrinted = (text: string) => {
78
78
  separator: string,
79
79
  ) => {
80
80
  const node: PrintedNode = { kind, first, last: first, children: [] };
81
- const position = { index: skipWhitespace(start) };
82
- while (position.index !== undefined && text[position.index] !== close) {
83
- const item = parseItem(position.index);
81
+ let position = skipWhitespace(start);
82
+ while (position !== undefined && text[position] !== close) {
83
+ const item = parseItem(position);
84
84
  if (!item) return undefined;
85
85
  node.children.push(item);
86
86
  const afterItem = skipWhitespace(item.last + 1);
@@ -88,10 +88,10 @@ const parsePrinted = (text: string) => {
88
88
  const afterSeparator = text.startsWith(separator, afterItem)
89
89
  ? afterItem + separator.length
90
90
  : afterItem;
91
- position.index = skipWhitespace(afterSeparator);
91
+ position = skipWhitespace(afterSeparator);
92
92
  }
93
- if (position.index === undefined) return undefined;
94
- node.last = position.index;
93
+ if (position === undefined) return undefined;
94
+ node.last = position;
95
95
  return node;
96
96
  };
97
97
 
@@ -126,10 +126,7 @@ export const createRandomSubsetSet = (runtime: CheckerRuntime) =>
126
126
  export const createRandomizationOperators = (runtime: CheckerRuntime): Builtin[] => [
127
127
  overrideWithJava(
128
128
  defineOperator("RandomSubset", 2, (args) => {
129
- const count = getValue(args, 0, "RandomSubset");
130
- if (typeof count !== "number" || count < 0) {
131
- throw createModuleArgumentError("first", "RandomSubset", "nonnegative integer", count);
132
- }
129
+ const count = getCount(getValue(args, 0, "RandomSubset"), "first", "RandomSubset");
133
130
  const set = getValue(args, 1, "RandomSubset");
134
131
  if (!isTlcEnumerable(set) || !isFiniteSet(set)) {
135
132
  throw createModuleArgumentError("second", "RandomSubset", "a finite set", set);
package/src/resolve.ts CHANGED
@@ -22,7 +22,6 @@ import {
22
22
  } from "./ast";
23
23
  import { formatRange, TlaSyntaxError, type SanyError } from "./errors";
24
24
 
25
- // A parameter is also a bound name, and a NEW symbol has a kind for each level.
26
25
  export type SymbolKind =
27
26
  | "Builtin"
28
27
  | "Constant"
@@ -33,7 +32,6 @@ export type SymbolKind =
33
32
  | "Parameter"
34
33
  | `New${NewSymbol["level"]}`;
35
34
 
36
- // Two symbols at one range are one node to SANY.
37
35
  interface Binding {
38
36
  kind: SymbolKind;
39
37
  arity: number;
@@ -53,9 +51,6 @@ interface Goal {
53
51
  isInProof: boolean;
54
52
  }
55
53
 
56
- // isPending holds for an operator a RECURSIVE declaration names until its definition.
57
- // isNonFact holds for the name of a USE, HIDE, DEFINE or INSTANCE step, which SANY takes neither as
58
- // a fact nor as an expression.
59
54
  interface LocalName extends Binding {
60
55
  name: string;
61
56
  parent: LocalName | undefined;
@@ -111,7 +106,6 @@ const renamedArities = new WeakMap<Expression, number>();
111
106
 
112
107
  export const KEY_SEPARATOR = "@";
113
108
 
114
- // A key is a name, the separator, and an id, so the operator @@ is not one.
115
109
  const isKey = (name: string) => {
116
110
  const index = name.lastIndexOf(KEY_SEPARATOR);
117
111
  return index > 0 && index < name.length - 1;
@@ -151,7 +145,6 @@ const getModuleBinding = (name: string, unit: Unit, range: SourceRange | undefin
151
145
  const isSameRange = (left: SourceRange | undefined, right: SourceRange | undefined) =>
152
146
  left !== undefined && right !== undefined && formatRange(left) === formatRange(right);
153
147
 
154
- // A symbol SANY never sees, such as a generated one, binds.
155
148
  const isBindable = (name: string, current: Binding | undefined, added: Binding, unit: Unit) => {
156
149
  if (current === undefined) return true;
157
150
  if (isSameRange(current.range, added.range)) return false;
@@ -266,7 +259,6 @@ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
266
259
  end: { line: location.line, column: location.column + name.length - 1 },
267
260
  });
268
261
 
269
- // SANY reports a name at its tokens, such as M ! ⊕ for M!\oplus.
270
262
  const getSpelledNameRange = (
271
263
  expression: Expression & { kind: "Identifier" | "Apply" | "OperatorReference" },
272
264
  name: string,
@@ -278,7 +270,6 @@ const getSpelledNameRange = (
278
270
  : getNameRange(expression.location, expression.spelling ?? name);
279
271
  };
280
272
 
281
- // SANY reports an operator symbol applied to operands as one it cannot resolve.
282
273
  const getFixity = (expression: Expression) => {
283
274
  if (expression.kind !== "Apply") return undefined;
284
275
  if (expression.args.length === 2) return "infix";
@@ -286,7 +277,6 @@ const getFixity = (expression: Expression) => {
286
277
  return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
287
278
  };
288
279
 
289
- // SANY names an undefined operator symbol such as + differently from an undefined identifier.
290
280
  const isOperatorSymbol = (name: string) => !/^[\p{L}\d_]/u.test(name);
291
281
 
292
282
  const isStepName = (name: string) =>
@@ -305,7 +295,7 @@ export const getNameSelectors = (
305
295
  ): Selector[] => {
306
296
  const parts = name.split("!");
307
297
  const partCounts =
308
- counts ?? parts.map((_, index) => (index === parts.length - 1 ? args.length : 0));
298
+ counts ?? parts.map((_part, index) => (index === parts.length - 1 ? args.length : 0));
309
299
  return parts.map((part, index) => {
310
300
  const start = partCounts.slice(0, index).reduce((sum, count) => sum + count, 0);
311
301
  return { kind: "Name", name: part, args: args.slice(start, start + partCounts[index]) };
@@ -434,7 +424,6 @@ const findLabel = (expression: Expression, name: string): LabelExpression | unde
434
424
  );
435
425
  };
436
426
 
437
- // SANY drops a label in the scope of a NEW in a nested ASSUME, after it reports the label.
438
427
  const findClauseLabel = (
439
428
  clause: Expression | NewSymbol | AssumeProve,
440
429
  name: string,
@@ -460,9 +449,6 @@ const getOperandName = (operand: number | "<<" | ">>") =>
460
449
 
461
450
  const SCOPE_MESSAGE = "within the scope of a declaration\n from outside that declaration's scope.";
462
451
 
463
- // A part in the scope of a NEW in its ASSUME may be selected only within the theorem's proof, or
464
- // only after the proof of a SUFFICES step. A label takes its own arguments, and an operand must
465
- // exist, unless the part selected depends on bound names.
466
452
  const checkSelection = (
467
453
  reference: Reference,
468
454
  selectors: Selector[],
@@ -600,7 +586,6 @@ const checkSelection = (
600
586
  }
601
587
  };
602
588
 
603
- // Generator.generateLabel reports a label where it may not appear, and skips the label's body.
604
589
  const isLabelReported = (label: LabelExpression, unit: Unit) => {
605
590
  const message = unit.isGenerated
606
591
  ? undefined
@@ -616,9 +601,6 @@ const isLabelReported = (label: LabelExpression, unit: Unit) => {
616
601
  return true;
617
602
  };
618
603
 
619
- // Generator.generateLabel reports, after the label's body, each parameter that names no bound name,
620
- // then formalParamsEqual each parameter given twice, each name bound since the label scope began
621
- // that the label leaves out, and the parameters it adds, and then a label of a name already used.
622
604
  const checkLabel = (label: LabelExpression, scope: LocalName | undefined, unit: Unit) => {
623
605
  const range = label.location.range;
624
606
  if (!range || unit.isGenerated) return;
@@ -683,9 +665,6 @@ const checkReference = (
683
665
  return goal !== undefined;
684
666
  };
685
667
 
686
- // Generator.selectorToNode reports an unknown operator and goes on without analyzing its arguments,
687
- // so its arity is undefined. It does the same for an operator given the wrong number of arguments,
688
- // and for a name that selects nothing, after the arguments of the parts before.
689
668
  const getSymbolArity = (
690
669
  expression: Expression & { kind: "Identifier" | "Apply" | "OperatorReference" },
691
670
  name: string,
@@ -717,8 +696,6 @@ const getSymbolArity = (
717
696
  renamedArities.set(expression, symbol.arity);
718
697
  return symbol.arity;
719
698
  }
720
- // A name such as Inv!P1 selects the label P1 of a definition or theorem, which takes its own
721
- // arguments.
722
699
  const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
723
700
  const isSelected =
724
701
  prefix !== "" &&
@@ -772,9 +749,6 @@ const markRecursiveConstructions = (expression: Expression, name: string): void
772
749
  getChildren(expression).forEach((child) => markRecursiveConstructions(child, name));
773
750
  };
774
751
 
775
- // SANY binds the parameters, reports a name already bound unless a RECURSIVE declaration of this
776
- // level awaits the definition, analyzes the body, and then binds the name. A function binds the
777
- // bound names before it looks up the name, and binds the name only where nothing else does.
778
752
  const resolveDefinition = (
779
753
  definition: Definition,
780
754
  scope: LocalName | undefined,
@@ -833,8 +807,6 @@ const resolveDefinition = (
833
807
  );
834
808
  };
835
809
 
836
- // SANY analyzes an INSTANCE in a LET where it appears, before the definitions that follow it, which
837
- // tla-ts generates at its location and analyzes without reporting.
838
810
  const resolveDefinitions = (
839
811
  definitions: Definition[],
840
812
  scope: LocalName | undefined,
@@ -893,7 +865,6 @@ const resolveDefinitions = (
893
865
  return resolveInstances(resolved, () => true);
894
866
  };
895
867
 
896
- // The INSTANCE that a name such as K!C starts with, whose arguments SANY requires at its name.
897
868
  const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) => {
898
869
  const prefix = name.split("!")[0];
899
870
  const binding =
@@ -903,8 +874,6 @@ const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) =>
903
874
  return binding?.kind === "Instance" ? { name: prefix, arity: binding.arity } : undefined;
904
875
  };
905
876
 
906
- // SANY reports an INSTANCE given the wrong number of arguments at its name, as in K!C or
907
- // K(1, 2)!C, and goes on without analyzing them.
908
877
  const isInstanceArityReported = (
909
878
  expression: Expression,
910
879
  scope: LocalName | undefined,
@@ -930,9 +899,7 @@ const isInstanceArityReported = (
930
899
  return true;
931
900
  };
932
901
 
933
- // OpDefNode#match reports each argument that gives no operator of the parameter's arity, or one
934
- // whose own parameters take operators. tla-ts lets an operator whose parameters it does not know
935
- // take any argument.
902
+ // Deviation from SANY: an operator whose parameters tla-ts does not know takes any argument.
936
903
  const resolveApply = (
937
904
  expression: Expression & { kind: "Apply" },
938
905
  scope: LocalName | undefined,
@@ -963,8 +930,7 @@ const resolveApply = (
963
930
  const expected = params[index] ?? 0;
964
931
  const range = arg.location.range;
965
932
  if (expected === 0) {
966
- // SANY fails on an operator here with an internal error, so tla-ts words it as it does for
967
- // a name.
933
+ // Deviation from SANY: SANY fails here with an internal error; tla-ts words it as for a name.
968
934
  if (arg.kind === "Lambda" && arg.operator !== undefined) {
969
935
  report(range, `The operator ${arg.operator} requires 1 arguments.`);
970
936
  } else if (arg.kind === "Lambda" && range) {
@@ -977,7 +943,6 @@ const resolveApply = (
977
943
  } else resolveExpression(arg, scope, unit);
978
944
  return true;
979
945
  }
980
- // A name that selects a subexpression gives an operator of the names it leaves unbound.
981
946
  if (arg.kind === "Lambda") {
982
947
  resolveExpression(arg, scope, unit);
983
948
  const isMatched = arg.params.length === expected;
@@ -998,13 +963,11 @@ const resolveApply = (
998
963
  resolveExpression(arg, scope, unit);
999
964
  return true;
1000
965
  }
1001
- // Generator.selectorToNode: a name such as K(1)!C names an operator, but none of its parts
1002
- // may take arguments.
1003
966
  if (arg.kind === "Apply" && arg.argumentCounts?.at(-1) === 0) {
1004
- const index = arg.argumentCounts.findIndex((count) => count > 0);
967
+ const selectorIndex = arg.argumentCounts.findIndex((count) => count > 0);
1005
968
  report(
1006
- arg.selectorRanges?.[index],
1007
- `Selector \`${arg.operator.split("!")[index]}' should not have argument(s).`,
969
+ arg.selectorRanges?.[selectorIndex],
970
+ `Selector \`${arg.operator.split("!")[selectorIndex]}' should not have argument(s).`,
1008
971
  );
1009
972
  return false;
1010
973
  }
@@ -1216,8 +1179,6 @@ const resolveExpression = (
1216
1179
  }
1217
1180
  };
1218
1181
 
1219
- // A fact that is a name may also select an ASSUME/PROVE or a NEW clause or name a theorem or
1220
- // assumption. SANY analyzes any other fact as an expression.
1221
1182
  const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) =>
1222
1183
  facts.forEach((fact) => {
1223
1184
  if (
@@ -1247,8 +1208,6 @@ const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit:
1247
1208
  );
1248
1209
  };
1249
1210
 
1250
- // The NEW symbols of an ASSUME stay in scope for its conclusion and the proof that follows. SANY
1251
- // forbids a label in the scope of a NEW in a nested ASSUME.
1252
1211
  const resolveAssumeProve = (
1253
1212
  assumeProve: AssumeProve,
1254
1213
  scope: LocalName | undefined,
@@ -1291,7 +1250,6 @@ const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, ou
1291
1250
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
1292
1251
  };
1293
1252
 
1294
- // A LET or a step binds the name of the INSTANCE after the names it adds.
1295
1253
  const resolveLocalInstance = (instance: Instance, scope: LocalName | undefined, unit: Unit) => {
1296
1254
  const instanced = resolveInstance(instance, scope, unit);
1297
1255
  return instance.name === undefined
@@ -1304,8 +1262,6 @@ const resolveLocalInstance = (instance: Instance, scope: LocalName | undefined,
1304
1262
  );
1305
1263
  };
1306
1264
 
1307
- // Generator.generateProof binds the name of a step after its statement and before its proof, or
1308
- // after the step where it takes no proof.
1309
1265
  const resolveStep = (
1310
1266
  step: ProofStep,
1311
1267
  scope: LocalName | undefined,
@@ -1323,8 +1279,6 @@ const resolveStep = (
1323
1279
  ? parent
1324
1280
  : { name: step.name, arity: 0, kind: "Theorem", parent, isNonFact: true };
1325
1281
  switch (body.kind) {
1326
- // The NEW symbols of a SUFFICES ASSUME are in scope after its proof, and those of any other
1327
- // ASSUME in its proof.
1328
1282
  case "Assert": {
1329
1283
  const assumed = resolveStatement(body.statement, scope, stepUnit);
1330
1284
  const proofScope = body.isSuffices ? scope : assumed;
@@ -1391,7 +1345,6 @@ const resolveStep = (
1391
1345
  }
1392
1346
  };
1393
1347
 
1394
- // SANY binds the name of a theorem after its statement and before its proof.
1395
1348
  const resolveTheorem = (theorem: Theorem, unit: Unit) => {
1396
1349
  const isDefinition = theorem.name !== undefined && theorem.statement.kind !== "AssumeProve";
1397
1350
  const scope = isDefinition ? undefined : resolveStatement(theorem.statement, undefined, unit);
@@ -1434,7 +1387,6 @@ export interface ModuleUnit {
1434
1387
 
1435
1388
  export const MODULE_START: SourceLocation = { line: 0, column: 0 };
1436
1389
 
1437
- // A named theorem or assumption is linked as a definition too.
1438
1390
  export const isTheoremDefinition = (module: Module, definition: Definition) =>
1439
1391
  [...module.theorems, ...module.assumptions].some(
1440
1392
  (item) =>
@@ -1454,9 +1406,6 @@ const createSymbols = (module: Module, imported: Symbols) => {
1454
1406
  return symbols;
1455
1407
  };
1456
1408
 
1457
- // Generator.processSubst analyzes the explicit substitutions in the order they appear, then the
1458
- // implicit ones, and then reports each declaration left without one. The parameters of the INSTANCE
1459
- // are in scope.
1460
1409
  const checkSubstitutions = (
1461
1410
  instance: Instance,
1462
1411
  declarations: Declaration[],
@@ -1529,8 +1478,6 @@ const checkSubstitutions = (
1529
1478
  return substitutions;
1530
1479
  };
1531
1480
 
1532
- // Generator.processSubst analyzes an INSTANCE in a LET or a proof, which then binds the names the
1533
- // INSTANCE adds.
1534
1481
  const resolveInstance = (instance: Instance, scope: LocalName | undefined, unit: Unit) => {
1535
1482
  const instanced = unit.getInstance(instance);
1536
1483
  checkSubstitutions(instance, instanced.declarations, instanced.instancer, scope, unit);
@@ -1572,16 +1519,12 @@ export const resolveSubstitutions = (
1572
1519
  });
1573
1520
  };
1574
1521
 
1575
- // SANY reports the errors of every unit in the order of the units, after the warnings. A unit
1576
- // reports what SANY goes on after, and throws the error that stops it. An error tla-ts cannot
1577
- // word as SANY does yields to the errors the unit reported before it.
1578
- export const collectSemanticErrors = (
1579
- units: {
1580
- location: SourceLocation;
1581
- check: (reported: SanyError[], warned: SanyError[]) => void;
1582
- }[],
1583
- warnings: SanyError[],
1584
- ) => {
1522
+ interface SemanticUnit {
1523
+ location: SourceLocation;
1524
+ check: (reported: SanyError[], warned: SanyError[]) => void;
1525
+ }
1526
+
1527
+ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError[]) => {
1585
1528
  const errors: SanyError[] = [];
1586
1529
  const addUnique = (list: SanyError[], item: SanyError) => {
1587
1530
  if (
@@ -1617,7 +1560,6 @@ export const collectSemanticErrors = (
1617
1560
  return errors;
1618
1561
  };
1619
1562
 
1620
- // SANY reports a RECURSIVE declaration that no definition follows at the end.
1621
1563
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
1622
1564
  const symbols = createSymbols(module, unit.imported);
1623
1565
  const facts = new Set([
package/src/runtime.ts CHANGED
@@ -20,11 +20,7 @@ export interface CheckerRuntime {
20
20
  evaluateAtStartup: <Result>(evaluate: () => Result) => Result;
21
21
  pause: (() => void) | undefined;
22
22
  warn: (code: number, text: string) => void;
23
- // TLC's -nowarning turns the warnings off, and with them the shortcut that evaluates the rest
24
- // of an action once it assigns every variable, since that shortcut skips a warning.
25
23
  isWarningEnabled: boolean;
26
- // TLC's -tool, under which the message of an error that TLC raises with a code holds the
27
- // code's markers, which AssertError compares with.
28
24
  isTool: boolean;
29
25
  version: TlcVersion;
30
26
  seed: bigint;
@@ -45,14 +41,11 @@ export interface CheckerRuntime {
45
41
  startedAt: number;
46
42
  }
47
43
 
48
- // TLC's RandomEnumerableValues keeps one java.util.Random per thread, seeded with -seed. The
49
- // main thread evaluates constants, assumptions, and initial states with it. A worker reseeds
50
- // its Random with the fingerprint of each state it expands, XORed with the seed, so a state's
51
- // successors are the same whatever order the workers expand states in.
52
44
  export const createRuntime = (checkDeadlock: boolean, seed = 0n): CheckerRuntime => {
53
45
  const startupRandom = createJavaRandom(seed);
54
- const worker = { random: createJavaRandom(seed), seededState: undefined as Value[] | undefined };
55
- const phase = { isStartup: false };
46
+ const workerRandom = createJavaRandom(seed);
47
+ let seededState: Value[] | undefined;
48
+ let isStartup = false;
56
49
  const runtime: CheckerRuntime = {
57
50
  getLevel: () => 0,
58
51
  getBehavior: () => [],
@@ -66,21 +59,21 @@ export const createRuntime = (checkDeadlock: boolean, seed = 0n): CheckerRuntime
66
59
  getFingerprint: getTlcFingerprint,
67
60
  getSimulationValue: undefined,
68
61
  getRandom: () => {
69
- const state = phase.isStartup ? undefined : runtime.getCurrentState();
62
+ const state = isStartup ? undefined : runtime.getCurrentState();
70
63
  if (state === undefined) return startupRandom;
71
- if (state !== worker.seededState) {
72
- worker.random.setSeed(runtime.getFingerprint(state) ^ BigInt.asUintN(64, seed));
73
- worker.seededState = state;
64
+ if (state !== seededState) {
65
+ workerRandom.setSeed(runtime.getFingerprint(state) ^ BigInt.asUintN(64, seed));
66
+ seededState = state;
74
67
  }
75
- return worker.random;
68
+ return workerRandom;
76
69
  },
77
70
  evaluateAtStartup: (evaluate) => {
78
- const wasStartup = phase.isStartup;
79
- phase.isStartup = true;
71
+ const wasStartup = isStartup;
72
+ isStartup = true;
80
73
  try {
81
74
  return evaluate();
82
75
  } finally {
83
- phase.isStartup = wasStartup;
76
+ isStartup = wasStartup;
84
77
  }
85
78
  },
86
79
  pause: undefined,
@@ -1,7 +1,5 @@
1
1
  import type { FormalParamNode, LevelFields, OpDefNode, SanyLocation } from "./nodes";
2
2
 
3
- // Name, arity, level, maximum argument levels and argument weights. SANY leaves the levels of
4
- // "." and \neg unset.
5
3
  const BUILTIN_OPERATORS: [string, number, number, number[] | undefined, number[] | undefined][] = [
6
4
  ["STRING", 0, 0, [], []],
7
5
  ["FALSE", 0, 0, [], []],
@@ -105,7 +103,7 @@ export const createBuiltins = (getId: () => number) =>
105
103
  const params =
106
104
  arity < 0
107
105
  ? undefined
108
- : Array.from({ length: arity }, (_, index): FormalParamNode => ({
106
+ : Array.from({ length: arity }, (_value, index): FormalParamNode => ({
109
107
  ...createLevelFields(getId()),
110
108
  kind: "FormalParam",
111
109
  name: `Formal_${index}`,