tla-ts 0.0.10-dev.37a75eb5b → 0.0.10-dev.45c0eaef5

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