tla-ts 0.0.10-dev.c92e6a4ea → 0.0.10-dev.d166e0ae9

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 (235) hide show
  1. package/dist/compile.cjs +3 -3
  2. package/dist/compile.js +1 -1
  3. package/dist/deciders.cjs +36 -36
  4. package/dist/deciders.js +54 -54
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.cts +13 -3
  7. package/dist/index.d.ts +13 -3
  8. package/dist/index.js +1 -1
  9. package/dist/parallel-worker.cjs +1 -1
  10. package/dist/parallel-worker.js +1 -1
  11. package/dist/prove-worker.cjs +1 -1
  12. package/dist/prove-worker.js +1 -1
  13. package/dist/prove.cjs +68 -68
  14. package/dist/prove.js +78 -78
  15. package/dist/run.cjs +42 -42
  16. package/dist/run.js +44 -44
  17. package/dist/tlapm.cjs +1 -1
  18. package/dist/tlapm.js +2 -2
  19. package/dist/transfer.cjs +45 -43
  20. package/dist/transfer.js +45 -43
  21. package/dist/worker.cjs +7 -7
  22. package/dist/worker.js +7 -7
  23. package/package.json +1 -1
  24. package/src/ast.ts +11 -1
  25. package/src/bags.ts +50 -29
  26. package/src/builtins.ts +4 -3
  27. package/src/check-failure.ts +9 -6
  28. package/src/check-trace.ts +116 -64
  29. package/src/check.ts +356 -173
  30. package/src/cli/tlc-output.ts +1 -0
  31. package/src/cli/tlc.ts +4 -3
  32. package/src/cli/xml-exporter.ts +1 -1
  33. package/src/codegen.ts +34 -13
  34. package/src/coverage.ts +3 -0
  35. package/src/dependencies.ts +61 -13
  36. package/src/dfid.ts +22 -10
  37. package/src/environment.ts +71 -35
  38. package/src/errors.ts +7 -0
  39. package/src/evaluate.ts +149 -54
  40. package/src/exit-codes.ts +29 -15
  41. package/src/instances.ts +16 -6
  42. package/src/java-hash.ts +14 -0
  43. package/src/java-overrides.ts +2 -2
  44. package/src/levels.ts +186 -97
  45. package/src/liveness-checker.ts +131 -83
  46. package/src/liveness.ts +52 -11
  47. package/src/obligations/index.ts +1 -1
  48. package/src/obligations/normalize.ts +1 -4
  49. package/src/obligations/printer.ts +5 -5
  50. package/src/obligations/source.ts +2 -0
  51. package/src/parser.ts +115 -145
  52. package/src/prover/isabelle/isar/attrib.ts +4 -4
  53. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  54. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  55. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  56. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  57. package/src/prover/isabelle/pure/term.ts +3 -3
  58. package/src/prover/prep/md5.ts +26 -29
  59. package/src/prover/smt/rewrite.ts +2 -7
  60. package/src/prover/smt/simplify.ts +1 -1
  61. package/src/prover/smt/solver/arith-rewriter.ts +11 -3
  62. package/src/prover/smt/solver/array-rewriter.ts +12 -2
  63. package/src/prover/smt/solver/asserted-formulas.ts +169 -58
  64. package/src/prover/smt/solver/ast-lt.ts +1 -1
  65. package/src/prover/smt/solver/ast.ts +63 -14
  66. package/src/prover/smt/solver/auf-solver.ts +23 -12
  67. package/src/prover/smt/solver/bit-blast-tactic.ts +26 -0
  68. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  69. package/src/prover/smt/solver/bound-simplifier.ts +11 -13
  70. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  71. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  72. package/src/prover/smt/solver/card2bv.ts +35 -18
  73. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +39 -24
  74. package/src/prover/smt/solver/context.ts +67 -13
  75. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  76. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  77. package/src/prover/smt/solver/dependent-expr-state.ts +26 -15
  78. package/src/prover/smt/solver/diff-neq.ts +1 -2
  79. package/src/prover/smt/solver/dt2bv-tactic.ts +36 -20
  80. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  81. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  82. package/src/prover/smt/solver/elim-uncnstr.ts +5 -8
  83. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  84. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  85. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  86. package/src/prover/smt/solver/euf/egraph.ts +4 -11
  87. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  88. package/src/prover/smt/solver/euf/mam.ts +1 -5
  89. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  90. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  91. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  92. package/src/prover/smt/solver/factor.ts +36 -14
  93. package/src/prover/smt/solver/fd-solver.ts +148 -39
  94. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  95. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  96. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  97. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  98. package/src/prover/smt/solver/goal.ts +6 -3
  99. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  100. package/src/prover/smt/solver/hashtable.ts +4 -0
  101. package/src/prover/smt/solver/internalizer.ts +1 -1
  102. package/src/prover/smt/solver/logic-tactics.ts +9 -2
  103. package/src/prover/smt/solver/lp/lp-settings.ts +5 -1
  104. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  105. package/src/prover/smt/solver/lp/nla-grobner.ts +2 -2
  106. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  107. package/src/prover/smt/solver/lp/pdd.ts +2 -3
  108. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  109. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  110. package/src/prover/smt/solver/maxcore.ts +2 -1
  111. package/src/prover/smt/solver/maxsmt-base.ts +1 -0
  112. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  113. package/src/prover/smt/solver/model-checker.ts +1 -1
  114. package/src/prover/smt/solver/model-evaluator.ts +2 -0
  115. package/src/prover/smt/solver/model-generator.ts +85 -43
  116. package/src/prover/smt/solver/mpf.ts +2 -4
  117. package/src/prover/smt/solver/mus.ts +2 -3
  118. package/src/prover/smt/solver/muz/dl-context.ts +22 -44
  119. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +1 -1
  120. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  121. package/src/prover/smt/solver/muz/dl-rule.ts +8 -9
  122. package/src/prover/smt/solver/muz/hnf.ts +2 -2
  123. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  124. package/src/prover/smt/solver/muz/horn-tactic.ts +15 -2
  125. package/src/prover/smt/solver/muz/rule-properties.ts +22 -0
  126. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  127. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  128. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +1 -1
  129. package/src/prover/smt/solver/nlqsat.ts +1 -1
  130. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  131. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  132. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  133. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  134. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  135. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  136. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  137. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  138. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  139. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  140. package/src/prover/smt/solver/nnf.ts +6 -2
  141. package/src/prover/smt/solver/opt-context.ts +21 -7
  142. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  143. package/src/prover/smt/solver/opt-pareto.ts +19 -0
  144. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  145. package/src/prover/smt/solver/opt-solver.ts +10 -6
  146. package/src/prover/smt/solver/optsmt.ts +1 -1
  147. package/src/prover/smt/solver/parallel-tactic.ts +1 -1
  148. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  149. package/src/prover/smt/solver/poly-rewriter.ts +75 -18
  150. package/src/prover/smt/solver/probes.ts +88 -23
  151. package/src/prover/smt/solver/proto-model.ts +8 -8
  152. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  153. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  154. package/src/prover/smt/solver/qe-lite.ts +2 -2
  155. package/src/prover/smt/solver/qe.ts +3 -2
  156. package/src/prover/smt/solver/qsat.ts +23 -8
  157. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  158. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  159. package/src/prover/smt/solver/rewriter-tpl.ts +7 -6
  160. package/src/prover/smt/solver/rewriter.ts +31 -25
  161. package/src/prover/smt/solver/rlimit.ts +4 -0
  162. package/src/prover/smt/solver/sat/config.ts +1 -1
  163. package/src/prover/smt/solver/sat/goal2sat.ts +0 -1
  164. package/src/prover/smt/solver/sat/inc-sat-solver.ts +81 -28
  165. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  166. package/src/prover/smt/solver/sat/pb-solver.ts +1 -1
  167. package/src/prover/smt/solver/sat/sat-tactic.ts +17 -7
  168. package/src/prover/smt/solver/sat/sat2goal.ts +10 -7
  169. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  170. package/src/prover/smt/solver/sat/solver.ts +25 -47
  171. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  172. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  173. package/src/prover/smt/solver/seq-derive.ts +2 -2
  174. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  175. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  176. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  177. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  178. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  179. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  180. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  181. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  182. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  183. package/src/prover/smt/solver/smt-consequences.ts +1 -1
  184. package/src/prover/smt/solver/smt-kernel.ts +48 -7
  185. package/src/prover/smt/solver/smt-setup.ts +96 -10
  186. package/src/prover/smt/solver/smtlib-parser.ts +589 -224
  187. package/src/prover/smt/solver/smtlib-script.ts +674 -195
  188. package/src/prover/smt/solver/solve-eqs.ts +36 -37
  189. package/src/prover/smt/solver/solver.ts +18 -3
  190. package/src/prover/smt/solver/tactic.ts +332 -189
  191. package/src/prover/smt/solver/theory-bv.ts +13 -3
  192. package/src/prover/smt/solver/theory-fpa.ts +1 -1
  193. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -0
  194. package/src/prover/smt/solver/theory-lra-internalize.ts +2 -0
  195. package/src/prover/smt/solver/theory-lra-propagate.ts +11 -3
  196. package/src/prover/smt/solver/theory-lra.ts +1 -1
  197. package/src/prover/smt/solver/theory-pb.ts +24 -7
  198. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  199. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  200. package/src/prover/smt/solver/tseitin-cnf.ts +1 -0
  201. package/src/prover/tlapm/cache.ts +8 -8
  202. package/src/prover/zenon/index-table.ts +5 -2
  203. package/src/prover/zenon/isar-case.ts +1 -1
  204. package/src/prover/zenon/isar.ts +2 -2
  205. package/src/prover/zenon/phrase.ts +1 -1
  206. package/src/resolve.ts +1071 -251
  207. package/src/runtime.ts +5 -1
  208. package/src/sany/builtins.ts +10 -10
  209. package/src/sany/generation.ts +2 -13
  210. package/src/sany/generator-definitions.ts +3 -1
  211. package/src/sany/generator-expressions.ts +38 -30
  212. package/src/sany/generator-proofs.ts +6 -3
  213. package/src/sany/generator.ts +2 -1
  214. package/src/sany/lexer.ts +3 -3
  215. package/src/sany/modules.ts +4 -2
  216. package/src/sany/nodes.ts +1 -1
  217. package/src/sany/selectors.ts +11 -6
  218. package/src/sany/xml.ts +2 -3
  219. package/src/search.ts +197 -117
  220. package/src/simulate.ts +165 -102
  221. package/src/spec-description.ts +8 -6
  222. package/src/standard-modules.ts +56 -22
  223. package/src/subexpressions.ts +518 -123
  224. package/src/successors.ts +10 -3
  225. package/src/symmetry.ts +2 -1
  226. package/src/tlc/jar-data.ts +10 -0
  227. package/src/tlc/messages.ts +3 -3
  228. package/src/tlc/random.ts +2 -1
  229. package/src/tlc/replay.ts +27 -14
  230. package/src/tlc/tlc-operators.ts +10 -8
  231. package/src/tlc/tlcext-operators.ts +26 -10
  232. package/src/tlc/trace-spec.ts +9 -22
  233. package/src/typed-tier.ts +44 -27
  234. package/src/typescript/types.ts +2 -2
  235. package/src/values.ts +135 -78
