tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.63a6693bd

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 (172) hide show
  1. package/dist/compile.cjs +6 -6
  2. package/dist/compile.js +10 -10
  3. package/dist/deciders.cjs +29 -29
  4. package/dist/deciders.js +40 -40
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +1 -1
  9. package/dist/prove-worker.cjs +1 -1
  10. package/dist/prove-worker.js +1 -1
  11. package/dist/prove.cjs +54 -54
  12. package/dist/prove.js +52 -52
  13. package/dist/run.cjs +42 -42
  14. package/dist/run.js +44 -44
  15. package/dist/tlapm.cjs +2 -2
  16. package/dist/tlapm.js +2 -2
  17. package/dist/transfer.cjs +39 -39
  18. package/dist/transfer.js +41 -41
  19. package/dist/worker.cjs +4 -4
  20. package/dist/worker.js +4 -4
  21. package/package.json +1 -1
  22. package/src/ast.ts +44 -39
  23. package/src/builtins.ts +4 -13
  24. package/src/check-failure.ts +116 -0
  25. package/src/check-trace.ts +282 -0
  26. package/src/check.ts +152 -518
  27. package/src/cli/options.ts +6 -31
  28. package/src/cli/shared.ts +1 -1
  29. package/src/cli/tlapm.ts +14 -13
  30. package/src/cli/tlc-arguments.ts +222 -210
  31. package/src/cli/tlc-output.ts +687 -0
  32. package/src/cli/tlc-usage.ts +1 -1
  33. package/src/cli/tlc.ts +34 -701
  34. package/src/cli/xml-exporter.ts +23 -33
  35. package/src/codegen.ts +5 -10
  36. package/src/coverage.ts +3 -10
  37. package/src/dependencies.ts +8 -13
  38. package/src/dfid.ts +16 -16
  39. package/src/environment-config.ts +315 -0
  40. package/src/environment.ts +45 -333
  41. package/src/errors.ts +3 -2
  42. package/src/evaluate.ts +5 -4
  43. package/src/fingerprints.ts +65 -1
  44. package/src/instances.ts +47 -10
  45. package/src/java-hash.ts +7 -0
  46. package/src/json.ts +4 -7
  47. package/src/levels.ts +39 -42
  48. package/src/liveness-checker.ts +24 -37
  49. package/src/liveness.ts +47 -54
  50. package/src/obligations/action.ts +4 -11
  51. package/src/obligations/anonymize.ts +4 -2
  52. package/src/obligations/expression.ts +18 -2
  53. package/src/obligations/generate.ts +45 -38
  54. package/src/obligations/index.ts +2 -2
  55. package/src/obligations/module.ts +27 -38
  56. package/src/obligations/normalize.ts +2 -1
  57. package/src/obligations/simplify.ts +39 -44
  58. package/src/obligations/source.ts +47 -57
  59. package/src/obligations/temporal.ts +5 -5
  60. package/src/parallel-worker.ts +10 -30
  61. package/src/parallel.ts +22 -45
  62. package/src/parser.ts +19 -34
  63. package/src/prover/decide-pool.ts +3 -3
  64. package/src/prover/deciders.ts +3 -3
  65. package/src/prover/isabelle/encode.ts +1 -1
  66. package/src/prover/isabelle/isar/inner-syntax.ts +9 -4
  67. package/src/prover/isabelle/isar/method.ts +14 -25
  68. package/src/prover/isabelle/isar/theory.ts +11 -10
  69. package/src/prover/isabelle/isar/type-check.ts +6 -6
  70. package/src/prover/isabelle/provers/blast/blast.ts +7 -63
  71. package/src/prover/isabelle/provers/hypsubst.ts +17 -26
  72. package/src/prover/isabelle/pure/bicompose.ts +9 -25
  73. package/src/prover/isabelle/pure/conv.ts +2 -8
  74. package/src/prover/isabelle/pure/drule.ts +9 -2
  75. package/src/prover/isabelle/pure/logic.ts +1 -1
  76. package/src/prover/isabelle/pure/raw-simplifier.ts +4 -13
  77. package/src/prover/isabelle/pure/rewriter.ts +5 -9
  78. package/src/prover/isabelle/pure/table.ts +2 -1
  79. package/src/prover/isabelle/pure/tactical.ts +42 -35
  80. package/src/prover/isabelle/pure/thm.ts +14 -11
  81. package/src/prover/isabelle/tla/classical-setup.ts +17 -14
  82. package/src/prover/isabelle/tla/context.ts +7 -2
  83. package/src/prover/isabelle/tla/logic.ts +10 -21
  84. package/src/prover/isabelle/tla/simpdata.ts +1 -10
  85. package/src/prover/prep/action.ts +11 -19
  86. package/src/prover/prep/fingerprint.ts +2 -5
  87. package/src/prover/prep/methods.ts +24 -3
  88. package/src/prover/prove.ts +87 -64
  89. package/src/prover/smt/context.ts +1 -2
  90. package/src/prover/smt/data.ts +418 -406
  91. package/src/prover/smt/encode.ts +30 -18
  92. package/src/prover/smt/rewrite.ts +657 -626
  93. package/src/prover/smt/solver/ast.ts +0 -22
  94. package/src/prover/smt/solver/auf-solver.ts +2 -5
  95. package/src/prover/smt/solver/context.ts +3 -3
  96. package/src/prover/smt/solver/e-matching.ts +1 -1
  97. package/src/prover/smt/solver/expr-safe-replace.ts +1 -1
  98. package/src/prover/smt/solver/internalizer.ts +1 -2
  99. package/src/prover/smt/solver/lp/dioph-eq.ts +1 -8
  100. package/src/prover/smt/solver/lp/hnf-cutter.ts +1 -1
  101. package/src/prover/smt/solver/lp/nla-core.ts +2 -6
  102. package/src/prover/smt/solver/mam-compiler.ts +4 -2
  103. package/src/prover/smt/solver/model-checker.ts +1 -1
  104. package/src/prover/smt/solver/model-finder.ts +12 -17
  105. package/src/prover/smt/solver/model-macro-solver.ts +11 -19
  106. package/src/prover/smt/solver/nlsat/algebraic.ts +9 -9
  107. package/src/prover/smt/solver/nlsat/atoms.ts +20 -4
  108. package/src/prover/smt/solver/nlsat/explain.ts +7 -22
  109. package/src/prover/smt/solver/nlsat/levelwise.ts +1 -6
  110. package/src/prover/smt/solver/nlsat/polynomial.ts +12 -3
  111. package/src/prover/smt/solver/nlsat/solver.ts +12 -24
  112. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -1
  113. package/src/prover/smt/solver/proto-model.ts +0 -4
  114. package/src/prover/smt/solver/quantifier-analyzer.ts +10 -10
  115. package/src/prover/smt/solver/quantifier-manager.ts +1 -5
  116. package/src/prover/smt/solver/smtlib-parser.ts +78 -94
  117. package/src/prover/smt/solver/theory-lra-bounds.ts +1 -2
  118. package/src/prover/smt/solver/theory-lra-internalize.ts +5 -16
  119. package/src/prover/tlapm/cache.ts +28 -18
  120. package/src/prover/tlapm/tlapm.ts +15 -9
  121. package/src/prover/verdict.ts +7 -0
  122. package/src/prover/zenon/check/check.ts +1 -2
  123. package/src/prover/zenon/check/records.ts +1 -1
  124. package/src/prover/zenon/check/relations.ts +2 -1
  125. package/src/prover/zenon/check/rewrites.ts +2 -15
  126. package/src/prover/zenon/check/sets.ts +40 -58
  127. package/src/prover/zenon/check/terms.ts +1 -2
  128. package/src/prover/zenon/eqrel.ts +2 -0
  129. package/src/prover/zenon/expr.ts +7 -0
  130. package/src/prover/zenon/index-table.ts +9 -19
  131. package/src/prover/zenon/isar.ts +35 -35
  132. package/src/prover/zenon/llproof.ts +2 -11
  133. package/src/prover/zenon/mltoll.ts +12 -28
  134. package/src/prover/zenon/parse.ts +3 -6
  135. package/src/prover/zenon/search.ts +4 -14
  136. package/src/prover/zenon/tla/functions.ts +2 -2
  137. package/src/prover/zenon/tla/llproof.ts +9 -11
  138. package/src/prover/zenon/tla/records.ts +1 -6
  139. package/src/prover/zenon/tla/sets.ts +15 -14
  140. package/src/prover/zenon/tla/tla.ts +7 -6
  141. package/src/resolve.ts +55 -72
  142. package/src/sany/generation.ts +394 -0
  143. package/src/sany/generator-def-entries.ts +210 -0
  144. package/src/sany/generator-definitions.ts +686 -0
  145. package/src/sany/generator-expressions.ts +1100 -0
  146. package/src/sany/generator-proofs.ts +662 -0
  147. package/src/sany/generator.ts +155 -2625
  148. package/src/sany/lexer.ts +17 -16
  149. package/src/sany/nodes.ts +6 -13
  150. package/src/sany/report.ts +3 -6
  151. package/src/sany/selectors.ts +35 -38
  152. package/src/sany/xml.ts +23 -55
  153. package/src/search.ts +65 -27
  154. package/src/simulate.ts +157 -133
  155. package/src/spec-description.ts +33 -48
  156. package/src/standard-modules.ts +16 -32
  157. package/src/state-graph.ts +2 -7
  158. package/src/substitution-levels.ts +5 -4
  159. package/src/successors.ts +5 -7
  160. package/src/tlc/messages.ts +20 -15
  161. package/src/tlc/order.ts +2 -9
  162. package/src/tlc/random.ts +4 -4
  163. package/src/tlc/replay.ts +8 -15
  164. package/src/tlc/tlc-operators.ts +2 -3
  165. package/src/tlc/trace-spec.ts +25 -45
  166. package/src/typescript/actions.ts +2 -4
  167. package/src/typescript/collections.ts +34 -20
  168. package/src/typescript/compile.ts +1 -3
  169. package/src/typescript/formula.ts +5 -3
  170. package/src/typescript/model.ts +4 -5
  171. package/src/typescript/steps.ts +20 -18
  172. package/src/values.ts +63 -158
