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
@@ -247,6 +247,9 @@ const getProofInstances = (proof: Proof | undefined): Instance[] =>
247
247
  ...getProofInstances(step.proof),
248
248
  ]);
249
249
 
250
+ // SANY resolves a top-level INSTANCE to an inner module only when the module's first top-level
251
+ // INSTANCE follows the inner module, and otherwise looks for a file. It looks for a file for an
252
+ // INSTANCE in a LET or a proof step too, where tla-ts takes an inner module defined before it.
250
253
  const isInternalInstance = (module: Module, instance: Instance) => {
251
254
  const seen = new Set<string>();
252
255
  for (const unit of module.units) {
@@ -273,10 +276,13 @@ interface LabelScope {
273
276
  params: FormalParamNode[][];
274
277
  }
275
278
 
279
+ // SANY looks at a module's own EXTENDS and INSTANCEs before those of its inner modules.
276
280
  const getDependencies = (module: Module) => {
277
281
  const extendees: string[] = [];
278
282
  const instancees: string[] = [];
279
283
  const importers = new Map<string, string>();
284
+ // A module knows the inner modules defined before it in its enclosing modules and those of the
285
+ // modules it extends, but not itself.
280
286
  const visit = (current: Module, context: Map<string, Module>) => {
281
287
  const isRoot = current === module;
282
288
  const addImports = (names: string[], imports: string[]) =>
@@ -338,6 +344,7 @@ const OPERATOR_ARGUMENT_KINDS = new Set<Expression["kind"]>([
338
344
  "Lambda",
339
345
  ]);
340
346
 
347
+ // A name such as K(1)!C, whose last part takes no arguments, is a GeneralId too.
341
348
  const isOperatorArgument = (argument: Expression) => {
342
349
  const items = argument.kind === "Apply" ? getSelectorItems(argument) : undefined;
343
350
  return OPERATOR_ARGUMENT_KINDS.has(argument.kind) || (items !== undefined && isGeneralId(items));
@@ -395,6 +402,7 @@ const NESTED_FIRST_CHILD_KINDS = new Set([
395
402
 
396
403
  const POSTFIX_OPERATOR_TEXTS = new Set(["'", "^+", "^*", "^#"]);
397
404
 
405
+ // SANY's parser reads a prefix operator other than ~ and -. as a LAMBDA.
398
406
  const getOperatorNodeKind = (
399
407
  expression: Expression & { kind: "OperatorReference" | "Lambda" },
400
408
  text: string,
@@ -415,9 +423,10 @@ export const generateSanySpecification = (
415
423
  addSanyMessage(messages, { location, text, isWarning: false });
416
424
  const addWarning = (location: SanyLocation | undefined, text: string) =>
417
425
  addSanyMessage(messages, { location, text, isWarning: true });
418
- let lastId = options.version === "1.7.4" ? -1 : 0;
419
- const getId = () => ++lastId;
420
- let nullApplicationId = 0;
426
+ // TLC 1.7.4's SANY numbers its first node 0, and the master builds create one before.
427
+ const counter = { value: options.version === "1.7.4" ? -1 : 0 };
428
+ const getId = () => ++counter.value;
429
+ const nullApplication = { id: 0 };
421
430
 
422
431
  const addSymbol = (table: SymbolTable, symbol: SymbolNode) => {
423
432
  const binding = resolveSymbol(table, symbol.name);
@@ -430,6 +439,7 @@ export const generateSanySpecification = (
430
439
  symbol.kind === "FormalParam" ||
431
440
  getSymbolKind(binding) !== getSymbolKind(symbol) ||
432
441
  getSymbolArity(binding) !== getSymbolArity(symbol);
442
+ // TLC 1.7.4's SANY reports a conflict before the redefinition of a built-in operator.
433
443
  const isBuiltIn = binding.kind === "OpDef" && binding.defKind === "BuiltIn";
434
444
  if (isBuiltIn && !(isConflict && options.version === "1.7.4")) {
435
445
  addError(
@@ -450,7 +460,8 @@ export const generateSanySpecification = (
450
460
  );
451
461
  }
452
462
  };
453
- // SANY creates the builtins twice, in Context's static initializer and in frontEndInitialize.
463
+ // Context's static initializer creates the builtins and SANY.frontEndInitialize creates them
464
+ // again; TLC 1.7.4's SANY creates them only once.
454
465
  if (options.version !== "1.7.4") createBuiltins(getId);
455
466
  const builtins = createBuiltins(getId);
456
467
  getId();
@@ -514,6 +525,8 @@ export const generateSanySpecification = (
514
525
  path.pop();
515
526
  order.push(name);
516
527
  };
528
+ // SANY resolves the first unresolved name from the root, every extended module before any
529
+ // instantiated one, each in the context of the module that names it.
517
530
  const resolutions = new Set<string>();
518
531
  const isResolved = (importer: string, name: string) => resolutions.has(`${importer} ${name}`);
519
532
  const findUnresolved = (
@@ -551,6 +564,7 @@ export const generateSanySpecification = (
551
564
  }
552
565
  };
553
566
  const rootName = options.rootFileName ?? parseSource("", rootSource).name;
567
+ // The post conditions' modules join the root module's own extendees, before its inner modules'.
554
568
  const getModuleDependencies = (name: string, module: Module) => {
555
569
  const dependencies = getDependencies(module);
556
570
  if (name !== rootName || options.rootExtendees === undefined) return dependencies;
@@ -716,8 +730,9 @@ export const generateSanySpecification = (
716
730
  location,
717
731
  });
718
732
 
733
+ // nullOAN has no syntax tree node, so SANY locates it at the builtins.
719
734
  const createNullNode = (): OpApplNode => ({
720
- ...createOpAppl(getBuiltin("$Nop"), [], BUILTIN_LOCATION, {}, nullApplicationId),
735
+ ...createOpAppl(getBuiltin("$Nop"), [], BUILTIN_LOCATION, {}, nullApplication.id),
721
736
  isNull: true,
722
737
  });
723
738
 
@@ -741,10 +756,10 @@ export const generateSanySpecification = (
741
756
  location,
742
757
  });
743
758
 
744
- const createOpArg = (operator: SymbolNode, location: SanyLocation): OpArgNode => ({
759
+ const createOpArg = (op: SymbolNode, location: SanyLocation): OpArgNode => ({
745
760
  ...createLevelFields(getId()),
746
761
  kind: "OpArg",
747
- op: operator,
762
+ op,
748
763
  location,
749
764
  });
750
765
 
@@ -758,6 +773,8 @@ export const generateSanySpecification = (
758
773
  return symbol;
759
774
  };
760
775
 
776
+ // A definition's parameter count differs from its arity only where its RECURSIVE declaration
777
+ // gives another.
761
778
  const matchArguments = (
762
779
  operator: SymbolNode,
763
780
  operands: ExprOrOpArgNode[],
@@ -854,21 +871,21 @@ export const generateSanySpecification = (
854
871
  });
855
872
 
856
873
  const locateSelectorItems = (items: SelectorItem[], span: TokenSpan) => {
857
- let cursor = span.start;
874
+ const cursor = { value: span.start };
858
875
  return items.map((item): SelectorItem => {
859
876
  const text = item.op === "Name" ? item.name : item.op === "Null" ? "(" : String(item.op);
860
- const index = findToken(file, cursor, span.end, text);
877
+ const index = findToken(file, cursor.value, span.end, text);
861
878
  if (index === -1) return item;
862
879
  if (item.op === "Null") {
863
880
  const close = getMatchingIndex(file, index);
864
- cursor = close + 1;
881
+ cursor.value = close + 1;
865
882
  return { ...item, location: getSpanLocation(file, { start: index, end: close }) };
866
883
  }
867
- cursor = index + 1;
884
+ cursor.value = index + 1;
868
885
  const location = getTokenLocation(file, index);
869
886
  if (item.args === undefined || !isToken(file, index + 1, "(")) return { ...item, location };
870
887
  const close = getMatchingIndex(file, index + 1);
871
- cursor = close + 1;
888
+ cursor.value = close + 1;
872
889
  return {
873
890
  ...item,
874
891
  location,
@@ -907,6 +924,7 @@ export const generateSanySpecification = (
907
924
  if (recursive) recursive.node.operator = getBuiltin("$RecursiveFcnSpec");
908
925
  };
909
926
 
927
+ // tla-ts expands \A x, y \in S into a bound per name that shares the set; SANY keeps one group.
910
928
  const getBoundGroups = (bounds: Bound[]) =>
911
929
  bounds.reduce<Bound[][]>((groups, bound) => {
912
930
  const last = groups[groups.length - 1];
@@ -920,6 +938,7 @@ export const generateSanySpecification = (
920
938
  return groups;
921
939
  }, []);
922
940
 
941
+ // SANY generates every bounding set before it declares the symbols.
923
942
  const generateBounds = (bounds: Bound[], searchStart: number) =>
924
943
  generateBoundsWithRanges(
925
944
  bounds,
@@ -935,19 +954,6 @@ export const generateSanySpecification = (
935
954
  return node;
936
955
  };
937
956
 
938
- const generateBoundApplication = (
939
- name: string,
940
- bounds: Bound[],
941
- searchStart: number,
942
- body: Expression,
943
- location: SanyLocation,
944
- ) =>
945
- withContext(createContext(), () => {
946
- const symbols = generateBounds(bounds, searchStart);
947
- const operand = generateWithParams(symbols.bounded.flat(), body);
948
- return applyBuiltin(name, [operand], location, symbols);
949
- });
950
-
951
957
  const generateLambda = (expression: Expression & { kind: "Lambda" }): OpDefNode => {
952
958
  const span = getExpressionSpan(file, expression);
953
959
  const nameIndexes = findNameTokens(file, span.start, span.end, expression.params);
@@ -966,6 +972,7 @@ export const generateSanySpecification = (
966
972
  });
967
973
  };
968
974
 
975
+ // tla-ts desugars an operator symbol argument, such as SUBSET or -., into a LAMBDA naming it.
969
976
  const getOperatorArgumentName = (argument: Expression) =>
970
977
  argument.kind === "OperatorReference"
971
978
  ? argument.operator
@@ -1062,6 +1069,7 @@ export const generateSanySpecification = (
1062
1069
  return createNullNode();
1063
1070
  };
1064
1071
 
1072
+ // A /\ B /\ C nests as ((A /\ B) /\ C) in SANY; tla-ts flattens it.
1065
1073
  const generateJunction = (expression: Expression & { kind: "And" | "Or" }) => {
1066
1074
  const location = getLocation(expression);
1067
1075
  if (expression.isBulleted) {
@@ -1126,21 +1134,21 @@ export const generateSanySpecification = (
1126
1134
  const operands: ExprOrOpArgNode[] = [generateExpression(expression.function)];
1127
1135
  const exceptNode = applyBuiltin("$Except", operands, location);
1128
1136
  const functionSpan = getExpressionSpan(file, expression.function);
1129
- let cursor = findToken(file, functionSpan.end + 1, span.end, "EXCEPT") + 1;
1137
+ const cursor = { value: findToken(file, functionSpan.end + 1, span.end, "EXCEPT") + 1 };
1130
1138
  expression.updates.forEach((update) => {
1131
- const bang = findToken(file, cursor, span.end, "!");
1139
+ const bang = findToken(file, cursor.value, span.end, "!");
1132
1140
  const valueSpan = getParenthesizedSpan(file, getExpressionSpan(file, update.value));
1133
1141
  const specLocation = getSpanLocation(file, { start: bang, end: valueSpan.end });
1134
- let pathCursor = bang + 1;
1142
+ const pathCursor = { value: bang + 1 };
1135
1143
  const components = update.path.map((step): ExprNode => {
1136
1144
  if (step.kind === "Field") {
1137
- const nameIndex = findNameOrKeyword(pathCursor, step.name);
1138
- pathCursor = nameIndex + 1;
1145
+ const nameIndex = findNameOrKeyword(pathCursor.value, step.name);
1146
+ pathCursor.value = nameIndex + 1;
1139
1147
  return createString(step.name, getTokenLocation(file, nameIndex));
1140
1148
  }
1141
- const open = findToken(file, pathCursor, span.end, "[");
1149
+ const open = findToken(file, pathCursor.value, span.end, "[");
1142
1150
  const close = getMatchingIndex(file, open);
1143
- pathCursor = close + 1;
1151
+ pathCursor.value = close + 1;
1144
1152
  if (step.args.length === 1) return generateExpression(step.args[0]);
1145
1153
  return applyBuiltin(
1146
1154
  "$Tuple",
@@ -1156,7 +1164,7 @@ export const generateSanySpecification = (
1156
1164
  exceptSpecStack.pop();
1157
1165
  exceptStack.pop();
1158
1166
  operands.push(pair);
1159
- cursor = valueSpan.end + 1;
1167
+ cursor.value = valueSpan.end + 1;
1160
1168
  });
1161
1169
  return exceptNode;
1162
1170
  };
@@ -1173,11 +1181,11 @@ export const generateSanySpecification = (
1173
1181
  expression: Expression & { kind: "Record" | "RecordSet" },
1174
1182
  ) => {
1175
1183
  const span = getExpressionSpan(file, expression);
1176
- let cursor = span.start + 1;
1184
+ const cursor = { value: span.start + 1 };
1177
1185
  const pairs = expression.fields.map((field, fieldIndex) => {
1178
- const nameIndex = findNameOrKeyword(cursor, field.name);
1186
+ const nameIndex = findNameOrKeyword(cursor.value, field.name);
1179
1187
  const valueSpan = getParenthesizedSpan(file, getExpressionSpan(file, field.value));
1180
- cursor = valueSpan.end + 1;
1188
+ cursor.value = valueSpan.end + 1;
1181
1189
  if (expression.fields.slice(0, fieldIndex).some((other) => other.name === field.name)) {
1182
1190
  addError(getTokenLocation(file, nameIndex), "Non-unique fields in constructor.");
1183
1191
  }
@@ -1200,6 +1208,7 @@ export const generateSanySpecification = (
1200
1208
  column: file.tokens[index].column,
1201
1209
  });
1202
1210
 
1211
+ // The syntax tree of a LET leaves out its RECURSIVE declarations, so read them from the tokens.
1203
1212
  const getRecursiveDeclarations = (start: number) => {
1204
1213
  const declarations: Declaration[] = [];
1205
1214
  let index = start;
@@ -1294,6 +1303,7 @@ export const generateSanySpecification = (
1294
1303
  const names = pattern.kind === "Name" ? [pattern.name] : pattern.names;
1295
1304
  if (expression.set === undefined) {
1296
1305
  const indexes = findNameTokens(file, span.start, span.end, names);
1306
+ // SANY locates the symbol of CHOOSE x : P at the CHOOSE keyword.
1297
1307
  const params = names.map((name, index) =>
1298
1308
  createFormalParam(
1299
1309
  name,
@@ -1332,6 +1342,7 @@ export const generateSanySpecification = (
1332
1342
  return undefined;
1333
1343
  }
1334
1344
  const span = getExpressionSpan(file, expression);
1345
+ // SANY reports an operator applied like a function, as in op(a, b), as an unknown operator.
1335
1346
  if (
1336
1347
  file.tokens[span.start].text === expression.operator &&
1337
1348
  isToken(file, span.start + 1, "(")
@@ -1444,14 +1455,19 @@ export const generateSanySpecification = (
1444
1455
  case "Let":
1445
1456
  return generateLet(expression);
1446
1457
  case "Forall":
1447
- case "Exists":
1448
- return generateBoundApplication(
1449
- expression.kind === "Forall" ? "$BoundedForall" : "$BoundedExists",
1450
- expression.bounds,
1451
- getExpressionSpan(file, expression).start,
1452
- expression.body,
1453
- location,
1454
- );
1458
+ case "Exists": {
1459
+ const span = getExpressionSpan(file, expression);
1460
+ return withContext(createContext(), () => {
1461
+ const bounds = generateBounds(expression.bounds, span.start);
1462
+ const body = generateWithParams(bounds.bounded.flat(), expression.body);
1463
+ return applyBuiltin(
1464
+ expression.kind === "Forall" ? "$BoundedForall" : "$BoundedExists",
1465
+ [body],
1466
+ location,
1467
+ bounds,
1468
+ );
1469
+ });
1470
+ }
1455
1471
  case "UnboundedQuantifier": {
1456
1472
  const span = getExpressionSpan(file, expression);
1457
1473
  const bodySpan = getExpressionSpan(file, expression.body);
@@ -1490,22 +1506,22 @@ export const generateSanySpecification = (
1490
1506
  return applyBuiltin("$SubsetOf", [body], location, bounds);
1491
1507
  });
1492
1508
  }
1493
- case "SetMap":
1494
- return generateBoundApplication(
1495
- "$SetOfAll",
1496
- expression.bounds,
1497
- getExpressionSpan(file, expression.expression).end + 1,
1498
- expression.expression,
1499
- location,
1500
- );
1501
- case "FunctionConstruction":
1502
- return generateBoundApplication(
1503
- "$FcnConstructor",
1504
- expression.bounds,
1505
- getExpressionSpan(file, expression).start,
1506
- expression.body,
1507
- location,
1508
- );
1509
+ case "SetMap": {
1510
+ const expressionSpan = getExpressionSpan(file, expression.expression);
1511
+ return withContext(createContext(), () => {
1512
+ const bounds = generateBounds(expression.bounds, expressionSpan.end + 1);
1513
+ const body = generateWithParams(bounds.bounded.flat(), expression.expression);
1514
+ return applyBuiltin("$SetOfAll", [body], location, bounds);
1515
+ });
1516
+ }
1517
+ case "FunctionConstruction": {
1518
+ const span = getExpressionSpan(file, expression);
1519
+ return withContext(createContext(), () => {
1520
+ const bounds = generateBounds(expression.bounds, span.start);
1521
+ const body = generateWithParams(bounds.bounded.flat(), expression.body);
1522
+ return applyBuiltin("$FcnConstructor", [body], location, bounds);
1523
+ });
1524
+ }
1509
1525
  case "FunctionSet":
1510
1526
  return applyBuiltin(
1511
1527
  "$SetOfFcns",
@@ -1535,6 +1551,7 @@ export const generateSanySpecification = (
1535
1551
  }
1536
1552
  case "FunctionApplication": {
1537
1553
  const functionNode = generateExpression(expression.function);
1554
+ // SANY leaves the whole application null, without generating its arguments.
1538
1555
  if (isAbsent(functionNode)) return functionNode;
1539
1556
  checkRecursion(functionNode);
1540
1557
  const operator = functionNode.kind === "OpAppl" ? functionNode.operator : undefined;
@@ -1607,14 +1624,14 @@ export const generateSanySpecification = (
1607
1624
  ranges: ExprNode[],
1608
1625
  ): BoundSymbols => {
1609
1626
  const groups = getBoundGroups(bounds);
1610
- let cursor = searchStart;
1627
+ const cursor = { value: searchStart };
1611
1628
  const bounded = groups.map((group) => {
1612
1629
  const setSpan = getExpressionSpan(file, group[0].set);
1613
1630
  const names = group.flatMap((bound) =>
1614
1631
  bound.pattern.kind === "Name" ? [bound.pattern.name] : bound.pattern.names,
1615
1632
  );
1616
- const indexes = findNameTokens(file, cursor, setSpan.start, names);
1617
- cursor = setSpan.end + 1;
1633
+ const indexes = findNameTokens(file, cursor.value, setSpan.start, names);
1634
+ cursor.value = setSpan.end + 1;
1618
1635
  return names.map((name, index) =>
1619
1636
  createFormalParam(name, 0, getTokenLocation(file, indexes[index]), true),
1620
1637
  );
@@ -1633,6 +1650,7 @@ export const generateSanySpecification = (
1633
1650
  addError(location, "Label not in definition or proof step.");
1634
1651
  return createNullNode();
1635
1652
  }
1653
+ // No label may lie in the scope of a declaration of a nested ASSUME/PROVE.
1636
1654
  if (assumeProveState.isDeclared.slice(2, assumeProveState.depth + 1).some(Boolean)) {
1637
1655
  addError(location, "Label not allowed within scope of declaration in nested ASSUME/PROVE.");
1638
1656
  return createNullNode();
@@ -1698,13 +1716,14 @@ export const generateSanySpecification = (
1698
1716
  span: TokenSpan,
1699
1717
  isAdded: boolean,
1700
1718
  ) => {
1701
- let cursor = span.start;
1719
+ const cursor = { value: span.start };
1702
1720
  return definition.params.map((param) => {
1703
1721
  const index = param.location
1704
1722
  ? getTokenIndex(file, param.location)
1705
- : findNameOrKeyword(cursor, param.name);
1723
+ : findNameOrKeyword(cursor.value, param.name);
1706
1724
  const paramSpan = getOperatorSpan(index, param.arity);
1707
- cursor = paramSpan.end + 1;
1725
+ cursor.value = paramSpan.end + 1;
1726
+ // SANY keeps the spelling of a prefix parameter, so ~ _ does not redefine \lnot.
1708
1727
  const isPrefix = param.arity === 1 && isToken(file, index + 1, "_");
1709
1728
  return createFormalParam(
1710
1729
  isPrefix ? (file.tokens[index].spelling ?? param.name) : resolveSynonym(param.name),
@@ -1747,6 +1766,7 @@ export const generateSanySpecification = (
1747
1766
  `Definition of ${existing.name} has different arity than its RECURSIVE declaration.`,
1748
1767
  );
1749
1768
  }
1769
+ // SANY sets the parameters before it analyzes the body.
1750
1770
  existing.params = params;
1751
1771
  }
1752
1772
  } else if (existing !== undefined) {
@@ -1851,6 +1871,7 @@ export const generateSanySpecification = (
1851
1871
  : existing.kind === "OpDef" && (isRecursive || !isPendingRecursive)
1852
1872
  ? existing
1853
1873
  : undefined;
1874
+ // A function whose RECURSIVE declaration has parameters stays undefined.
1854
1875
  if (isRecursive) {
1855
1876
  if (existing.arity === 0) endOpDefNode(existing, node, location, preComments);
1856
1877
  } else if (existing === undefined && definitionNode !== undefined) {
@@ -1863,6 +1884,7 @@ export const generateSanySpecification = (
1863
1884
  }
1864
1885
  functions.unshift({ name: definition.name, node });
1865
1886
  pushLabelScope();
1887
+ // The bound identifiers are bound in the body only of a function with an OpDefNode.
1866
1888
  const generateBody = () => generateWithParams(bounds.bounded.flat(), definition.body);
1867
1889
  const body =
1868
1890
  definitionNode === undefined ? generateBody() : withContext(context, generateBody);
@@ -1914,6 +1936,8 @@ export const generateSanySpecification = (
1914
1936
  state.unresolvedSum -= state.unresolvedCount[state.curLevel];
1915
1937
  };
1916
1938
 
1939
+ // Implicit substitutions in the order of the instantiated module's Hashtable, then the explicit
1940
+ // WITH substitutions.
1917
1941
  const processSubstitutions = (
1918
1942
  instance: Instance,
1919
1943
  instanceeContext: Context,
@@ -1939,6 +1963,7 @@ export const generateSanySpecification = (
1939
1963
  },
1940
1964
  ];
1941
1965
  });
1966
+ // SANY locates an arity error at its builtins for the nullOpArg it substitutes after an error.
1942
1967
  const checkArity = (target: OpDeclNode, substitute: ExprOrOpArgNode) => {
1943
1968
  const arity = substitute.kind === "OpArg" ? getSymbolArity(substitute.op) : 0;
1944
1969
  if (arity !== target.arity) {
@@ -1949,11 +1974,12 @@ export const generateSanySpecification = (
1949
1974
  }
1950
1975
  };
1951
1976
  const span = getDefinitionSpan(instance);
1952
- let cursor = findToken(file, span.start, span.end, "WITH") + 1;
1977
+ const cursor = { value: findToken(file, span.start, span.end, "WITH") + 1 };
1953
1978
  instance.substitutions.forEach((substitution) => {
1954
- const targetIndex = findToken(file, cursor, span.end, substitution.name);
1979
+ const targetIndex = findToken(file, cursor.value, span.end, substitution.name);
1980
+ // The next target follows this substitution's expression, which may name it too.
1955
1981
  if (targetIndex !== -1) {
1956
- cursor = getExpressionSpan(file, substitution.expression).end + 1;
1982
+ cursor.value = getExpressionSpan(file, substitution.expression).end + 1;
1957
1983
  }
1958
1984
  const target = getContextSymbol(instanceeContext, resolveSynonym(substitution.name));
1959
1985
  if (target?.kind !== "OpDecl") {
@@ -1979,6 +2005,7 @@ export const generateSanySpecification = (
1979
2005
  existing.isImplicit = false;
1980
2006
  } else substs.push({ op: target, expr: substitute, isImplicit: false });
1981
2007
  });
2008
+ // TLC 1.7.4's SANY checks the arity of only the substitutions that the INSTANCE writes.
1982
2009
  substs
1983
2010
  .filter((subst) => subst.isImplicit && options.version !== "1.7.4")
1984
2011
  .forEach((subst) => checkArity(subst.op, subst.expr));
@@ -2123,9 +2150,12 @@ export const generateSanySpecification = (
2123
2150
  preComments,
2124
2151
  });
2125
2152
  addSymbol(symbolTable, moduleDefinition);
2153
+ // TLC 1.7.4's SANY leaves the definition out of the definitions of a LET.
2126
2154
  if (options.version !== "1.7.4") definitions?.push(moduleDefinition);
2127
2155
  };
2128
2156
 
2157
+ // An INSTANCE proof step is located at the step's body and adds no theorem definitions or
2158
+ // instance to the module.
2129
2159
  const generateInstance = (
2130
2160
  instance: Instance,
2131
2161
  isTopLevel = true,
@@ -2174,6 +2204,8 @@ export const generateSanySpecification = (
2174
2204
  currentModule.definitions.push(node);
2175
2205
  setRecursionFields(node);
2176
2206
  });
2207
+ // SANY reuses a theorem of a parameter-free module without adding it to the symbol table when
2208
+ // the instantiated module has parameters.
2177
2209
  getHashtableValues(instanceeContext.table).forEach((symbol) => {
2178
2210
  if (symbol.kind !== "ThmOrAssumpDef" || symbol.isLocal) return;
2179
2211
  const copyFrom = (module: ModuleNode, body: LevelNode) => {
@@ -2258,12 +2290,15 @@ export const generateSanySpecification = (
2258
2290
  if (expression.kind === "Apply") return getApplicationKind(expression, span);
2259
2291
  return SYNTAX_KINDS.get(expression.kind);
2260
2292
  };
2293
+ // Generator.genIdToSelector takes a childless first child for an empty prefix of a name.
2261
2294
  const hasChildlessFirstChild = (expression: Expression, span: TokenSpan) => {
2262
2295
  if (expression.kind === "String" && !isParenthesized(span)) return false;
2263
2296
  if (expression.kind === "Identifier" && !expression.name.includes("!")) return true;
2264
2297
  const kind = getSyntaxKind(expression, span);
2265
2298
  return kind === undefined || NESTED_FIRST_CHILD_KINDS.has(kind) ? undefined : true;
2266
2299
  };
2300
+ // Generator.genIdToSelector reads a DEF entry that isn't a name as one: its first child as the
2301
+ // prefix and its second as the last part.
2267
2302
  const getDefEntryParts = (
2268
2303
  expression: Expression,
2269
2304
  span: TokenSpan,
@@ -2352,6 +2387,7 @@ export const generateSanySpecification = (
2352
2387
  }
2353
2388
  return undefined;
2354
2389
  };
2390
+ // False where SANY's reading of the entry isn't modeled.
2355
2391
  const reportDefEntry = (expression: Expression) => {
2356
2392
  const span = getParenthesizedSpan(file, getExpressionSpan(file, expression));
2357
2393
  const isName =
@@ -2387,6 +2423,8 @@ export const generateSanySpecification = (
2387
2423
  false,
2388
2424
  true,
2389
2425
  );
2426
+ // SANY rejects a proof step name in a DEF clause and leaves out an entry it rejects.
2427
+ // Errors.addMessage drops the message when selectorToNode already reported it.
2390
2428
  const isDefinition =
2391
2429
  symbol.kind === "OpDef" ||
2392
2430
  (symbol.kind === "ThmOrAssumpDef" && !symbol.name.startsWith("<"));
@@ -2397,6 +2435,7 @@ export const generateSanySpecification = (
2397
2435
  return [symbol];
2398
2436
  });
2399
2437
 
2438
+ // SANY rejects a BY, USE or HIDE with nothing after its keyword before it reads the facts.
2400
2439
  const checkKeywordOnly = (
2401
2440
  statement: UseOrHide | Extract<Proof, { kind: "By" }>,
2402
2441
  location: SanyLocation,
@@ -2411,6 +2450,7 @@ export const generateSanySpecification = (
2411
2450
  const facts = generateFacts(use.facts);
2412
2451
  const defs = generateDefs(use.defs);
2413
2452
  if (facts.length + defs.length === 0) addError(location, "Empty USE or HIDE statement.");
2453
+ // A HIDE cites facts by name only.
2414
2454
  if (use.kind === "Hide") {
2415
2455
  facts
2416
2456
  .filter((fact) => fact.kind === "OpAppl" && fact.operator.kind !== "ThmOrAssumpDef")
@@ -2432,6 +2472,7 @@ export const generateSanySpecification = (
2432
2472
  };
2433
2473
  };
2434
2474
 
2475
+ // SANY generates the set before it declares the symbol.
2435
2476
  const generateNewSymbol = (symbol: NewSymbol): NewSymbNode => {
2436
2477
  const span = getUnitSpan(symbol.location);
2437
2478
  const set = symbol.set && generateExpression(symbol.set);
@@ -2538,6 +2579,7 @@ export const generateSanySpecification = (
2538
2579
  return node;
2539
2580
  };
2540
2581
 
2582
+ // SANY numbers the ThmOrAssumpDefNode before it generates what it asserts.
2541
2583
  const createTheoremDefinition = (
2542
2584
  id: number,
2543
2585
  name: string,
@@ -2642,7 +2684,10 @@ export const generateSanySpecification = (
2642
2684
  symbolTable.contexts.push(proofContext);
2643
2685
  const instances: InstanceNode[] = [];
2644
2686
  const sufficesContexts: Context[] = [];
2645
- let previousRight: ExprOrOpArgNode | undefined;
2687
+ // An assertion step @ = e continues the step before it, whose right side the @ stands for.
2688
+ const infixStep: { previousRight: ExprOrOpArgNode | undefined } = {
2689
+ previousRight: undefined,
2690
+ };
2646
2691
  const generateOtherStep = (
2647
2692
  body: ProofStep["body"],
2648
2693
  stepSpan: TokenSpan,
@@ -2688,9 +2733,11 @@ export const generateSanySpecification = (
2688
2733
  }
2689
2734
  if (step.name !== undefined) pushLabelScope();
2690
2735
  const definitionId = step.name === undefined ? undefined : getId();
2691
- if (body.kind !== "Assert") previousRight = undefined;
2736
+ if (body.kind !== "Assert") infixStep.previousRight = undefined;
2692
2737
  const otherStep = generateOtherStep(body, stepSpan, bodySpan);
2693
2738
  if (otherStep !== undefined) {
2739
+ // SANY puts a definition for a named step that asserts nothing in the symbol table, for a DEF
2740
+ // clause to name.
2694
2741
  if (step.name !== undefined) {
2695
2742
  addSymbol(
2696
2743
  symbolTable,
@@ -2706,7 +2753,7 @@ export const generateSanySpecification = (
2706
2753
  return otherStep;
2707
2754
  }
2708
2755
  const isAssumeProve = body.kind === "Assert" && body.statement.kind === "AssumeProve";
2709
- if (isAssumeProve) previousRight = undefined;
2756
+ if (isAssumeProve) infixStep.previousRight = undefined;
2710
2757
  const isSuffices = body.kind === "Assert" && body.isSuffices;
2711
2758
  const assumeContext = createContext();
2712
2759
  const generateAssertion = (statement: Expression | AssumeProve): LevelNode => {
@@ -2725,6 +2772,7 @@ export const generateSanySpecification = (
2725
2772
  const expression = generateExpression(statement);
2726
2773
  return applyBuiltin("$Suffices", [expression], getSpanLocation(file, bodySpan));
2727
2774
  }
2775
+ const previousRight = infixStep.previousRight;
2728
2776
  const isAtStep =
2729
2777
  previousRight !== undefined &&
2730
2778
  statement.kind === "Apply" &&
@@ -2740,7 +2788,7 @@ export const generateSanySpecification = (
2740
2788
  )
2741
2789
  : generateExpression(statement);
2742
2790
  const right = expression.kind === "OpAppl" ? expression.operands[1] : undefined;
2743
- previousRight = isInfixExpression(statement) ? right : undefined;
2791
+ infixStep.previousRight = isInfixExpression(statement) ? right : undefined;
2744
2792
  return expression;
2745
2793
  };
2746
2794
  const generated =
@@ -2871,6 +2919,8 @@ export const generateSanySpecification = (
2871
2919
 
2872
2920
  const createDeclaration = (declaration: Declaration, declKind: number): OpDeclNode => {
2873
2921
  const span = getDeclarationSpan(declaration);
2922
+ // Generator.processParameters makes this check of a constant too, of its syntax node's name,
2923
+ // which is never @.
2874
2924
  if (declaration.name === "@" && declKind === VARIABLE_DECL_KIND) {
2875
2925
  addError(getSpanLocation(file, span), "Attempted to declare '@' as a variable.");
2876
2926
  }
@@ -2893,6 +2943,8 @@ export const generateSanySpecification = (
2893
2943
  return node;
2894
2944
  };
2895
2945
 
2946
+ // The extended module's symbols join in the order they joined it, apart from LOCAL ones and
2947
+ // those already present.
2896
2948
  ast.extends.forEach((name) => {
2897
2949
  const extendee = getModule(name);
2898
2950
  currentModule.extendees.push(extendee);
@@ -2995,9 +3047,10 @@ export const generateSanySpecification = (
2995
3047
  const modules = order.map((name) => {
2996
3048
  options.onAnalyze?.(name);
2997
3049
  // Each module's Generator creates its nullODN, nullOAN, nullOpArg and nullLabelNode.
2998
- nullApplicationId = Array.from({ length: 4 }, getId)[1];
3050
+ nullApplication.id = Array.from({ length: 4 }, getId)[1];
2999
3051
  const entry = getSource(name, undefined);
3000
3052
  const context = createContext();
3053
+ // SANY's global context lists its builtins from the last to the first.
3001
3054
  builtins.toReversed().forEach((builtin) => addToContext(context, builtin));
3002
3055
  const module = generateModule(entry.module, entry.file, undefined, {
3003
3056
  contexts: [context],