@@ -2,6 +2,7 @@ import {
2
2
  getChildren,
3
3
  type AssumeProve,
4
4
  type Bound,
5
+ type Declaration,
5
6
  type Definition,
6
7
  type Expression,
7
8
  type Fact,
@@ -14,17 +15,30 @@ import {
14
15
  type SourceRange,
15
16
  type StepBody,
16
17
  } from "./ast";
17
- import { formatRange, TlaSyntaxError } from "./errors";
18
+ import { formatRange, TlaSyntaxError, type SanyError } from "./errors";
18
19
  import { getSourceName, mapChildren, mapDefinition } from "./instances";
20
+ import { parenthesizedRanges } from "./parser";
21
+ import { STANDARD_LEVELS } from "./standard-definitions";
22
+ import { resolveSynonym } from "./tlc/jar-data";
19
23
  import {
24
+ compareLocations,
20
25
  getArity,
21
26
  getBinder,
22
27
  getNameSelectors,
23
28
  getOperandIndex,
24
29
  getOperands,
30
+ getParamArities,
31
+ isBefore,
25
32
  LOCAL_RESOLUTION,
33
+ nullSelections,
34
+ operatorSelectionErrors,
26
35
  selectionErrors,
36
+ selectionArguments,
27
37
  selections,
38
+ SELECTION_NAME,
39
+ factReferences,
40
+ type NullSelection,
41
+ type SelectionArguments,
28
42
  } from "./resolve";
29
43
 
30
44
  type Lookup = (name: string) => Definition | undefined;
@@ -47,7 +61,49 @@ interface SelectingName {
47
61
  argumentRanges?: (SourceRange | undefined)[];
48
62
  }
49
63
 
50
- const SELECTION_NAME = "$subexpression";
64
+ const declaredArities = new WeakMap<Definition, number>();
65
+ const generatedArgumentCounts = new WeakMap<Expression, number>();
66
+
67
+ const resolveDefinition = (
68
+ definition: Definition,
69
+ resolve: (expression: Expression) => Expression,
70
+ ) => {
71
+ const resolved = mapDefinition(definition, resolve);
72
+ const arity = declaredArities.get(definition);
73
+ if (arity !== undefined) declaredArities.set(resolved, arity);
74
+ return resolved;
75
+ };
76
+
77
+ const setDeclaredArities = (declarations: Declaration[], definitions: Definition[]) =>
78
+ declarations.forEach((declaration) => {
79
+ const definition = definitions.find(
80
+ (candidate) => candidate.isRecursive && candidate.name === declaration.name,
81
+ );
82
+ if (definition) declaredArities.set(definition, declaration.arity);
83
+ });
84
+
85
+ const getSelectorName = (selector: Selector) => {
86
+ switch (selector.kind) {
87
+ case "Name":
88
+ return selector.name;
89
+ case "Operand":
90
+ return typeof selector.operand === "number"
91
+ ? `argument selector ${selector.operand}`
92
+ : selector.operand;
93
+ case "Bound":
94
+ return "!(...)";
95
+ case "At":
96
+ return "@";
97
+ case "Colon":
98
+ return ":";
99
+ }
100
+ };
101
+
102
+ const getExpressionArguments = (
103
+ operator: string,
104
+ range: SourceRange | undefined,
105
+ args: Expression[],
106
+ ): SelectionArguments => ({ operator, range, args, params: args.map(() => 0) });
51
107
 
52
108
  const createError = (message: string, location: SourceLocation) =>
53
109
  new TlaSyntaxError(`${message} at line ${location.line}, column ${location.column}`);
@@ -62,24 +118,33 @@ const findLabel = (
62
118
  }
63
119
  if (expression.kind === "Let")
64
120
  return findLabel(expression.body, name, [...lets, expression.definitions]);
65
- if (expression.kind === "Lambda") return undefined;
66
- for (const child of getChildren(expression)) {
121
+ if (expression.kind === "Lambda" || expression.kind === "Selection") return undefined;
122
+ for (const child of getChildren(expression).slice(0, generatedArgumentCounts.get(expression))) {
67
123
  const found = findLabel(child, name, lets);
68
124
  if (found) return found;
69
125
  }
70
126
  return undefined;
71
127
  };
72
128
 
129
+ const getHiddenLocation = (location: SourceLocation) => ({
130
+ line: location.line,
131
+ column: location.column,
132
+ });
133
+
73
134
  const wrapLets = (body: Expression, lets: Definition[][], location: SourceLocation) =>
74
135
  lets.reduceRight<Expression>(
75
- (inner, definitions) => ({ kind: "Let", definitions, body: inner, location }),
136
+ (inner, definitions) => ({
137
+ kind: "Let",
138
+ definitions,
139
+ body: inner,
140
+ location: getHiddenLocation(location),
141
+ }),
76
142
  body,
77
143
  );
78
144
 
79
145
  const createApplication = (selection: Selection, body: Expression): Expression => {
80
146
  const location = selection.location;
81
- const wrapped = wrapLets(body, selection.lets, location);
82
- if (selection.params.length === 0) return wrapped;
147
+ if (selection.params.length === 0) return body;
83
148
  if (selection.args.length === 0) {
84
149
  if (selection.params.some((param) => param.arity > 0)) {
85
150
  throw createError("Selected an operator with operator parameters as an argument", location);
@@ -87,7 +152,7 @@ const createApplication = (selection: Selection, body: Expression): Expression =
87
152
  return {
88
153
  kind: "Lambda",
89
154
  params: selection.params.map((param) => param.name),
90
- body: wrapped,
155
+ body,
91
156
  location,
92
157
  };
93
158
  }
@@ -104,7 +169,7 @@ const createApplication = (selection: Selection, body: Expression): Expression =
104
169
  kind: "Operator",
105
170
  name: SELECTION_NAME,
106
171
  params: selection.params,
107
- body: wrapped,
172
+ body,
108
173
  isLocal: true,
109
174
  isRecursive: false,
110
175
  location,
@@ -117,7 +182,7 @@ const createApplication = (selection: Selection, body: Expression): Expression =
117
182
  location,
118
183
  resolution: LOCAL_RESOLUTION,
119
184
  },
120
- location,
185
+ location: getHiddenLocation(location),
121
186
  };
122
187
  };