@@ -25,6 +25,20 @@ const decomposeAdd = (set: Expr): [Expr[], Expr] => {
25
25
  return [elements, rest];
26
26
  };
27
27
 
28
+ const BINARY_SET_RULES = new Map<
29
+ string,
30
+ [
31
+ "in_cup" | "in_cap" | "in_setminus",
32
+ "notin_cup" | "notin_cap" | "notin_setminus",
33
+ boolean,
34
+ boolean,
35
+ ]
36
+ >([
37
+ ["TLA.cup", ["in_cup", "notin_cup", true, false]],
38
+ ["TLA.cap", ["in_cap", "notin_cap", false, true]],
39
+ ["TLA.setminus", ["in_setminus", "notin_setminus", false, true]],
40
+ ]);
41
+
28
42
  export const getMembershipNodes = (literal: Literal): Item[] | undefined => {
29
43
  const exprs = literal.context.exprs;
30
44
  const formula = literal.formula;
@@ -137,20 +151,7 @@ export const getMembershipNodes = (literal: Literal): Item[] | undefined => {
137
151
  [[exists]],
138
152
  );
139
153
  }
140
- const binarySetRules: Record<
141
- string,
142
- [
143
- "in_cup" | "in_cap" | "in_setminus",
144
- "notin_cup" | "notin_cap" | "notin_setminus",
145
- boolean,
146
- boolean,
147
- ]
148
- > = {
149
- "TLA.cup": ["in_cup", "notin_cup", true, false],
150
- "TLA.cap": ["in_cap", "notin_cap", false, true],
151
- "TLA.setminus": ["in_setminus", "notin_setminus", false, true],
152
- };
153
- const binarySetRule = set.kind === "app" ? binarySetRules[set.symbol] : undefined;
154
+ const binarySetRule = set.kind === "app" ? BINARY_SET_RULES.get(set.symbol) : undefined;
154
155
  if (binarySetRule !== undefined && set.args.length === 2) {
155
156
  const first = member(exprs, element, set.args[0]);
156
157
  const secondPositive = member(exprs, element, set.args[1]);
@@ -410,14 +410,13 @@ const getBoundedInstances = (context: TlaContext, formula: Expr, goalness: numbe
410
410
 
411
411
  const makePropositionEqualityNode = (
412
412
  exprs: Expressions,
413
- name: "p_eq_l" | "p_eq_r" | "np_eq_l" | "np_eq_r",
413
+ isNegated: boolean,
414
+ isLeft: boolean,
414
415
  formula: Expr,
415
416
  left: Expr,
416
417
  right: Expr,
417
418
  goalness: number,
418
419
  ): Node => {
419
- const isNegated = name === "np_eq_l" || name === "np_eq_r";
420
- const isLeft = name === "p_eq_l" || name === "np_eq_l";
421
420
  const proposition = isNegated && formula.kind === "not" ? formula.args[0] : formula;
422
421
  const equality = equal(exprs, left, right);
423
422
  const differ = exprs.enot(equal(exprs, proposition, isLeft ? left : right));
@@ -426,7 +425,7 @@ const makePropositionEqualityNode = (
426
425
  return {
427
426
  conclusions: [formula, equality],
428
427
  rule: makeRule(
429
- name,
428
+ isNegated ? (isLeft ? "np_eq_l" : "np_eq_r") : isLeft ? "p_eq_l" : "p_eq_r",
430
429
  isNegated
431
430
  ? [formula, equality, differ, rest, proposition, left, right]
432
431
  : [formula, equality, differ, other, formula, left, right],
@@ -446,7 +445,8 @@ const getPropositionEqualityNodes = (context: TlaContext, formula: Expr, goalnes
446
445
  const make = (isLeft: boolean) => (entry: [RelationExpr, number]) =>
447
446
  makePropositionEqualityNode(
448
447
  exprs,
449
- isNegated ? (isLeft ? "np_eq_l" : "np_eq_r") : isLeft ? "p_eq_l" : "p_eq_r",
448
+ isNegated,
449
+ isLeft,
450
450
  formula,
451
451
  entry[0].args[0],
452
452
  entry[0].args[1],
@@ -471,7 +471,8 @@ const getEqualityPropositionNodes = (
471
471
  const make = (isNegated: boolean) => (entry: [Expr, number]) =>
472
472
  makePropositionEqualityNode(
473
473
  exprs,
474
- isNegated ? (isLeft ? "np_eq_l" : "np_eq_r") : isLeft ? "p_eq_l" : "p_eq_r",
474
+ isNegated,
475
+ isLeft,
475
476
  entry[0],
476
477
  formula.args[0],
477
478
  formula.args[1],
package/src/resolve.ts CHANGED
@@ -1581,41 +1581,44 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1581
1581
  );
1582
1582
  const recursive = new Set<Binding>();
1583
1583
  const declarations: { declaration: Declaration; binding: ModuleBinding | undefined }[] = [];
1584
- const createUnit = (
1584
+ const createCheck = (
1585
1585
  location: SourceLocation,
1586
1586
  self: Definition | undefined,
1587
- errors: SanyError[],
1588
- warnings: SanyError[],
1589
1587
  hasLabelScope: boolean,
1590
- ): Unit => ({
1591
- imported: symbols,
1592
- getInstance: unit.getInstance,
1593
- definitions: unit.definitions,
1594
- getKey: unit.getKey,
1588
+ check: (inner: Unit) => void,
1589
+ ): SemanticUnit => ({
1595
1590
  location,
1596
- self,
1597
- facts,
1598
- goals,
1599
- bindings,
1600
- errors,
1601
- warnings,
1602
- hasLabelScope,
1603
- isLabelForbidden: false,
1604
- isInExcept: false,
1605
- labelParams: [],
1606
- labels: new Set(),
1607
- isGenerated: false,
1591
+ check: (errors, warnings) =>
1592
+ check({
1593
+ imported: symbols,
1594
+ getInstance: unit.getInstance,
1595
+ definitions: unit.definitions,
1596
+ getKey: unit.getKey,
1597
+ location,
1598
+ self,
1599
+ facts,
1600
+ goals,
1601
+ bindings,
1602
+ errors,
1603
+ warnings,
1604
+ hasLabelScope,
1605
+ isLabelForbidden: false,
1606
+ isInExcept: false,
1607
+ labelParams: [],
1608
+ labels: new Set(),
1609
+ isGenerated: false,
1610
+ }),
1608
1611
  });
1609
1612
  const bindDeclarations = (declarations: Declaration[], kind: "Constant" | "Variable") =>
1610
- declarations.map((declaration) => ({
1611
- location: declaration.location,
1612
- check: (errors: SanyError[], warnings: SanyError[]) =>
1613
+ declarations.map((declaration) =>
1614
+ createCheck(declaration.location, undefined, false, (inner) =>
1613
1615
  bindModuleName(
1614
1616
  declaration.name,
1615
1617
  { kind, arity: declaration.arity, range: declaration.location.range },
1616
- createUnit(declaration.location, undefined, errors, warnings, false),
1618
+ inner,
1617
1619
  ),
1618
- }));
1620
+ ),
1621
+ );
1619
1622
  return collectSemanticErrors(
1620
1623
  [
1621
1624
  ...unit.reports.map((report) => ({
@@ -1629,9 +1632,8 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1629
1632
  ...bindDeclarations(module.variables, "Variable"),
1630
1633
  ...module.units
1631
1634
  .flatMap((item) => (item.kind === "Recursive" ? item.declarations : []))
1632
- .map((declaration) => ({
1633
- location: declaration.location,
1634
- check: (errors: SanyError[], warnings: SanyError[]) => {
1635
+ .map((declaration) =>
1636
+ createCheck(declaration.location, undefined, false, (inner) => {
1635
1637
  const binding: ModuleBinding = {
1636
1638
  kind: "Definition",
1637
1639
  arity: declaration.arity,
@@ -1643,19 +1645,17 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1643
1645
  declaration.name,
1644
1646
  bindings.get(declaration.name),
1645
1647
  binding,
1646
- createUnit(declaration.location, undefined, errors, warnings, false),
1648
+ inner,
1647
1649
  );
1648
1650
  if (isBound) {
1649
1651
  bindings.set(declaration.name, binding);
1650
1652
  recursive.add(binding);
1651
1653
  }
1652
1654
  declarations.push({ declaration, binding: isBound ? binding : undefined });
1653
- },
1654
- })),
1655
- ...module.definitions.map((definition) => ({
1656
- location: definition.location,
1657
- check: (errors: SanyError[], warnings: SanyError[]) => {
1658
- const inner = createUnit(definition.location, definition, errors, warnings, true);
1655
+ }),
1656
+ ),
1657
+ ...module.definitions.map((definition) =>
1658
+ createCheck(definition.location, definition, true, (inner) => {
1659
1659
  if (isTheoremDefinition(module, definition)) {
1660
1660
  resolveExpression(definition.body, undefined, inner);
1661
1661
  } else if (resolveDefinition(definition, undefined, inner, recursive)) {
@@ -1666,12 +1666,10 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1666
1666
  position: definition.location,
1667
1667
  });
1668
1668
  }
1669
- },
1670
- })),
1671
- ...module.instances.map((instance) => ({
1672
- location: instance.location,
1673
- check: (errors: SanyError[], warnings: SanyError[]) => {
1674
- const inner = createUnit(instance.location, undefined, errors, warnings, false);
1669
+ }),
1670
+ ),
1671
+ ...module.instances.map((instance) =>
1672
+ createCheck(instance.location, undefined, false, (inner) => {
1675
1673
  bindParams(undefined, instance.params, inner);
1676
1674
  unit.instanced
1677
1675
  .get(instance)
@@ -1683,18 +1681,10 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1683
1681
  inner,
1684
1682
  );
1685
1683
  }
1686
- },
1687
- })),
1688
- ...module.assumptions.map((assumption) => ({
1689
- location: assumption.location,
1690
- check: (errors: SanyError[], warnings: SanyError[]) => {
1691
- const inner = createUnit(
1692
- assumption.location,
1693
- undefined,
1694
- errors,
1695
- warnings,
1696
- assumption.name !== undefined,
1697
- );
1684
+ }),
1685
+ ),
1686
+ ...module.assumptions.map((assumption) =>
1687
+ createCheck(assumption.location, undefined, assumption.name !== undefined, (inner) => {
1698
1688
  resolveExpression(assumption.expression, undefined, inner);
1699
1689
  if (assumption.name !== undefined) {
1700
1690
  bindModuleName(
@@ -1703,25 +1693,18 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1703
1693
  inner,
1704
1694
  );
1705
1695
  }
1706
- },
1707
- })),
1708
- ...module.theorems.map((theorem) => ({
1709
- location: theorem.location,
1710
- check: (errors: SanyError[], warnings: SanyError[]) =>
1711
- resolveTheorem(
1712
- theorem,
1713
- createUnit(theorem.location, undefined, errors, warnings, theorem.name !== undefined),
1714
- ),
1715
- })),
1716
- ...module.uses.map((use) => ({
1717
- location: use.location,
1718
- check: (errors: SanyError[], warnings: SanyError[]) =>
1719
- checkFacts(
1720
- use.facts,
1721
- undefined,
1722
- createUnit(use.location, undefined, errors, warnings, false),
1723
- ),
1724
- })),
1696
+ }),
1697
+ ),
1698
+ ...module.theorems.map((theorem) =>
1699
+ createCheck(theorem.location, undefined, theorem.name !== undefined, (inner) =>
1700
+ resolveTheorem(theorem, inner),
1701
+ ),
1702
+ ),
1703
+ ...module.uses.map((use) =>
1704
+ createCheck(use.location, undefined, false, (inner) =>
1705
+ checkFacts(use.facts, undefined, inner),
1706
+ ),
1707
+ ),
1725
1708
  {
1726
1709
  location: module.location.range?.end ?? module.location,
1727
1710
  check: (errors: SanyError[]) =>
@@ -0,0 +1,394 @@
1
+ import { TEMPORAL_LEVEL } from "../levels";
2
+ import type { TlcVersion } from "../tlc/version";
3
+ import type { Expression, SourceLocation } from "../ast";
4
+ import { TlaSyntaxError, TlaUnsupportedError } from "../errors";
5
+ import { BUILTIN_LOCATION, createLevelFields } from "./builtins";
6
+ import {
7
+ addToContext,
8
+ type AssumeProveNode,
9
+ CONSTANT_DECL_KIND,
10
+ type Context,
11
+ type ExprNode,
12
+ type ExprOrOpArgNode,
13
+ type FormalParamNode,
14
+ formatSanyLocation,
15
+ getContextModule,
16
+ getContextSymbol,
17
+ getDeclarations,
18
+ getSymbolArity,
19
+ type LabelNode,
20
+ type LevelNode,
21
+ type ModuleNode,
22
+ type OpApplNode,
23
+ type OpArgNode,
24
+ type OpDefNode,
25
+ type SanyLocation,
26
+ type SymbolNode,
27
+ VARIABLE_DECL_KIND,
28
+ } from "./nodes";
29
+ import { createSelectorResolver } from "./selectors";
30
+ import {
31
+ getExpressionSpan,
32
+ getRangeSpan,
33
+ getSpanLocation,
34
+ getTokenIndex,
35
+ type SourceFile,
36
+ } from "./source";
37
+ import { SANY_OPERATOR_SYNONYMS } from "../tlc/jar-data";
38
+
39
+ const SYNONYMS = new Map(
40
+ SANY_OPERATOR_SYNONYMS.flatMap(([canonical, ...synonyms]) =>
41
+ synonyms.map((synonym) => [synonym, canonical]),
42
+ ),
43
+ );
44
+
45
+ export const resolveSynonym = (name: string) =>
46
+ name
47
+ .split("!")
48
+ .map((part) => SYNONYMS.get(part) ?? (part === "~" ? "\\lnot" : part))
49
+ .join("!");
50
+
51
+ export interface AssumeProveScope {
52
+ isDeclaredBefore: boolean[];
53
+ hasGoal: boolean;
54
+ isSuffices: boolean;
55
+ isInProof: boolean;
56
+ }
57
+
58
+ interface AssumeProveState {
59
+ depth: number;
60
+ isDeclared: boolean[];
61
+ goal: AssumeProveScope | undefined;
62
+ goalClause: number;
63
+ }
64
+
65
+ interface LabelGoal {
66
+ scope: AssumeProveScope;
67
+ clause: number;
68
+ }
69
+
70
+ interface OpApplBinding {
71
+ unbounded?: FormalParamNode[];
72
+ bounded?: FormalParamNode[][];
73
+ tupleOrs?: boolean[];
74
+ ranges?: ExprNode[];
75
+ }
76
+
77
+ export const getTopContext = (contexts: Context[]) => contexts[contexts.length - 1];
78
+
79
+ export const resolveSymbol = (contexts: Context[], name: string) => {
80
+ for (let index = contexts.length - 1; index >= 0; index--) {
81
+ const symbol = getContextSymbol(contexts[index], name);
82
+ if (symbol) return symbol;
83
+ }
84
+ return undefined;
85
+ };
86
+
87
+ const getSymbolKind = (symbol: SymbolNode) =>
88
+ symbol.kind === "OpDecl"
89
+ ? `${symbol.kind}${symbol.declKind}`
90
+ : symbol.kind === "OpDef"
91
+ ? symbol.defKind
92
+ : symbol.kind;
93
+
94
+ export const isSameOrigin = (symbol: SymbolNode, other: SymbolNode) => {
95
+ if (symbol.kind === "OpDef" && other.kind === "OpDef") {
96
+ const source = symbol.source ?? symbol;
97
+ if (source !== (other.source ?? other)) return false;
98
+ return source.module === undefined || isParameterFree(source.module);
99
+ }
100
+ if (symbol.kind === "ThmOrAssumpDef" && other.kind === "ThmOrAssumpDef") {
101
+ const source = symbol.source ?? symbol;
102
+ return source === (other.source ?? other) && isParameterFree(source.module);
103
+ }
104
+ return false;
105
+ };
106
+
107
+ export const isParameterFree = (module: ModuleNode) =>
108
+ getDeclarations(module, CONSTANT_DECL_KIND).length === 0 &&
109
+ getDeclarations(module, VARIABLE_DECL_KIND).length === 0;
110
+
111
+ interface LabelScope {
112
+ labels: Map<string, LabelNode>;
113
+ params: FormalParamNode[][];
114
+ }
115
+
116
+ export interface ModuleGeneration {
117
+ version: TlcVersion | undefined;
118
+ addError: (location: SanyLocation | string | undefined, text: string) => void;
119
+ addWarning: (location: SanyLocation | undefined, text: string) => void;
120
+ getId: () => number;
121
+ builtinsByName: Map<string, OpDefNode>;
122
+ externalModules: Map<string, ModuleNode>;
123
+ nullApplicationId: number;
124
+ file: SourceFile;
125
+ contexts: Context[];
126
+ currentModule: ModuleNode;
127
+ curLevel: number;
128
+ unresolvedCount: number[];
129
+ unresolvedSum: number;
130
+ recursiveSectionCount: number;
131
+ functions: { name: string; node: OpApplNode }[];
132
+ exceptStack: OpApplNode[];
133
+ exceptSpecStack: OpApplNode[];
134
+ labelScopes: LabelScope[];
135
+ assumeContexts: WeakSet<Context>;
136
+ assumeProveState: AssumeProveState;
137
+ assumeProveScopes: WeakMap<AssumeProveNode, AssumeProveScope>;
138
+ labelGoals: WeakMap<LabelNode, LabelGoal>;
139
+ recursiveDeclarations: OpDefNode[];
140
+ selectorToNode: ReturnType<typeof createSelectorResolver>;
141
+ }
142
+
143
+ export const addSymbol = (generation: ModuleGeneration, symbol: SymbolNode) => {
144
+ const binding = resolveSymbol(generation.contexts, symbol.name);
145
+ if (binding === symbol) return;
146
+ if (binding === undefined) {
147
+ addToContext(getTopContext(generation.contexts), symbol);
148
+ return;
149
+ }
150
+ const isConflict =
151
+ symbol.kind === "FormalParam" ||
152
+ getSymbolKind(binding) !== getSymbolKind(symbol) ||
153
+ getSymbolArity(binding) !== getSymbolArity(symbol);
154
+ const isBuiltIn = binding.kind === "OpDef" && binding.defKind === "BuiltIn";
155
+ if (isBuiltIn && !(isConflict && generation.version === "1.7.4")) {
156
+ generation.addError(
157
+ symbol.location,
158
+ `Symbol ${symbol.name} is a built-in operator, and cannot be redefined.`,
159
+ );
160
+ return;
161
+ }
162
+ if (isConflict) {
163
+ generation.addError(
164
+ symbol.location,
165
+ `Multiply-defined symbol '${symbol.name}': this definition or declaration conflicts \nwith the one at ${formatSanyLocation(binding.location)}.`,
166
+ );
167
+ } else if (!isSameOrigin(symbol, binding)) {
168
+ generation.addWarning(
169
+ symbol.location,
170
+ `Multiple declarations or definitions for symbol ${symbol.name}. \nThis duplicates the one at ${formatSanyLocation(binding.location)}.`,
171
+ );
172
+ }
173
+ };
174
+
175
+ export const pushLabelScope = (generation: ModuleGeneration) =>
176
+ generation.labelScopes.push({ labels: new Map(), params: [] });
177
+
178
+ export const popLabels = (generation: ModuleGeneration) =>
179
+ generation.labelScopes.pop()?.labels ?? new Map<string, LabelNode>();
180
+
181
+ export const endProof = (generation: ModuleGeneration, statement: LevelNode) => {
182
+ const scope =
183
+ statement.kind === "AssumeProve" ? generation.assumeProveScopes.get(statement) : undefined;
184
+ if (scope) scope.isInProof = false;
185
+ };
186
+
187
+ export const getLocation = (file: SourceFile, expression: Expression) =>
188
+ getSpanLocation(file, getExpressionSpan(file, expression));
189
+
190
+ export const getUnitSpan = (file: SourceFile, location: SourceLocation) =>
191
+ location.range
192
+ ? getRangeSpan(file, location.range)
193
+ : { start: getTokenIndex(file, location), end: getTokenIndex(file, location) };
194
+
195
+ export const getUnitLocation = (file: SourceFile, location: SourceLocation) =>
196
+ getSpanLocation(file, getUnitSpan(file, location));
197
+
198
+ export const resolveModule = (generation: ModuleGeneration, name: string) => {
199
+ for (let index = generation.contexts.length - 1; index >= 0; index--) {
200
+ const module = getContextModule(generation.contexts[index], name);
201
+ if (module?.kind === "Module") return module;
202
+ }
203
+ return generation.externalModules.get(name);
204
+ };
205
+
206
+ export const getModule = (generation: ModuleGeneration, name: string) => {
207
+ const module = resolveModule(generation, name);
208
+ if (module === undefined) throw new TlaSyntaxError(`Could not find module ${name}`);
209
+ return module;
210
+ };
211
+
212
+ export const withContext = <Result>(
213
+ generation: ModuleGeneration,
214
+ context: Context,
215
+ generate: () => Result,
216
+ ) => {
217
+ generation.contexts.push(context);
218
+ const result = generate();
219
+ generation.contexts.pop();
220
+ return result;
221
+ };
222
+
223
+ export const createFormalParam = (
224
+ generation: ModuleGeneration,
225
+ name: string,
226
+ arity: number,
227
+ location: SanyLocation | undefined,
228
+ isAdded: boolean,
229
+ ): FormalParamNode => {
230
+ const param: FormalParamNode = {
231
+ ...createLevelFields(generation.getId()),
232
+ kind: "FormalParam",
233
+ name,
234
+ arity,
235
+ location,
236
+ };
237
+ if (isAdded) addSymbol(generation, param);
238
+ return param;
239
+ };
240
+
241
+ export const createOpDef = (
242
+ generation: ModuleGeneration,
243
+ fields: Partial<OpDefNode> & Pick<OpDefNode, "name" | "location">,
244
+ ): OpDefNode => ({
245
+ ...createLevelFields(generation.getId()),
246
+ kind: "OpDef",
247
+ defKind: "UserDefined",
248
+ arity: fields.params?.length ?? 0,
249
+ params: [],
250
+ body: undefined,
251
+ isLocal: false,
252
+ module: generation.currentModule,
253
+ source: undefined,
254
+ preComments: [],
255
+ isDefined: true,
256
+ inRecursive: false,
257
+ inRecursiveSection: false,
258
+ recursiveSection: -1,
259
+ letInLevel: 0,
260
+ weights: (fields.params ?? []).map(() => 0),
261
+ isLeibnizArg: (fields.params ?? []).map(() => true),
262
+ isLeibniz: true,
263
+ opLevelCond: undefined,
264
+ maxLevels: (fields.params ?? []).map(() => TEMPORAL_LEVEL),
265
+ minMaxLevel: undefined,
266
+ labels: new Map(),
267
+ step: undefined,
268
+ ...fields,
269
+ });
270
+
271
+ export const setRecursionFields = (generation: ModuleGeneration, definition: OpDefNode) => {
272
+ definition.letInLevel = generation.curLevel;
273
+ if (generation.unresolvedSum > 0) {
274
+ definition.recursiveSection = generation.recursiveSectionCount;
275
+ definition.inRecursiveSection = generation.unresolvedCount[generation.curLevel] > 0;
276
+ generation.currentModule.opDefsInRecursiveSection.push(definition);
277
+ }
278
+ };
279
+
280
+ export const createOpAppl = (
281
+ generation: ModuleGeneration,
282
+ operator: SymbolNode,
283
+ operands: (ExprOrOpArgNode | undefined)[],
284
+ location: SanyLocation,
285
+ binding: OpApplBinding = {},
286
+ id = generation.getId(),
287
+ ): OpApplNode => ({
288
+ ...createLevelFields(id),
289
+ kind: "OpAppl",
290
+ operator,
291
+ operands,
292
+ unbounded: binding.unbounded,
293
+ bounded: binding.bounded,
294
+ tupleOrs: binding.tupleOrs,
295
+ ranges: binding.ranges ?? [],
296
+ location,
297
+ });
298
+
299
+ export const createNullNode = (generation: ModuleGeneration): OpApplNode => ({
300
+ ...createOpAppl(
301
+ generation,
302
+ getBuiltin(generation, "$Nop"),
303
+ [],
304
+ BUILTIN_LOCATION,
305
+ {},
306
+ generation.nullApplicationId,
307
+ ),
308
+ nullKind: "null",
309
+ });
310
+
311
+ export const getBuiltin = (generation: ModuleGeneration, name: string) => {
312
+ const builtin = generation.builtinsByName.get(name);
313
+ if (!builtin) throw new TlaUnsupportedError(`SANY has no builtin operator ${name}`);
314
+ return builtin;
315
+ };
316
+
317
+ export const applyBuiltin = (
318
+ generation: ModuleGeneration,
319
+ name: string,
320
+ operands: (ExprOrOpArgNode | undefined)[],
321
+ location: SanyLocation,
322
+ binding: OpApplBinding = {},
323
+ ) => createOpAppl(generation, getBuiltin(generation, name), operands, location, binding);
324
+
325
+ export const createString = (
326
+ generation: ModuleGeneration,
327
+ value: string,
328
+ location: SanyLocation,
329
+ ): ExprNode => ({
330
+ ...createLevelFields(generation.getId()),
331
+ kind: "String",
332
+ value,
333
+ location,
334
+ });
335
+
336
+ export const createOpArg = (
337
+ generation: ModuleGeneration,
338
+ operator: SymbolNode,
339
+ location: SanyLocation,
340
+ ): OpArgNode => ({
341
+ ...createLevelFields(generation.getId()),
342
+ kind: "OpArg",
343
+ op: operator,
344
+ location,
345
+ });
346
+
347
+ export const resolveName = (generation: ModuleGeneration, name: string, location: SanyLocation) => {
348
+ const symbol = resolveSymbol(generation.contexts, resolveSynonym(name));
349
+ if (symbol === undefined || symbol.kind === "Module") {
350
+ throw new TlaSyntaxError(
351
+ `Unknown operator: \`${name}' at line ${location.beginLine}, column ${location.beginColumn} of module ${location.file}`,
352
+ );
353
+ }
354
+ return symbol;
355
+ };
356
+
357
+ export const matchArguments = (
358
+ generation: ModuleGeneration,
359
+ operator: SymbolNode,
360
+ operands: ExprOrOpArgNode[],
361
+ location: SanyLocation,
362
+ ) => {
363
+ if (operator.kind !== "OpDef" || operator.defKind !== "UserDefined") return;
364
+ const params = operator.params ?? [];
365
+ if (params.length !== operands.length) {
366
+ generation.addError(
367
+ location,
368
+ `Wrong number of arguments (${operands.length}) given to operator '${operator.name}', \nwhich requires ${params.length} arguments.`,
369
+ );
370
+ return;
371
+ }
372
+ params.forEach((param, index) => {
373
+ const operand = operands[index];
374
+ if (param.arity === 0 && operand.kind === "OpArg") {
375
+ generation.addError(
376
+ location,
377
+ `Operator used in argument number ${index + 1} has incorrect number of arguments.`,
378
+ );
379
+ }
380
+ const isMatching =
381
+ operand.kind === "OpArg" &&
382
+ getSymbolArity(operand.op) === param.arity &&
383
+ !(
384
+ operand.op.kind === "OpDef" &&
385
+ (operand.op.params ?? []).some((parameter) => parameter.arity > 0)
386
+ );
387
+ if (param.arity > 0 && !isMatching) {
388
+ generation.addError(
389
+ location,
390
+ `Argument number ${index + 1} to operator '${operator.name}' \nshould be a ${param.arity}-parameter operator.`,
391
+ );
392
+ }
393
+ });
394
+ };