tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.b4a856304

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