123
188
 
@@ -146,7 +211,10 @@ const applyDefinition = (definition: Definition, selection: Selection) => {
146
211
  location,
147
212
  resolution: LOCAL_RESOLUTION,
148
213
  };
149
- return createApplication({ ...selection, params: [...selection.params, ...params] }, reference);
214
+ return createApplication(
215
+ { ...selection, params: [...selection.params, ...params] },
216
+ wrapLets(reference, selection.lets, location),
217
+ );
150
218
  };
151
219
 
152
220
  const selectSubexpression = (
@@ -158,17 +226,32 @@ const selectSubexpression = (
158
226
  const location = reference.location;
159
227
  const selection: Selection = { params: [], args: [], lets: [], location };
160
228
  let selectorIndex = 0;
161
- let current = undefined as Expression | undefined;
229
+ let operatorIndex = -1;
230
+ let current: Expression | undefined;
231
+ let unwrappedSelection: Expression | undefined;
162
232
  let isFailed = false;
233
+ let generatedArguments = 0;
234
+ const nulls: NullSelection[] = [];
235
+ const applications: SelectionArguments[] = [];
236
+ let expressionError: SanyError | undefined;
237
+ const deferToExpression = (range: SourceRange | undefined, message: string) => {
238
+ if (!expressionError && range) expressionError = { location: formatRange(range), message };
239
+ };
240
+ const checkNull = (node: Expression | undefined, message: string, isEmpty = false) => {
241
+ const range = reference.selectorRanges?.[selectorIndex];
242
+ if (node && range) {
243
+ nulls.push({ node, error: { location: formatRange(range), message }, isEmpty });
244
+ }
245
+ };
163
246
 
164
247
  const report = (range: SourceRange | undefined, message: string) => {
165
248
  if (!range) throw createError(message, location);
166
249
  selectionErrors.set(reference, {
167
- args: selectors
168
- .slice(0, selectorIndex)
169
- .flatMap((selector) => ("args" in selector ? selector.args : [])),
250
+ applications,
251
+ nulls,
170
252
  error: { location: formatRange(range), message },
171
253
  });
254
+ generatedArgumentCounts.set(reference, generatedArguments);
172
255
  isFailed = true;
173
256
  return undefined;
174
257
  };
@@ -178,6 +261,7 @@ const selectSubexpression = (
178
261
  const args: Expression[] = [];
179
262
  while (selectorIndex < selectors.length) {
180
263
  const selector = selectors[selectorIndex];
264
+ if (selector.kind !== "Name" && !local) return undefined;
181
265
  if (selector.kind !== "Name") throw createError("Expected an operator name", location);
182
266
  names.push(selector.name);
183
267
  args.push(...selector.args);
@@ -194,22 +278,60 @@ const selectSubexpression = (
194
278
 
195
279
  const enterDefinition = (local: Definition[] | undefined) => {
196
280
  const found = findDefinition(local);
281
+ if (!found) {
282
+ isFailed = true;
283
+ return undefined;
284
+ }
197
285
  const definition = found.definition;
198
- const arity = getArity(definition);
286
+ const arity = declaredArities.get(definition) ?? getArity(definition);
199
287
  const isLast = selectorIndex === selectors.length - 1;
200
- if (found.args.length !== arity && (!isOperator || found.args.length !== 0)) {
288
+ if (found.args.length !== arity) {
289
+ const range = reference.argumentRanges?.[selectorIndex] ?? location.range;
290
+ const message = `The operator ${resolveSynonym(found.name)} requires ${arity - found.earlier} arguments.`;
291
+ if (!isOperator || found.args.length !== 0) {
292
+ generatedArguments += found.earlier;
293
+ return report(range, message);
294
+ }
295
+ deferToExpression(range, message);
296
+ }
297
+ generatedArguments += found.args.length;
298
+ found.args.forEach((arg, index) =>
299
+ selectionArguments.set(arg, {
300
+ operator: found.name,
301
+ index,
302
+ range: reference.selectorRanges?.[selectorIndex],
303
+ }),
304
+ );
305
+ if (isLast) return { definition, args: found.args };
306
+ const range = definition.location.range;
307
+ const isUndefined =
308
+ declaredArities.has(definition) &&
309
+ range?.module === location.range?.module &&
310
+ isBefore(location, definition.location);
311
+ applications.push({
312
+ operator: found.name,
313
+ range: reference.selectorRanges?.[selectorIndex],
314
+ args: found.args,
315
+ params: isUndefined ? Array(arity).fill(0) : getParamArities(definition),
316
+ });
317
+ if (
318
+ definition.isRecursive &&
319
+ range &&
320
+ range.module === location.range?.module &&
321
+ isBefore(location, range.end)
322
+ ) {
201
323
  return report(
202
- reference.argumentRanges?.[selectorIndex] ?? location.range,
203
- `The operator ${found.name} requires ${arity - found.earlier} arguments.`,
324
+ reference.selectorRanges?.[selectorIndex],
325
+ `Subexpression of \`${found.name}' used inside the operator's definition.`,
204
326
  );
205
327
  }
206
- if (isLast) return { definition, args: found.args };
207
328
  if (definition.kind !== "Operator") {
208
329
  throw createError(`Cannot select a subexpression of ${definition.name}`, location);
209
330
  }
210
331
  selection.params.push(...definition.params);
211
332
  selection.args.push(...found.args);
212
333
  current = definition.body;
334
+ operatorIndex = selectorIndex;
213
335
  selectorIndex++;
214
336
  return undefined;
215
337
  };
@@ -222,12 +344,16 @@ const selectSubexpression = (
222
344
  const found = current && findLabel(current, selector.name, []);
223
345
  if (!found) return report(range, `Cannot find label \`${selector.name}'.`);
224
346
  const params = found.label.params;
225
- if (!isOperator && selector.args.length !== params.length) {
226
- return report(range, `Label \`${selector.name}' used with wrong number of arguments.`);
347
+ if (selector.args.length !== params.length) {
348
+ const message = `Label \`${selector.name}' used with wrong number of arguments.`;
349
+ if (!isOperator) return report(range, message);
350
+ deferToExpression(range, message);
227
351
  }
352
+ generatedArguments += selector.args.length;
228
353
  selection.lets.push(...found.lets);
229
354
  selection.params.push(...params.map((name) => ({ name, arity: 0 })));
230
355
  selection.args.push(...selector.args);
356
+ applications.push(getExpressionArguments(selector.name, range, selector.args));
231
357
  current = found.label.body;
232
358
  selectorIndex++;
233
359
  }
@@ -236,14 +362,35 @@ const selectSubexpression = (
236
362
  const selectOperand = (selector: Selector) => {
237
363
  if (!current) throw createError("Subexpression selection failed", location);
238
364
  if (selector.kind === "Colon") return;
365
+ const range = reference.selectorRanges?.[selectorIndex];
366
+ const noOperands = `Choosing operand \`${getSelectorName(selector)}' of subexpression with no operands.`;
367
+ if (selectionErrors.has(current)) {
368
+ report(range, noOperands);
369
+ return;
370
+ }
371
+ if (selections.has(current) && current.kind !== "Lambda" && current !== unwrappedSelection) {
372
+ checkNull(current, noOperands, true);
373
+ unwrappedSelection = current;
374
+ current =
375
+ current.kind === "Let" &&
376
+ current.body.kind === "Apply" &&
377
+ current.body.operator === SELECTION_NAME
378
+ ? current.body
379
+ : current.kind === "Selection"
380
+ ? current
381
+ : // SANY wraps a selection without parameters in $Nop, whose only operand is the selection.
382
+ { kind: "Tuple", elements: [current], location: current.location };
383
+ }
239
384
  if (current.kind === "Label") {
240
385
  current = current.body;
241
386
  selectOperand(selector);
242
387
  return;
243
388
  }
389
+ const nonexistent = `Nonexistent operand specified by \`${getSelectorName(selector)}'.`;
244
390
  if (current.kind === "Let") {
245
391
  if (selector.kind !== "Operand" || getOperandIndex(selector.operand, 1) !== 0) {
246
- throw createError("A LET/IN expression has only one operand", location);
392
+ report(range, "A LET/IN expression has only one operand.");
393
+ return;
247
394
  }
248
395
  selection.lets.push(current.definitions);
249
396
  current = current.body;
@@ -251,33 +398,83 @@ const selectSubexpression = (
251
398
  }
252
399
  const binder = getBinder(current);
253
400
  if (binder && (selector.kind === "Bound" || selector.kind === "At")) {
401
+ if (selector.kind === "Bound" && selector.args.length !== binder.names.length) {
402
+ report(
403
+ range,
404
+ `Selector with ${selector.args.length} argument(s) used for quantifier with ${binder.names.length} bound identifier(s).`,
405
+ );
406
+ return;
407
+ }
254
408
  selection.params.push(...binder.names.map((name) => ({ name, arity: 0 })));
255
- if (selector.kind === "Bound") selection.args.push(...selector.args);
256
- current = binder.body;
409
+ if (selector.kind === "Bound") {
410
+ generatedArguments += selector.args.length;
411
+ selection.args.push(...selector.args);
412
+ applications.push(getExpressionArguments("", range, selector.args));
413
+ }
414
+ current =
415
+ selections.has(current) && binder.body.kind === "Selection"
416
+ ? binder.body.expression
417
+ : binder.body;
257
418
  return;
258
419
  }
259
- if (current.kind === "Case" && selector.kind === "Operand") {
420
+ if (current.kind === "Case") {
260
421
  const arms = [
261
422
  ...current.arms,
262
423
  ...(current.other ? [{ condition: undefined, body: current.other }] : []),
263
424
  ];
264
- const arm = arms[getOperandIndex(selector.operand, arms.length)];
265
- const next = selectors[selectorIndex + 1];
266
- if (!arm || next?.kind !== "Operand") {
267
- throw createError("A subexpression of CASE must have the form !i!j", location);
425
+ if (selectorIndex === selectors.length - 1) {
426
+ report(range, "Subexpression of CASE must have form !i!j.");
427
+ return;
428
+ }
429
+ const arm =
430
+ selector.kind === "Operand"
431
+ ? arms[getOperandIndex(selector.operand, arms.length)]
432
+ : undefined;
433
+ if (!arm) {
434
+ report(range, nonexistent);
435
+ return;
268
436
  }
269
437
  selectorIndex++;
270
- const part = getOperandIndex(next.operand, 2);
271
- const chosen = part === 0 ? arm.condition : part === 1 ? arm.body : undefined;
272
- if (!chosen) throw createError("Nonexistent CASE operand", location);
438
+ const next = selectors[selectorIndex];
439
+ const part = next.kind === "Operand" ? getOperandIndex(next.operand, 2) : -1;
440
+ const nextRange = reference.selectorRanges?.[selectorIndex];
441
+ if (part === -1) {
442
+ report(
443
+ nextRange,
444
+ "Second selector for CASE subexpression must specify one of two operands.",
445
+ );
446
+ return;
447
+ }
448
+ const chosen = part === 0 ? arm.condition : arm.body;
449
+ if (!chosen) {
450
+ report(nextRange, "Selecting OTHER in a CASE statement.");
451
+ return;
452
+ }
273
453
  current = chosen;
274
454
  return;
275
455
  }
276
- if (selector.kind !== "Operand")
277
- throw createError("Unexpected subexpression selector", location);
456
+ if (
457
+ current.kind === "Except" &&
458
+ selector.kind === "Operand" &&
459
+ getOperandIndex(selector.operand, current.updates.length + 1) > 0
460
+ ) {
461
+ report(range, "Selecting subexpression of an EXCEPT not yet implemented.");
462
+ return;
463
+ }
278
464
  const operands = binder ? binder.sets : getOperands(current);
465
+ if (!operands && current.kind !== "Identifier") {
466
+ report(range, "Selecting subexpression of expression that has none.");
467
+ return;
468
+ }
469
+ if (selector.kind !== "Operand") {
470
+ report(range, nonexistent);
471
+ return;
472
+ }
279
473
  const operand = operands?.[getOperandIndex(selector.operand, operands.length)];
280
- if (!operand) throw createError("Nonexistent operand specified by the selector", location);
474
+ if (!operand) {
475
+ report(range, nonexistent);
476
+ return;
477
+ }
281
478
  current = operand;
282
479
  };
283
480
 
@@ -290,7 +487,11 @@ const selectSubexpression = (
290
487
  if (selector.kind === "Name") {
291
488
  while (current?.kind === "Label") current = current.body;
292
489
  if (current?.kind !== "Let") {
293
- throw createError("A name selector here must be from a LET clause", location);
490
+ report(
491
+ reference.selectorRanges?.[selectorIndex - 1],
492
+ "A name selector here must be from a LET clause.",
493
+ );
494
+ return reference;
294
495
  }
295
496
  selection.lets.push(current.definitions);
296
497
  const last = enterDefinition(current.definitions);
@@ -304,12 +505,74 @@ const selectSubexpression = (
304
505
  followLabels();
305
506
  continue;
306
507
  }
508
+ if (selector.kind === "Colon" && selectors[selectorIndex - 1].kind !== "Name") {
509
+ report(
510
+ reference.selectorRanges?.[selectorIndex - 1],
511
+ "!: should not follow an operand selector.",
512
+ );
513
+ return reference;
514
+ }
515
+ if (
516
+ selector.kind === "Colon" &&
517
+ selectors[selectorIndex + 1]?.kind !== "Name" &&
518
+ (operatorIndex !== selectorIndex - 1 || selectorIndex !== selectors.length - 1)
519
+ ) {
520
+ report(
521
+ reference.selectorRanges?.[selectorIndex],
522
+ "`!:' can be used only after a name and either at the end after an\noperator name or before an operator name.",
523
+ );
524
+ return reference;
525
+ }
526
+ if (selector.kind !== "Colon") {
527
+ checkNull(
528
+ current,
529
+ "Subexpression selection failed, probably due to an error in the selected expression.",
530
+ );
531
+ checkNull(
532
+ current,
533
+ `Choosing operand \`${getSelectorName(selector)}' of subexpression with no operands.`,
534
+ true,
535
+ );
536
+ }
307
537
  selectOperand(selector);
538
+ checkNull(
539
+ current,
540
+ `An unexpected null node specified by '${getSelectorName(selectors[selectorIndex])}'.\nThis is probably due to a previous error.`,
541
+ );
308
542
  selectorIndex++;
309
543
  }
310
544
  if (isFailed) return reference;
311
545
  if (!current) throw createError("Subexpression selection failed", location);
312
- return createApplication(selection, current);
546
+ const params = selection.params.length;
547
+ const args = selection.args.length;
548
+ if (params !== args) {
549
+ const message = `Expected ${params} arguments but found ${args}.`;
550
+ if (!isOperator || args > 0) {
551
+ report(location.range, message);
552
+ return reference;
553
+ }
554
+ deferToExpression(location.range, message);
555
+ }
556
+ const body = wrapLets(current, selection.lets, location);
557
+ const share = (expression: Expression): Expression => ({
558
+ kind: "Selection",
559
+ expression,
560
+ // SANY's $Nop, which TLC's call stack shows at the reference, wraps only a selection without parameters.
561
+ location:
562
+ selection.params.length === 0 && body.kind !== "Lambda"
563
+ ? location
564
+ : getHiddenLocation(location),
565
+ });
566
+ // SANY selects a LAMBDA itself rather than wrapping it in $Nop, so the selection keeps its arity.
567
+ const selected = createApplication(
568
+ selection,
569
+ body.kind !== "Lambda"
570
+ ? share(body)
571
+ : { ...body, body: selections.has(body) ? body.body : share(body.body), location },
572
+ );
573
+ nullSelections.set(selected, nulls);
574
+ if (expressionError) operatorSelectionErrors.set(selected, expressionError);
575
+ return selected;
313
576
  };
314
577
 
315
578
  const getQualifiedSelectors = (
@@ -338,18 +601,43 @@ const resolveSubexpressions = (
338
601
  ): Expression => {
339
602
  if (!containsReference(expression)) return expression;
340
603
  if (expression.kind === "Let") {
604
+ if (expression.recursive) setDeclaredArities(expression.recursive, expression.definitions);
605
+ const resolved: Definition[] = [];
341
606
  const local: Lookup = (name) =>
342
- expression.definitions.find((definition) => definition.name === name) ?? lookup(name);
343
- const mapped = mapChildren(expression, (child) => resolveSubexpressions(child, local, isGoal));
344
- return mapped.kind === "Let" && mapped.instances
607
+ resolved.find((definition) => definition.name === name) ??
608
+ expression.definitions.find((definition) => definition.name === name) ??
609
+ lookup(name);
610
+ const isLocalGoal = (name: string) =>
611
+ !expression.definitions.some((definition) => definition.name === name) && isGoal(name);
612
+ expression.definitions.forEach((definition) =>
613
+ resolved.push(
614
+ resolveDefinition(definition, (child) => resolveSubexpressions(child, local, isLocalGoal)),
615
+ ),
616
+ );
617
+ const mapped = {
618
+ ...expression,
619
+ definitions: resolved,
620
+ body: resolveSubexpressions(expression.body, local, isLocalGoal),
621
+ };
622
+ return mapped.instances
345
623
  ? {
346
624
  ...mapped,
347
- instances: mapped.instances.map((instance) => resolveInstance(instance, local, isGoal)),
625
+ instances: mapped.instances.map((instance) =>
626
+ resolveInstance(instance, local, isLocalGoal),
627
+ ),
348
628
  }
349
629
  : mapped;
350
630
  }
351
631
  const callee = expression.kind === "Apply" ? lookup(expression.operator) : undefined;
352
- const mapped =
632
+ // SANY expects an operator argument only of a user-defined operator, which a standard module's built-in operators stand for.
633
+ const calleeParams =
634
+ callee?.kind === "Operator"
635
+ ? callee.params
636
+ : expression.kind === "Apply"
637
+ ? STANDARD_LEVELS.get(expression.operator.slice(expression.operator.lastIndexOf("!") + 1))
638
+ ?.formals
639
+ : undefined;
640
+ const rebuilt =
353
641
  expression.kind === "Apply"
354
642
  ? {
355
643
  ...expression,
@@ -358,11 +646,15 @@ const resolveSubexpressions = (
358
646
  arg,
359
647
  lookup,
360
648
  isGoal,
361
- callee?.kind !== "Operator" || callee.params[index]?.arity !== 0,
649
+ calleeParams !== undefined && calleeParams[index]?.arity !== 0,
362
650
  ),
363
651
  ),
364
652
  }
365
653
  : mapChildren(expression, (child) => resolveSubexpressions(child, lookup, isGoal));
654
+ const children = getChildren(expression);
655
+ const mapped = getChildren(rebuilt).every((child, index) => child === children[index])
656
+ ? expression
657
+ : rebuilt;
366
658
  const selectors =
367
659
  mapped.kind === "Subexpression"
368
660
  ? mapped.selectors
@@ -372,9 +664,39 @@ const resolveSubexpressions = (
372
664
  ? getQualifiedSelectors(mapped.operator, mapped.args, mapped.argumentCounts, lookup)
373
665
  : undefined;
374
666
  const first = selectors?.[0];
375
- if (!selectors || (first?.kind === "Name" && isGoal(first.name))) return mapped;
667
+ const setGeneratedArguments = (count: number) => {
668
+ generatedArgumentCounts.set(expression, count);
669
+ generatedArgumentCounts.set(mapped, count);
670
+ };
671
+ if (!selectors) {
672
+ if (mapped.kind === "Apply" && mapped.operator.includes("!") && !lookup(mapped.operator)) {
673
+ setGeneratedArguments(0);
674
+ }
675
+ return mapped;
676
+ }
677
+ const nameCount = selectors.findIndex((selector) => selector.kind !== "Name");
678
+ const names = selectors.slice(0, nameCount === -1 ? selectors.length : nameCount);
679
+ const isQualified = names.some(
680
+ (_name, index) =>
681
+ index > 0 &&
682
+ lookup(
683
+ names
684
+ .slice(0, index + 1)
685
+ .map(getSelectorName)
686
+ .join("!"),
687
+ ),
688
+ );
689
+ if (first?.kind === "Name" && isGoal(first.name) && !isQualified) return mapped;
690
+ if (first?.kind === "Name" && selectors[1].kind !== "Name" && !lookup(first.name)) {
691
+ setGeneratedArguments(0);
692
+ return mapped;
693
+ }
376
694
  const selected = selectSubexpression(selectors, lookup, mapped, isOperator);
377
- if (selected !== mapped) selections.add(selected);
695
+ const generated = generatedArgumentCounts.get(mapped);
696
+ if (generated !== undefined) setGeneratedArguments(generated);
697
+ const parenthesized = parenthesizedRanges.get(expression);
698
+ if (parenthesized && selected !== mapped) parenthesizedRanges.set(selected, parenthesized);
699
+ if (selected !== mapped) selections.set(selected, mapped);
378
700
  return selected;
379
701
  };
380
702
 
@@ -427,100 +749,173 @@ export const resolveModuleSubexpressions = (module: Module, available: Definitio
427
749
  },
428
750
  ];
429
751
  });
430
- const lookup = createLookup([...available, ...module.definitions]);
752
+ const own = new Set([...module.definitions, ...clauses]);
753
+ setDeclaredArities(
754
+ module.units.flatMap((unit) => (unit.kind === "Recursive" ? unit.declarations : [])),
755
+ module.definitions,
756
+ );
757
+ const recursive = new Map(
758
+ module.units.flatMap((unit): [string, SourceLocation][] =>
759
+ unit.kind === "Recursive"
760
+ ? unit.declarations.map((declaration) => [declaration.name, declaration.location])
761
+ : [],
762
+ ),
763
+ );
764
+ const isDeclaredBefore = (definition: Definition, location: SourceLocation) => {
765
+ const declared = recursive.get(definition.name);
766
+ return (
767
+ isBefore(definition.location, location) ||
768
+ (definition.isRecursive && declared !== undefined && isBefore(declared, location))
769
+ );
770
+ };
771
+ const resolvedDefinitions = new Map<Definition, Definition>();
772
+ const getVisibleLookup =
773
+ (lookup: Lookup, location: SourceLocation): Lookup =>
774
+ (name) => {
775
+ const definition = lookup(name);
776
+ if (!definition || (own.has(definition) && !isDeclaredBefore(definition, location))) {
777
+ return undefined;
778
+ }
779
+ return resolvedDefinitions.get(definition) ?? definition;
780
+ };
781
+ const proofLookup = createLookup([...available, ...module.definitions]);
431
782
  const isGoal = (name: string) => goals.has(name);
432
783
  const definitionLookup = createLookup([...available, ...module.definitions, ...clauses]);
433
- const resolve = (expression: Expression) =>
784
+ const resolve = (expression: Expression, location: SourceLocation) =>
434
785
  resolveSubexpressions(
435
786
  expression,
436
- definitionLookup,
787
+ getVisibleLookup(definitionLookup, location),
437
788
  (name) => isGoal(name) && clauses.every((clause) => clause.name !== name),
438
789
  );
439
- const isProofGoal = (name: string) => isGoal(name) || !lookup(name);
440
- const resolveInProof = (expression: Expression) =>
441
- resolveSubexpressions(expression, lookup, isProofGoal);
442
- const resolveFacts = (facts: Fact[]) =>
443
- facts.map((fact) => (fact.kind === "ModuleFact" ? fact : resolveInProof(fact)));
444
- const resolveBounds = (bounds: Bound[]) =>
445
- bounds.map((bound) => ({ ...bound, set: resolveInProof(bound.set) }));
446
- const resolveStatement = (statement: Expression | AssumeProve): Expression | AssumeProve =>
447
- statement.kind === "AssumeProve"
448
- ? {
449
- ...statement,
450
- assumptions: statement.assumptions.map((assumption) =>
451
- assumption.kind === "NewSymbol"
452
- ? { ...assumption, set: assumption.set && resolveInProof(assumption.set) }
453
- : resolveStatement(assumption),
454
- ),
455
- conclusion: resolveInProof(statement.conclusion),
456
- }
457
- : resolveInProof(statement);
458
- const resolveStep = (body: StepBody): StepBody => {
459
- switch (body.kind) {
460
- case "Use":
461
- case "Hide":
462
- return { ...body, facts: resolveFacts(body.facts) };
463
- case "Instance":
464
- return resolveInstance(body, lookup, isProofGoal);
465
- case "Define":
466
- return {
467
- ...body,
468
- definitions: body.definitions.map((definition) =>
469
- definition.kind === "Instance"
470
- ? resolveInstance(definition, lookup, isProofGoal)
471
- : mapDefinition(definition, resolveInProof),
472
- ),
473
- };
474
- case "Have":
475
- case "Case":
476
- return { ...body, expression: resolveInProof(body.expression) };
477
- case "Witness":
478
- return { ...body, expressions: body.expressions.map(resolveInProof) };
479
- case "Take":
480
- return { ...body, bounds: resolveBounds(body.bounds) };
481
- case "Pick":
482
- return { ...body, bounds: resolveBounds(body.bounds), body: resolveInProof(body.body) };
483
- case "Assert":
484
- return { ...body, statement: resolveStatement(body.statement) };
485
- default:
486
- return body;
487
- }
488
- };
489
- const resolveProof = (proof: Proof | undefined): Proof | undefined =>
490
- proof?.kind === "By"
491
- ? { ...proof, facts: resolveFacts(proof.facts) }
492
- : proof?.kind === "Steps"
790
+ const createProofResolver = (lookup: Lookup) => {
791
+ const isProofGoal = (name: string) => isGoal(name) || !lookup(name);
792
+ const resolveInProof = (expression: Expression) =>
793
+ resolveSubexpressions(expression, lookup, isProofGoal);
794
+ const resolveFacts = (facts: Fact[]) => {
795
+ const resolved = facts.map((fact) =>
796
+ fact.kind === "ModuleFact" ? fact : resolveInProof(fact),
797
+ );
798
+ factReferences.set(resolved, facts);
799
+ return resolved;
800
+ };
801
+ const resolveBounds = (bounds: Bound[]) =>
802
+ bounds.map((bound) => ({ ...bound, set: resolveInProof(bound.set) }));
803
+ const resolveStatement = (statement: Expression | AssumeProve): Expression | AssumeProve =>
804
+ statement.kind === "AssumeProve"
493
805
  ? {
494
- ...proof,
495
- steps: proof.steps.map((step) => ({
496
- ...step,
497
- body: resolveStep(step.body),
498
- proof: resolveProof(step.proof),
499
- })),
806
+ ...statement,
807
+ assumptions: statement.assumptions.map((assumption) =>
808
+ assumption.kind === "NewSymbol"
809
+ ? { ...assumption, set: assumption.set && resolveInProof(assumption.set) }
810
+ : resolveStatement(assumption),
811
+ ),
812
+ conclusion: resolveInProof(statement.conclusion),
500
813
  }
501
- : proof;
502
- const resolved = {
503
- ...module,
504
- theorems: module.theorems.map((theorem) => ({
505
- ...theorem,
506
- statement:
507
- theorem.name !== undefined && theorem.statement.kind !== "AssumeProve"
508
- ? theorem.statement
509
- : resolveStatement(theorem.statement),
510
- proof: resolveProof(theorem.proof),
511
- })),
512
- uses: module.uses.map((use) => ({ ...use, facts: resolveFacts(use.facts) })),
814
+ : resolveInProof(statement);
815
+ const resolveStep = (body: StepBody): StepBody => {
816
+ switch (body.kind) {
817
+ case "Use":
818
+ case "Hide":
819
+ return { ...body, facts: resolveFacts(body.facts) };
820
+ case "Instance":
821
+ return resolveInstance(body, lookup, isProofGoal);
822
+ case "Define":
823
+ return {
824
+ ...body,
825
+ definitions: body.definitions.map((definition) =>
826
+ definition.kind === "Instance"
827
+ ? resolveInstance(definition, lookup, isProofGoal)
828
+ : resolveDefinition(definition, resolveInProof),
829
+ ),
830
+ };
831
+ case "Have":
832
+ case "Case":
833
+ return { ...body, expression: resolveInProof(body.expression) };
834
+ case "Witness":
835
+ return { ...body, expressions: body.expressions.map(resolveInProof) };
836
+ case "Take":
837
+ return { ...body, bounds: resolveBounds(body.bounds) };
838
+ case "Pick":
839
+ return { ...body, bounds: resolveBounds(body.bounds), body: resolveInProof(body.body) };
840
+ case "Assert":
841
+ return { ...body, statement: resolveStatement(body.statement) };
842
+ default:
843
+ return body;
844
+ }
845
+ };
846
+ const resolveProof = (proof: Proof | undefined): Proof | undefined => {
847
+ if (proof?.kind === "By") return { ...proof, facts: resolveFacts(proof.facts) };
848
+ if (proof?.kind !== "Steps") return proof;
849
+ let resolver = { lookup, resolveStep, resolveProof };
850
+ return {
851
+ ...proof,
852
+ steps: proof.steps.map((step) => {
853
+ const resolved = {
854
+ ...step,
855
+ body: resolver.resolveStep(step.body),
856
+ proof: resolver.resolveProof(step.proof),
857
+ };
858
+ if (resolved.body.kind === "Define") {
859
+ const definitions = resolved.body.definitions.flatMap((definition) =>
860
+ definition.kind === "Instance" ? [] : [definition],
861
+ );
862
+ const outer = resolver.lookup;
863
+ resolver = createProofResolver(
864
+ (name) => definitions.find((definition) => definition.name === name) ?? outer(name),
865
+ );
866
+ }
867
+ return resolved;
868
+ }),
869
+ };
870
+ };
871
+ return { lookup, resolveFacts, resolveStatement, resolveStep, resolveProof };
513
872
  };
514
873
  const hasReferences =
515
874
  module.definitions.some((definition) => containsReference(definition.body)) ||
516
875
  module.assumptions.some((assumption) => containsReference(assumption.expression));
876
+ if (hasReferences) {
877
+ [...module.definitions, ...clauses]
878
+ .toSorted((left, right) => compareLocations(left.location, right.location))
879
+ .forEach((definition) =>
880
+ resolvedDefinitions.set(
881
+ definition,
882
+ resolveDefinition(definition, (expression) => resolve(expression, definition.location)),
883
+ ),
884
+ );
885
+ }
886
+ const resolved = {
887
+ ...module,
888
+ theorems: module.theorems.map((theorem) => {
889
+ const resolver = createProofResolver(getVisibleLookup(proofLookup, theorem.location));
890
+ return {
891
+ ...theorem,
892
+ statement:
893
+ theorem.name !== undefined && theorem.statement.kind !== "AssumeProve"
894
+ ? theorem.statement
895
+ : resolver.resolveStatement(theorem.statement),
896
+ proof:
897
+ theorem.proof &&
898
+ createProofResolver(getVisibleLookup(proofLookup, theorem.proof.location)).resolveProof(
899
+ theorem.proof,
900
+ ),
901
+ };
902
+ }),
903
+ uses: module.uses.map((use) => ({
904
+ ...use,
905
+ facts: createProofResolver(getVisibleLookup(proofLookup, use.location)).resolveFacts(
906
+ use.facts,
907
+ ),
908
+ })),
909
+ };
517
910
  if (!hasReferences) return resolved;
518
911
  return {
519
912
  ...resolved,
520
- definitions: module.definitions.map((definition) => mapDefinition(definition, resolve)),
913
+ definitions: module.definitions.map(
914
+ (definition) => resolvedDefinitions.get(definition) ?? definition,
915
+ ),
521
916
  assumptions: module.assumptions.map((assumption) => ({
522
917
  ...assumption,
523
- expression: resolve(assumption.expression),
918
+ expression: resolve(assumption.expression, assumption.location),
524
919
  })),
525
920
  };
526
921
  };