tla-ts 0.0.10-dev.d618a2d79 → 0.0.10-dev.e5c8dc315

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