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

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 (252) 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 +49 -44
  20. package/dist/transfer.js +48 -43
  21. package/dist/worker.cjs +7 -7
  22. package/dist/worker.js +7 -7
  23. package/package.json +1 -1
  24. package/src/ast.ts +14 -2
  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 +116 -64
  29. package/src/check.ts +516 -280
  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 +190 -1
  37. package/src/dependencies.ts +68 -15
  38. package/src/dfid.ts +101 -36
  39. package/src/environment.ts +123 -38
  40. package/src/errors.ts +7 -0
  41. package/src/evaluate.ts +370 -99
  42. package/src/exit-codes.ts +28 -14
  43. package/src/instances.ts +135 -11
  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 +51 -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/arith-rewriter.ts +11 -3
  67. package/src/prover/smt/solver/array-rewriter.ts +12 -2
  68. package/src/prover/smt/solver/asserted-formulas.ts +171 -58
  69. package/src/prover/smt/solver/ast-lt.ts +1 -1
  70. package/src/prover/smt/solver/ast.ts +66 -14
  71. package/src/prover/smt/solver/auf-solver.ts +23 -12
  72. package/src/prover/smt/solver/bit-blast-tactic.ts +27 -1
  73. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  74. package/src/prover/smt/solver/bound-simplifier.ts +11 -13
  75. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  76. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  77. package/src/prover/smt/solver/card2bv.ts +35 -18
  78. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +39 -24
  79. package/src/prover/smt/solver/context.ts +84 -15
  80. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  81. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  82. package/src/prover/smt/solver/dependent-expr-state.ts +28 -16
  83. package/src/prover/smt/solver/diff-neq.ts +1 -2
  84. package/src/prover/smt/solver/dt2bv-tactic.ts +57 -21
  85. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  86. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  87. package/src/prover/smt/solver/elim-uncnstr.ts +5 -8
  88. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  89. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  90. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  91. package/src/prover/smt/solver/euf/egraph.ts +4 -11
  92. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  93. package/src/prover/smt/solver/euf/mam.ts +1 -5
  94. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  95. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  96. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  97. package/src/prover/smt/solver/factor.ts +36 -14
  98. package/src/prover/smt/solver/fd-solver.ts +608 -139
  99. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  100. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  101. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  102. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  103. package/src/prover/smt/solver/goal.ts +6 -3
  104. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  105. package/src/prover/smt/solver/hashtable.ts +4 -0
  106. package/src/prover/smt/solver/internalizer.ts +1 -1
  107. package/src/prover/smt/solver/logic-tactics.ts +15 -5
  108. package/src/prover/smt/solver/lp/core-solver.ts +12 -8
  109. package/src/prover/smt/solver/lp/lar-solver.ts +1 -1
  110. package/src/prover/smt/solver/lp/lp-settings.ts +6 -2
  111. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  112. package/src/prover/smt/solver/lp/nla-grobner.ts +158 -80
  113. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  114. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -2
  115. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -20
  116. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -39
  117. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  118. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  119. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  120. package/src/prover/smt/solver/maxcore.ts +2 -1
  121. package/src/prover/smt/solver/maxsmt-base.ts +1 -0
  122. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  123. package/src/prover/smt/solver/model-checker.ts +1 -1
  124. package/src/prover/smt/solver/model-evaluator.ts +2 -0
  125. package/src/prover/smt/solver/model-generator.ts +85 -43
  126. package/src/prover/smt/solver/mpf.ts +2 -4
  127. package/src/prover/smt/solver/mus.ts +2 -3
  128. package/src/prover/smt/solver/muz/dl-context.ts +22 -44
  129. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +1 -1
  130. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  131. package/src/prover/smt/solver/muz/dl-rule.ts +8 -9
  132. package/src/prover/smt/solver/muz/hnf.ts +2 -2
  133. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  134. package/src/prover/smt/solver/muz/horn-tactic.ts +15 -2
  135. package/src/prover/smt/solver/muz/rule-properties.ts +22 -0
  136. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  137. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  138. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +1 -1
  139. package/src/prover/smt/solver/nlqsat.ts +1 -1
  140. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  141. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  142. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  143. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  144. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  145. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  146. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  147. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  148. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  149. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  150. package/src/prover/smt/solver/nnf.ts +6 -2
  151. package/src/prover/smt/solver/opt-context.ts +21 -7
  152. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  153. package/src/prover/smt/solver/opt-pareto.ts +19 -0
  154. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  155. package/src/prover/smt/solver/opt-solver.ts +10 -6
  156. package/src/prover/smt/solver/optsmt.ts +1 -1
  157. package/src/prover/smt/solver/parallel-tactic.ts +1 -1
  158. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  159. package/src/prover/smt/solver/poly-rewriter.ts +75 -18
  160. package/src/prover/smt/solver/probes.ts +88 -23
  161. package/src/prover/smt/solver/proto-model.ts +8 -8
  162. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  163. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  164. package/src/prover/smt/solver/qe-lite.ts +2 -2
  165. package/src/prover/smt/solver/qe.ts +3 -2
  166. package/src/prover/smt/solver/qsat.ts +23 -8
  167. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  168. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  169. package/src/prover/smt/solver/rewriter-tpl.ts +7 -6
  170. package/src/prover/smt/solver/rewriter.ts +31 -25
  171. package/src/prover/smt/solver/rlimit.ts +7 -3
  172. package/src/prover/smt/solver/sat/config.ts +1 -1
  173. package/src/prover/smt/solver/sat/goal2sat.ts +65 -12
  174. package/src/prover/smt/solver/sat/inc-sat-solver.ts +129 -43
  175. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  176. package/src/prover/smt/solver/sat/pb-constraint.ts +7 -0
  177. package/src/prover/smt/solver/sat/pb-solver.ts +26 -7
  178. package/src/prover/smt/solver/sat/sat-tactic.ts +17 -7
  179. package/src/prover/smt/solver/sat/sat2goal.ts +72 -48
  180. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  181. package/src/prover/smt/solver/sat/solver.ts +27 -47
  182. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  183. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  184. package/src/prover/smt/solver/seq-derive.ts +2 -2
  185. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  186. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  187. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  188. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  189. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  190. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  191. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  192. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  193. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  194. package/src/prover/smt/solver/smt-consequences.ts +1 -1
  195. package/src/prover/smt/solver/smt-kernel.ts +48 -7
  196. package/src/prover/smt/solver/smt-setup.ts +106 -13
  197. package/src/prover/smt/solver/smtlib-parser.ts +589 -224
  198. package/src/prover/smt/solver/smtlib-script.ts +713 -210
  199. package/src/prover/smt/solver/solve-eqs.ts +36 -37
  200. package/src/prover/smt/solver/solver.ts +18 -3
  201. package/src/prover/smt/solver/tactic.ts +350 -195
  202. package/src/prover/smt/solver/theory-bv.ts +13 -3
  203. package/src/prover/smt/solver/theory-fpa.ts +1 -1
  204. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -0
  205. package/src/prover/smt/solver/theory-lra-internalize.ts +2 -0
  206. package/src/prover/smt/solver/theory-lra-propagate.ts +11 -3
  207. package/src/prover/smt/solver/theory-lra-state.ts +1 -1
  208. package/src/prover/smt/solver/theory-lra.ts +1 -1
  209. package/src/prover/smt/solver/theory-pb.ts +24 -7
  210. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  211. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  212. package/src/prover/smt/solver/theory-without-terms.ts +24 -0
  213. package/src/prover/smt/solver/tseitin-cnf.ts +1 -0
  214. package/src/prover/tlapm/cache.ts +8 -8
  215. package/src/prover/zenon/index-table.ts +5 -2
  216. package/src/prover/zenon/isar-case.ts +1 -1
  217. package/src/prover/zenon/isar.ts +2 -2
  218. package/src/prover/zenon/phrase.ts +1 -1
  219. package/src/resolve.ts +1274 -257
  220. package/src/runtime.ts +7 -1
  221. package/src/sany/builtins.ts +10 -10
  222. package/src/sany/generation.ts +5 -15
  223. package/src/sany/generator-def-entries.ts +123 -36
  224. package/src/sany/generator-definitions.ts +5 -3
  225. package/src/sany/generator-expressions.ts +60 -37
  226. package/src/sany/generator-proofs.ts +18 -12
  227. package/src/sany/generator.ts +12 -6
  228. package/src/sany/lexer.ts +15 -7
  229. package/src/sany/modules.ts +4 -2
  230. package/src/sany/nodes.ts +1 -1
  231. package/src/sany/selectors.ts +11 -6
  232. package/src/sany/xml.ts +2 -3
  233. package/src/search.ts +319 -135
  234. package/src/simulate.ts +235 -182
  235. package/src/spec-description.ts +8 -6
  236. package/src/standard-definitions.ts +1 -0
  237. package/src/standard-modules.ts +56 -22
  238. package/src/subexpressions.ts +564 -138
  239. package/src/successors.ts +37 -13
  240. package/src/symmetry.ts +2 -1
  241. package/src/tlc/jar-data.ts +10 -0
  242. package/src/tlc/messages.ts +3 -3
  243. package/src/tlc/order.ts +14 -3
  244. package/src/tlc/random.ts +2 -1
  245. package/src/tlc/replay.ts +67 -43
  246. package/src/tlc/tlc-operators.ts +10 -8
  247. package/src/tlc/tlcext-operators.ts +44 -15
  248. package/src/tlc/trace-spec.ts +9 -22
  249. package/src/trace-liveness.ts +529 -0
  250. package/src/typed-tier.ts +52 -31
  251. package/src/typescript/types.ts +2 -2
  252. package/src/values.ts +150 -79
package/src/resolve.ts CHANGED
@@ -18,9 +18,14 @@ import {
18
18
  type Selector,
19
19
  type SourceLocation,
20
20
  type SourceRange,
21
+ type StepBody,
21
22
  type Theorem,
23
+ type UseOrHide,
22
24
  } from "./ast";
23
25
  import { formatRange, TlaSyntaxError, type SanyError } from "./errors";
26
+ import { defEntryErrors, getDefEntryBinder, parenthesizedRanges } from "./parser";
27
+ import { formatSanyLocation } from "./sany/nodes";
28
+ import { resolveSynonym } from "./tlc/jar-data";
24
29
 
25
30
  export type SymbolKind =
26
31
  | "Builtin"
@@ -37,6 +42,7 @@ interface Binding {
37
42
  arity: number;
38
43
  params?: number[];
39
44
  range?: SourceRange;
45
+ functionArity?: number;
40
46
  }
41
47
 
42
48
  export interface ModuleSymbol extends Binding {
@@ -49,6 +55,7 @@ interface Goal {
49
55
  statement: Expression | AssumeProve;
50
56
  isSuffices: boolean;
51
57
  isInProof: boolean;
58
+ keyword: string | undefined;
52
59
  }
53
60
 
54
61
  interface LocalName extends Binding {
@@ -56,7 +63,7 @@ interface LocalName extends Binding {
56
63
  parent: LocalName | undefined;
57
64
  goal?: Goal;
58
65
  isPending?: boolean;
59
- isNonFact?: boolean;
66
+ nonFactStep?: "Use" | "Hide" | "Instance" | "Define";
60
67
  }
61
68
 
62
69
  interface ModuleBinding extends Binding {
@@ -69,6 +76,7 @@ interface Unit {
69
76
  getInstance: (instance: Instance) => InstancedModule;
70
77
  definitions: Map<string, Definition>;
71
78
  getKey: (definition: Definition) => string;
79
+ isModuleKnown: (name: string, location: SourceLocation) => boolean;
72
80
  location: SourceLocation;
73
81
  self: Definition | undefined;
74
82
  facts: Set<string>;
@@ -84,8 +92,16 @@ interface Unit {
84
92
  isGenerated: boolean;
85
93
  }
86
94
 
87
- interface SelectionError {
95
+ export interface SelectionArguments {
96
+ operator: string;
97
+ range: SourceRange | undefined;
88
98
  args: Expression[];
99
+ params: number[];
100
+ }
101
+
102
+ interface SelectionError {
103
+ applications: SelectionArguments[];
104
+ nulls: NullSelection[];
89
105
  error: SanyError;
90
106
  }
91
107
 
@@ -99,8 +115,43 @@ type Reference = Expression & { kind: "Identifier" | "Apply" | "Subexpression" }
99
115
 
100
116
  export const LOCAL_RESOLUTION = { kind: "Local" } as const;
101
117
 
102
- export const selections = new WeakSet<Expression>();
118
+ export const SELECTION_NAME = "$subexpression";
119
+
120
+ export interface NullSelection {
121
+ node: Expression;
122
+ error: SanyError;
123
+ isEmpty: boolean;
124
+ applications: SelectionArguments[];
125
+ }
126
+
127
+ interface SelectionArgument {
128
+ operator: string;
129
+ index: number;
130
+ range: SourceRange | undefined;
131
+ }
132
+
133
+ export const selections = new WeakMap<Expression, Expression>();
103
134
  export const selectionErrors = new WeakMap<Expression, SelectionError>();
135
+ export const operatorSelectionErrors = new WeakMap<Expression, SanyError>();
136
+ export const factReferences = new WeakMap<Fact[], Fact[]>();
137
+ export const selectionArguments = new WeakMap<Expression, SelectionArgument>();
138
+ export const nullSelections = new WeakMap<Expression, NullSelection[]>();
139
+ export const generatedArgumentCounts = new WeakMap<Expression, number>();
140
+ const unresolvedExpressions = new WeakSet<Expression>();
141
+ const emptyExpressions = new WeakSet<Expression>();
142
+
143
+ // SANY's failed selection is an operator application with no operands.
144
+ const isEmptyExpression = (expression: Expression): boolean =>
145
+ emptyExpressions.has(expression) || findNullError(nullSelections.get(expression)) !== undefined;
146
+
147
+ const findNullSelection = (nulls: NullSelection[] | undefined) =>
148
+ nulls?.find((selection) =>
149
+ selection.isEmpty
150
+ ? isEmptyExpression(selection.node)
151
+ : unresolvedExpressions.has(selection.node),
152
+ );
153
+
154
+ const findNullError = (nulls: NullSelection[] | undefined) => findNullSelection(nulls)?.error;
104
155
 
105
156
  const renamedArities = new WeakMap<Expression, number>();
106
157
 
@@ -111,13 +162,20 @@ const isKey = (name: string) => {
111
162
  return index > 0 && index < name.length - 1;
112
163
  };
113
164
 
114
- const CORE_SYMBOLS: Symbols = new Map(
115
- ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2, kind: "Builtin" }]),
116
- );
165
+ const CORE_SYMBOLS: Symbols = new Map([
166
+ ...["~>", "-+->", "\\cdot", "\\X"].map((name): [string, ModuleSymbol] => [
167
+ name,
168
+ { key: name, arity: 2, kind: "Builtin" },
169
+ ]),
170
+ ["'", { key: "'", arity: 1, kind: "Builtin" }],
171
+ ]);
117
172
 
118
173
  export const isBefore = (left: SourceLocation, right: SourceLocation) =>
119
174
  left.line < right.line || (left.line === right.line && left.column < right.column);
120
175
 
176
+ export const compareLocations = (left: SourceLocation, right: SourceLocation) =>
177
+ isBefore(left, right) ? -1 : isBefore(right, left) ? 1 : 0;
178
+
121
179
  export const getArity = (definition: Definition) =>
122
180
  definition.kind === "Operator" ? definition.params.length : 0;
123
181
 
@@ -126,6 +184,11 @@ export const getParamArities = (definition: Definition) =>
126
184
 
127
185
  const isInstantiated = (definition: Definition) => definition.name.includes("!");
128
186
 
187
+ export const getFunctionArity = (definition: Definition) =>
188
+ definition.kind === "Function" && !isInstantiated(definition)
189
+ ? definition.bounds.length
190
+ : undefined;
191
+
129
192
  const lookupLocal = (scope: LocalName | undefined, name: string) => {
130
193
  for (let current = scope; current; current = current.parent) {
131
194
  if (current.name === name) return current;
@@ -157,7 +220,7 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
157
220
  if (current.kind === "Builtin") {
158
221
  unit.errors.push({
159
222
  location,
160
- message: `Symbol ${name} is a built-in operator, and cannot be redefined.`,
223
+ message: `Symbol ${resolveSynonym(name)} is a built-in operator, and cannot be redefined.`,
161
224
  });
162
225
  } else if (
163
226
  added.kind === "Parameter" ||
@@ -166,12 +229,12 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
166
229
  ) {
167
230
  unit.errors.push({
168
231
  location,
169
- message: `Multiply-defined symbol '${name}': this definition or declaration conflicts \nwith the one at ${existing}.`,
232
+ message: `Multiply-defined symbol '${resolveSynonym(name)}': this definition or declaration conflicts \nwith the one at ${existing}.`,
170
233
  });
171
234
  } else {
172
235
  unit.warnings.push({
173
236
  location,
174
- message: `Multiple declarations or definitions for symbol ${name}. \nThis duplicates the one at ${existing}.`,
237
+ message: `Multiple declarations or definitions for symbol ${resolveSynonym(name)}. \nThis duplicates the one at ${existing}.`,
175
238
  });
176
239
  }
177
240
  return false;
@@ -230,26 +293,44 @@ export const getBoundNames = (bounds: Bound[]) =>
230
293
 
231
294
  const getVisibleDefinition = (name: string, unit: Unit) => {
232
295
  const definition = unit.definitions.get(name);
296
+ const binding = getModuleBinding(name, unit, undefined);
233
297
  const isVisible =
234
298
  definition !== undefined &&
235
299
  (definition === unit.self
236
- ? definition.kind === "Function" || definition.isRecursive
237
- : definition.isRecursive || isBefore(definition.location, unit.location));
300
+ ? definition.isRecursive
301
+ : definition.isRecursive
302
+ ? binding !== undefined
303
+ : isBefore(definition.location, unit.location) &&
304
+ (binding === undefined || !isBefore(binding.position, definition.location)));
238
305
  return isVisible ? definition : undefined;
239
306
  };
240
307
 
241
308
  const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
242
309
  const definition = getVisibleDefinition(name, unit);
243
- return definition
244
- ? {
245
- key: unit.getKey(definition),
246
- arity: getArity(definition),
247
- params: getParamArities(definition),
248
- kind: "Definition",
249
- }
250
- : unit.imported.get(name);
310
+ if (definition) {
311
+ const declared = definition.isRecursive ? unit.bindings.get(name) : undefined;
312
+ return {
313
+ key: unit.getKey(definition),
314
+ arity: declared?.arity ?? getArity(definition),
315
+ params: declared?.params ?? getParamArities(definition),
316
+ kind: "Definition",
317
+ range: definition.location.range,
318
+ functionArity: getFunctionArity(definition),
319
+ };
320
+ }
321
+ const binding = getModuleBinding(name, unit, undefined);
322
+ if (binding?.isPending) {
323
+ return { key: name, arity: binding.arity, params: binding.params, kind: binding.kind };
324
+ }
325
+ return binding ? unit.imported.get(name) : undefined;
251
326
  };
252
327
 
328
+ const isFact = (name: string, unit: Unit) =>
329
+ unit.facts.has(name) || unit.bindings.get(name)?.kind === "Theorem";
330
+
331
+ const getGoal = (name: string, unit: Unit) =>
332
+ unit.bindings.get(name)?.kind === "Theorem" ? unit.goals.get(name) : undefined;
333
+
253
334
  const findBinding = (name: string, scope: LocalName | undefined, unit: Unit): Binding | undefined =>
254
335
  lookupLocal(scope, name) ?? findSymbol(name, unit);
255
336
 
@@ -271,12 +352,22 @@ const getSpelledNameRange = (
271
352
  };
272
353
 
273
354
  const getFixity = (expression: Expression) => {
274
- if (expression.kind !== "Apply") return undefined;
355
+ if (expression.kind !== "Apply" || expression.argumentsRange) return undefined;
275
356
  if (expression.args.length === 2) return "infix";
276
357
  if (expression.args.length !== 1) return undefined;
277
- return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
358
+ return expression.operator === "-." ? "prefix" : "postfix";
278
359
  };
279
360
 
361
+ const BUILTIN_LOCATION = "In module --TLA+ BUILTINS--";
362
+
363
+ const SELECTABLE_KINDS = new Set<SymbolKind>(["Definition", "Instance", "Theorem"]);
364
+
365
+ const reportUnselectable = (name: string, range: SourceRange, unit: Unit) =>
366
+ unit.errors.push({
367
+ location: formatRange(range),
368
+ message: `Cannot take subexpression of \`${resolveSynonym(name)}'.`,
369
+ });
370
+
280
371
  const isOperatorSymbol = (name: string) => !/^[\p{L}\d_]/u.test(name);
281
372
 
282
373
  const isStepName = (name: string) =>
@@ -388,6 +479,7 @@ export const getOperands = (expression: Expression): Expression[] | undefined =>
388
479
  case "Enabled":
389
480
  case "Always":
390
481
  case "Eventually":
482
+ case "Selection":
391
483
  return [expression.expression];
392
484
  case "BoxAction":
393
485
  case "AngleAction":
@@ -416,12 +508,19 @@ const isInScopeOfDeclaration = (assumeProve: AssumeProve, clause: number) =>
416
508
 
417
509
  const findLabel = (expression: Expression, name: string): LabelExpression | undefined => {
418
510
  if (expression.kind === "Label") return expression.name === name ? expression : undefined;
419
- if (expression.kind === "Lambda") return undefined;
511
+ if (expression.kind === "Lambda" || expression.kind === "Selection") return undefined;
420
512
  if (expression.kind === "Let") return findLabel(expression.body, name);
421
- return getChildren(expression).reduce<LabelExpression | undefined>(
422
- (found, child) => found ?? findLabel(child, name),
423
- undefined,
424
- );
513
+ const generated = generatedArgumentCounts.get(expression);
514
+ if (expression.kind === "Apply" && generated === undefined && isEmptyExpression(expression))
515
+ return undefined;
516
+ if (expression.kind === "FunctionApplication" && isEmptyExpression(expression))
517
+ return findLabel(expression.function, name);
518
+ return getChildren(expression)
519
+ .slice(0, generated)
520
+ .reduce<LabelExpression | undefined>(
521
+ (found, child) => found ?? findLabel(child, name),
522
+ undefined,
523
+ );
425
524
  };
426
525
 
427
526
  const findClauseLabel = (
@@ -453,7 +552,6 @@ const checkSelection = (
453
552
  reference: Reference,
454
553
  selectors: Selector[],
455
554
  goal: Goal,
456
- scope: LocalName | undefined,
457
555
  unit: Unit,
458
556
  isFact: boolean,
459
557
  ) => {
@@ -462,6 +560,7 @@ const checkSelection = (
462
560
  (index === undefined ? undefined : reference.selectorRanges?.[index]) ??
463
561
  reference.location.range;
464
562
  if (range) unit.errors.push({ location: formatRange(range), message });
563
+ return undefined;
465
564
  };
466
565
  const isOutOfScope = goal.isSuffices === goal.isInProof;
467
566
  const statement = goal.statement;
@@ -470,6 +569,8 @@ const checkSelection = (
470
569
  isGoal: true,
471
570
  isSufficesOpen: goal.isSuffices,
472
571
  };
572
+ let params = 0;
573
+ let args = 0;
473
574
  for (const [offset, selector] of selectors.slice(1).entries()) {
474
575
  const index = offset + 1;
475
576
  const node = state.node;
@@ -479,9 +580,7 @@ const checkSelection = (
479
580
  node.kind !== "NewSymbol" &&
480
581
  node.kind !== "AssumeProve" &&
481
582
  getLabelBody(node).kind === "Let";
482
- return isLet
483
- ? undefined
484
- : report(index - 1, "A name selector here must be from a LET clause.");
583
+ return isLet ? node : report(index - 1, "A name selector here must be from a LET clause.");
485
584
  }
486
585
  const clauses =
487
586
  statement.kind === "AssumeProve"
@@ -519,10 +618,30 @@ const checkSelection = (
519
618
  state.isSufficesOpen = false;
520
619
  continue;
521
620
  }
522
- if (selector.kind !== "Operand") return;
523
- const operand = getOperandName(selector.operand);
621
+ if (selector.kind === "Colon") {
622
+ if (selectors[index - 1].kind !== "Name") {
623
+ return report(index - 1, "!: should not follow an operand selector.");
624
+ }
625
+ const next = selectors[index + 1];
626
+ if (next === undefined ? index !== 1 : next.kind !== "Name") {
627
+ return report(
628
+ index,
629
+ "`!:' can be used only after a name and either at the end after an\noperator name or before an operator name.",
630
+ );
631
+ }
632
+ continue;
633
+ }
634
+ const operand =
635
+ selector.kind === "Operand"
636
+ ? getOperandName(selector.operand)
637
+ : selector.kind === "At"
638
+ ? "@"
639
+ : "!(...)";
640
+ const getPosition = (count: number) =>
641
+ selector.kind === "Operand" ? getOperandIndex(selector.operand, count) : -1;
642
+ const unexpectedNull = `An unexpected null node specified by '${operand}'.\nThis is probably due to a previous error.`;
524
643
  if (state.isSufficesOpen) {
525
- if (getOperandIndex(selector.operand, 1) !== 0) {
644
+ if (getPosition(1) !== 0) {
526
645
  return report(
527
646
  index,
528
647
  node.kind === "AssumeProve"
@@ -533,20 +652,37 @@ const checkSelection = (
533
652
  state.isSufficesOpen = false;
534
653
  continue;
535
654
  }
536
- if (node.kind === "NewSymbol") return;
655
+ if (node.kind === "NewSymbol") return node;
537
656
  if (node.kind !== "AssumeProve") {
538
657
  const expression = getLabelBody(node);
658
+ if (unresolvedExpressions.has(expression)) {
659
+ return report(
660
+ index,
661
+ "Subexpression selection failed, probably due to an error in the selected expression.",
662
+ );
663
+ }
539
664
  if (["Number", "Decimal", "String"].includes(expression.kind)) {
540
665
  return report(index, "Selecting subexpression of expression that has none.");
541
666
  }
542
- const kind =
543
- expression.kind === "Identifier"
544
- ? findBinding(expression.name, scope, unit)?.kind
545
- : undefined;
546
- if (kind === "Variable" || kind?.startsWith("New")) {
667
+ if (isEmptyExpression(expression)) {
547
668
  return report(index, `Choosing operand \`${operand}' of subexpression with no operands.`);
548
669
  }
549
- const sets = getBinder(expression)?.sets;
670
+ const binder = getBinder(expression);
671
+ if (binder && selector.kind !== "Operand") {
672
+ const count = selector.kind === "Bound" ? selector.args.length : 0;
673
+ if (selector.kind === "Bound" && count !== binder.names.length) {
674
+ return report(
675
+ index,
676
+ `Selector with ${count} argument(s) used for quantifier with ${binder.names.length} bound identifier(s).`,
677
+ );
678
+ }
679
+ params += binder.names.length;
680
+ args += count;
681
+ state.node = binder.body;
682
+ state.isGoal = false;
683
+ continue;
684
+ }
685
+ const sets = binder?.sets;
550
686
  const operands =
551
687
  expression.kind === "Identifier"
552
688
  ? []
@@ -554,18 +690,21 @@ const checkSelection = (
554
690
  ? sets.length > 0
555
691
  ? sets
556
692
  : undefined
557
- : expression.kind === "Except"
558
- ? undefined
559
- : getOperands(expression);
560
- if (!operands) return;
561
- const position = getOperandIndex(selector.operand, operands.length);
693
+ : getOperands(expression);
694
+ if (!operands) return node;
695
+ const isExcept = expression.kind === "Except";
696
+ const position = getPosition(isExcept ? expression.updates.length + 1 : operands.length);
562
697
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
698
+ if (isExcept && position > 0) {
699
+ return report(index, "Selecting subexpression of an EXCEPT not yet implemented.");
700
+ }
563
701
  state.node = operands[position];
564
702
  state.isGoal = false;
703
+ if (unresolvedExpressions.has(state.node)) return report(index, unexpectedNull);
565
704
  continue;
566
705
  }
567
706
  const clauses = [...node.assumptions, node.conclusion];
568
- const position = getOperandIndex(selector.operand, clauses.length);
707
+ const position = getPosition(clauses.length);
569
708
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
570
709
  if (isInScopeOfDeclaration(node, position) && (!state.isGoal || isOutOfScope)) {
571
710
  return report(index, `Accessing ASSUME/PROVE clause ${SCOPE_MESSAGE}`);
@@ -576,14 +715,24 @@ const checkSelection = (
576
715
  }
577
716
  state.node = clause;
578
717
  state.isGoal = false;
718
+ if (
719
+ clause.kind !== "NewSymbol" &&
720
+ clause.kind !== "AssumeProve" &&
721
+ unresolvedExpressions.has(clause)
722
+ ) {
723
+ return report(index, unexpectedNull);
724
+ }
579
725
  }
580
- if (isFact) return;
581
726
  if (state.node.kind === "AssumeProve") {
582
- report(undefined, "Selected ASSUME/PROVE instead of expression.");
727
+ return isFact ? state.node : report(undefined, "Selected ASSUME/PROVE instead of expression.");
583
728
  }
584
729
  if (state.node.kind === "NewSymbol") {
585
- report(undefined, "Selected a NEW declaration as an expression or operator.");
730
+ return isFact
731
+ ? state.node
732
+ : report(undefined, "Selected a NEW declaration as an expression or operator.");
586
733
  }
734
+ if (params !== args) return report(undefined, `Expected ${params} arguments but found ${args}.`);
735
+ return state.node;
587
736
  };
588
737
 
589
738
  const isLabelReported = (label: LabelExpression, unit: Unit) => {
@@ -659,10 +808,18 @@ const checkReference = (
659
808
  const first = selectors[0];
660
809
  const goal =
661
810
  selectors.length > 1 && first.kind === "Name"
662
- ? (lookupLocal(scope, first.name)?.goal ?? unit.goals.get(first.name))
811
+ ? (lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit))
663
812
  : undefined;
664
- if (goal) checkSelection(expression, selectors, goal, scope, unit, isFact);
665
- return goal !== undefined;
813
+ return goal && { node: checkSelection(expression, selectors, goal, unit, isFact) };
814
+ };
815
+
816
+ const isInstanceName = (name: string, scope: LocalName | undefined, unit: Unit) => {
817
+ const binding = lookupLocal(scope, name) ?? getModuleBinding(name, unit, undefined);
818
+ if (binding) return binding.kind === "Instance";
819
+ return (
820
+ findInstance(name, scope, unit) !== undefined &&
821
+ [...unit.bindings.keys()].some((key) => key.startsWith(`${name}!`))
822
+ );
666
823
  };
667
824
 
668
825
  const getSymbolArity = (
@@ -677,18 +834,53 @@ const getSymbolArity = (
677
834
  if (renamed !== undefined) return renamed;
678
835
  if (isKey(name)) return expression.kind === "Apply" ? expression.args.length : 0;
679
836
  const local = lookupLocal(scope, name);
680
- if (local?.isNonFact) {
837
+ if (local?.nonFactStep) {
681
838
  unit.errors.push({
682
839
  location: formatRange(getSpelledNameRange(expression, name)),
683
840
  message: "Step number of non-expression step used as an expression.",
684
841
  });
685
842
  return undefined;
686
843
  }
844
+ const keyword = local?.goal?.keyword;
845
+ if (keyword) {
846
+ unit.errors.push({
847
+ location: formatRange(getSpelledNameRange(expression, name)),
848
+ message: `${keyword} proof step selected instead of expression.`,
849
+ });
850
+ return undefined;
851
+ }
687
852
  if (checkReference(expression, scope, unit, false) || (isStepName(name) && local)) {
688
853
  return expression.kind === "Apply" ? expression.args.length : 0;
689
854
  }
855
+ if (isInstanceName(name, scope, unit)) {
856
+ const instance = lookupLocal(scope, name) ?? getModuleBinding(name, unit, undefined);
857
+ const count = expression.kind === "Apply" ? expression.args.length : 0;
858
+ if (instance?.kind === "Instance" && instance.arity !== count) {
859
+ unit.errors.push({
860
+ location: formatRange(
861
+ (expression.kind === "Apply" && expression.argumentsRange) ||
862
+ getSpelledNameRange(expression, name),
863
+ ),
864
+ message: `The operator ${name} requires ${instance.arity} arguments.`,
865
+ });
866
+ return undefined;
867
+ }
868
+ const range = getSpelledNameRange(expression, name);
869
+ unit.errors.push({
870
+ location: formatRange({
871
+ ...range,
872
+ start: {
873
+ line: range.end.line,
874
+ column: range.end.column - name.slice(name.lastIndexOf("!") + 1).length + 1,
875
+ },
876
+ }),
877
+ message: `Operator name ${name} is incomplete.`,
878
+ });
879
+ return undefined;
880
+ }
690
881
  if (local && expression.kind !== "OperatorReference") expression.resolution = LOCAL_RESOLUTION;
691
882
  if (local) return local.arity;
883
+ if (getGoal(name, unit)?.statement.kind === "AssumeProve") return 0;
692
884
  const symbol = findSymbol(name, unit);
693
885
  if (symbol) {
694
886
  if (expression.kind === "Identifier") expression.name = symbol.key;
@@ -697,29 +889,58 @@ const getSymbolArity = (
697
889
  return symbol.arity;
698
890
  }
699
891
  const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
700
- const isSelected =
892
+ const selected =
893
+ prefix === "" ? undefined : (lookupLocal(scope, prefix) ?? findSymbol(prefix, unit));
894
+ if (
895
+ selected &&
896
+ (!SELECTABLE_KINDS.has(selected.kind) || lookupLocal(scope, prefix)?.nonFactStep)
897
+ ) {
898
+ reportUnselectable(
899
+ prefix,
900
+ (expression.kind !== "OperatorReference" && expression.selectorRanges?.[0]) ||
901
+ getSpelledNameRange(expression, name),
902
+ unit,
903
+ );
904
+ return undefined;
905
+ }
906
+ if (
907
+ expression.kind !== "OperatorReference" &&
701
908
  prefix !== "" &&
702
- (lookupLocal(scope, prefix) !== undefined ||
703
- findSymbol(prefix, unit) !== undefined ||
704
- unit.facts.has(prefix));
705
- if (isSelected) {
909
+ isPendingSelectionReported(
910
+ prefix,
911
+ expression.kind === "Apply" && expression.argumentCounts
912
+ ? expression.args.slice(0, expression.argumentCounts[0])
913
+ : [],
914
+ expression.selectorRanges?.[0],
915
+ (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ?? location.range,
916
+ scope,
917
+ unit,
918
+ )
919
+ ) {
920
+ return undefined;
921
+ }
922
+ if (selected || (prefix !== "" && isFact(prefix, unit))) {
706
923
  return expression.kind === "Apply" ? expression.args.length : 0;
707
924
  }
708
- const spelling = (expression.kind === "Identifier" ? undefined : expression.spelling) ?? name;
709
- const range = formatRange(
710
- expression.kind === "Apply" && spelling === "-."
711
- ? getNameRange(location, "-")
712
- : getSpelledNameRange(expression, name),
713
- );
714
- if (!isOperatorSymbol(name) || isStepName(name)) {
715
- unit.errors.push({ location: range, message: `Unknown operator: \`${name}'.` });
925
+ const fixity = getFixity(expression);
926
+ const isOperatorApplication = expression.kind === "OperatorReference" || fixity !== undefined;
927
+ if (!isOperatorSymbol(name) || isStepName(name) || !isOperatorApplication) {
928
+ unit.errors.push({
929
+ location: formatRange(getSpelledNameRange(expression, name)),
930
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
931
+ });
716
932
  return undefined;
717
933
  }
934
+ const spelling = expression.spelling ?? name;
718
935
  unit.errors.push({
719
- location: range,
936
+ location: formatRange(
937
+ fixity === "prefix" && spelling === "-."
938
+ ? getNameRange(location, "-")
939
+ : getSpelledNameRange(expression, name),
940
+ ),
720
941
  message: `Could not find declaration or definition of symbol '${spelling}'.`,
721
942
  });
722
- const fixity = getFixity(expression);
943
+ if (fixity) unresolvedExpressions.add(expression);
723
944
  if (fixity && location.range) {
724
945
  unit.errors.push({
725
946
  location: formatRange(location.range),
@@ -774,15 +995,30 @@ const resolveDefinition = (
774
995
  const isDeclared = current?.isPending === true && recursive.has(current);
775
996
  if (current?.isPending && !isDeclared) {
776
997
  report(
777
- `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${name} defined at wrong LET/IN level.`,
998
+ `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${resolveSynonym(name)} defined at wrong LET/IN level.`,
778
999
  );
779
1000
  } else if (current && !isDeclared) {
780
1001
  report(
781
1002
  definition.kind === "Function"
782
1003
  ? `Function name \`${name}' already defined or declared.`
783
- : `Operator ${name} already defined or declared.`,
1004
+ : `Operator ${resolveSynonym(name)} already defined or declared.`,
1005
+ );
1006
+ } else if (current && definition.kind === "Function" && current.arity > 0) {
1007
+ report(`Function ${resolveSynonym(name)} has operator arguments in its RECURSIVE declaration.`);
1008
+ } else if (
1009
+ current &&
1010
+ definition.kind === "Operator" &&
1011
+ // Deviation from SANY: Generator#processOperator compares only the last parameter's arity with the RECURSIVE declaration's.
1012
+ (current.arity !== definition.params.length ||
1013
+ definition.params.some((param) => param.arity > 0))
1014
+ ) {
1015
+ report(
1016
+ `Definition of ${resolveSynonym(name)} has different arity than its RECURSIVE declaration.`,
784
1017
  );
785
1018
  }
1019
+ if (current && isDeclared && definition.kind === "Operator") {
1020
+ current.params = getParamArities(definition);
1021
+ }
786
1022
  if (definition.kind === "Function") {
787
1023
  resolveExpression(
788
1024
  definition.body,
@@ -793,8 +1029,10 @@ const resolveDefinition = (
793
1029
  definition.isSelfReferential = isReferenced(definition.body, name);
794
1030
  } else resolveExpression(definition.body, inner, unit);
795
1031
  if (current && isDeclared) {
796
- current.isPending = false;
797
- current.range = range;
1032
+ if (definition.kind === "Operator" || current.arity === 0) {
1033
+ current.isPending = false;
1034
+ current.range = range;
1035
+ }
798
1036
  return false;
799
1037
  }
800
1038
  return definition.kind === "Function"
@@ -812,10 +1050,15 @@ const resolveDefinitions = (
812
1050
  scope: LocalName | undefined,
813
1051
  unit: Unit,
814
1052
  instances: Instance[] = [],
1053
+ declarations: Declaration[] = [],
815
1054
  ) => {
816
1055
  const recursive = new Set<Binding>();
817
1056
  const declared = definitions
818
- .filter((definition) => definition.isRecursive)
1057
+ .filter(
1058
+ (definition) =>
1059
+ definition.isRecursive &&
1060
+ declarations.every((declaration) => declaration.name !== definition.name),
1061
+ )
819
1062
  .reduce<LocalName | undefined>((parent, definition) => {
820
1063
  if (lookupLocal(parent, definition.name)?.isPending) return parent;
821
1064
  const local: LocalName = {
@@ -829,28 +1072,62 @@ const resolveDefinitions = (
829
1072
  recursive.add(local);
830
1073
  return local;
831
1074
  }, scope);
832
- const pending = unit.isGenerated ? [] : [...instances];
833
- const resolveInstances = (
1075
+ const declaredLocals = new Map<Declaration, LocalName | undefined>();
1076
+ const bindDeclaration = (parent: LocalName | undefined, declaration: Declaration) => {
1077
+ const binding: Binding = {
1078
+ kind: "Definition",
1079
+ arity: declaration.arity,
1080
+ params: Array(declaration.arity).fill(0),
1081
+ range: declaration.location.range,
1082
+ };
1083
+ const local: LocalName | undefined = isBindable(
1084
+ declaration.name,
1085
+ lookupLocal(parent, declaration.name) ??
1086
+ getModuleBinding(declaration.name, unit, binding.range),
1087
+ binding,
1088
+ unit,
1089
+ )
1090
+ ? { ...binding, name: declaration.name, parent, isPending: true }
1091
+ : undefined;
1092
+ if (local) recursive.add(local);
1093
+ declaredLocals.set(declaration, local);
1094
+ return local ?? parent;
1095
+ };
1096
+ const pending = [...(unit.isGenerated ? [] : instances), ...declarations].toSorted(
1097
+ (left, right) => compareLocations(left.location, right.location),
1098
+ );
1099
+ const resolvePending = (
834
1100
  current: LocalName | undefined,
835
- isDue: (instance: Instance) => boolean,
1101
+ isDue: (item: Instance | Declaration) => boolean,
836
1102
  ) => {
837
- const count = pending.findIndex((instance) => !isDue(instance));
1103
+ const count = pending.findIndex((item) => !isDue(item));
838
1104
  return pending
839
1105
  .splice(0, count === -1 ? pending.length : count)
840
- .reduce((parent, instance) => resolveLocalInstance(instance, parent, unit), current);
1106
+ .reduce(
1107
+ (parent, item) =>
1108
+ "kind" in item ? resolveLocalInstance(item, parent, unit) : bindDeclaration(parent, item),
1109
+ current,
1110
+ );
841
1111
  };
842
1112
  const resolved = definitions.reduce<LocalName | undefined>((previous, definition) => {
843
1113
  const current = isKey(definition.name)
844
1114
  ? previous
845
- : resolveInstances(previous, (instance) => !isBefore(definition.location, instance.location));
1115
+ : resolvePending(previous, (item) => !isBefore(definition.location, item.location));
846
1116
  const local: LocalName = {
847
1117
  name: definition.name,
848
1118
  arity: getArity(definition),
849
1119
  kind: "Definition",
850
1120
  range: definition.location.range,
851
1121
  parent: current,
1122
+ functionArity: getFunctionArity(definition),
852
1123
  };
853
- if (isInstantiated(definition)) return { ...local, params: getParamArities(definition) };
1124
+ if (isInstantiated(definition)) {
1125
+ return {
1126
+ ...local,
1127
+ params: getParamArities(definition),
1128
+ functionArity: lookupLocal(current, definition.name)?.functionArity,
1129
+ };
1130
+ }
854
1131
  const isInstanced = instances.some((instance) => instance.location === definition.location);
855
1132
  const isGenerated = unit.isGenerated || definition.isLocal || isKey(definition.name);
856
1133
  const inner = isInstanced
@@ -862,7 +1139,17 @@ const resolveDefinitions = (
862
1139
  ? { ...local, params: getParamArities(definition) }
863
1140
  : current;
864
1141
  }, declared);
865
- return resolveInstances(resolved, () => true);
1142
+ const resolvedScope = resolvePending(resolved, () => true);
1143
+ declaredLocals.forEach((local, declaration) => {
1144
+ const range = declaration.location.range;
1145
+ if (range && !unit.isGenerated && (!local || local.isPending)) {
1146
+ unit.errors.push({
1147
+ location: formatRange(range),
1148
+ message: `Symbol ${resolveSynonym(declaration.name)} declared in RECURSIVE statement but not defined.`,
1149
+ });
1150
+ }
1151
+ });
1152
+ return resolvedScope;
866
1153
  };
867
1154
 
868
1155
  const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) => {
@@ -871,7 +1158,9 @@ const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) =>
871
1158
  prefix === name
872
1159
  ? undefined
873
1160
  : (lookupLocal(scope, prefix) ?? getModuleBinding(prefix, unit, undefined));
874
- return binding?.kind === "Instance" ? { name: prefix, arity: binding.arity } : undefined;
1161
+ return binding?.kind === "Instance"
1162
+ ? { name: prefix, arity: binding.arity, range: binding.range }
1163
+ : undefined;
875
1164
  };
876
1165
 
877
1166
  const isInstanceArityReported = (
@@ -879,16 +1168,22 @@ const isInstanceArityReported = (
879
1168
  scope: LocalName | undefined,
880
1169
  unit: Unit,
881
1170
  ) => {
882
- if (expression.kind !== "Identifier" && expression.kind !== "Apply") return false;
1171
+ if (!isReference(expression)) return false;
1172
+ const selectors = getSelectors(expression);
1173
+ const nameCount = selectors.findIndex((selector) => selector.kind !== "Name");
883
1174
  const instance = findInstance(
884
- expression.kind === "Identifier" ? expression.name : expression.operator,
1175
+ selectors
1176
+ .slice(0, nameCount === -1 ? selectors.length : nameCount)
1177
+ .flatMap((selector) => (selector.kind === "Name" ? [selector.name] : []))
1178
+ .join("!"),
885
1179
  scope,
886
1180
  unit,
887
1181
  );
888
- const count = expression.kind === "Apply" ? (expression.argumentCounts?.[0] ?? 0) : 0;
1182
+ const first = selectors[0];
1183
+ const count = first.kind === "Name" ? first.args.length : 0;
889
1184
  if (!instance || count === instance.arity) return false;
890
1185
  const range =
891
- (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ??
1186
+ (expression.kind === "Identifier" ? undefined : expression.argumentRanges?.[0]) ??
892
1187
  expression.location.range;
893
1188
  if (range) {
894
1189
  unit.errors.push({
@@ -899,103 +1194,215 @@ const isInstanceArityReported = (
899
1194
  return true;
900
1195
  };
901
1196
 
1197
+ const isArgumentCountReported = (
1198
+ callee: Binding | undefined,
1199
+ name: string,
1200
+ count: number,
1201
+ range: SourceRange | undefined,
1202
+ unit: Unit,
1203
+ ) => {
1204
+ const params = callee?.kind === "Definition" ? callee.params : undefined;
1205
+ if (!callee || !params || params.length === callee.arity) return false;
1206
+ if (range && !unit.isGenerated) {
1207
+ unit.errors.push({
1208
+ location: formatRange(range),
1209
+ message: `Wrong number of arguments (${count}) given to operator '${resolveSynonym(name)}', \nwhich requires ${params.length} arguments.`,
1210
+ });
1211
+ }
1212
+ return true;
1213
+ };
1214
+
1215
+ const resolveExpressionArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
1216
+ const range = arg.location.range;
1217
+ const report = (message: string) => {
1218
+ if (range) unit.errors.push({ location: formatRange(range), message });
1219
+ };
1220
+ const selectionError = operatorSelectionErrors.get(arg);
1221
+ // Deviation from SANY: SANY names its internal node kind here, where tla-ts words it as for a name.
1222
+ if (arg.kind === "Lambda" && arg.operator !== undefined) {
1223
+ report(`The operator ${resolveSynonym(arg.operator)} requires 1 arguments.`);
1224
+ } else if (selectionError) {
1225
+ unit.errors.push(selectionError);
1226
+ } else if (arg.kind === "Lambda" && range) {
1227
+ unresolvedExpressions.add(arg);
1228
+ report("LAMBDA expression used where an expression is required.");
1229
+ } else if (arg.kind === "OperatorReference") {
1230
+ const argArity = getSymbolArity(arg, arg.operator, scope, unit);
1231
+ if (argArity !== undefined) {
1232
+ report(`The operator ${resolveSynonym(arg.operator)} requires ${argArity} arguments.`);
1233
+ }
1234
+ } else resolveExpression(arg, scope, unit);
1235
+ };
1236
+
1237
+ const getSelectorArgumentError = (reference: Expression) => {
1238
+ // SANY reads a reference that ends in arguments as an application, not as a selector's arguments.
1239
+ const selectors =
1240
+ reference.kind === "Subexpression" ||
1241
+ (reference.kind === "Apply" && reference.argumentCounts?.at(-1) === 0)
1242
+ ? getSelectors(reference)
1243
+ : [];
1244
+ const index = selectors.findIndex((selector) => "args" in selector && selector.args.length > 0);
1245
+ if (index === -1 || !isReference(reference)) return undefined;
1246
+ const selector = selectors[index];
1247
+ return {
1248
+ index,
1249
+ range: reference.selectorRanges?.[index],
1250
+ message: `Selector \`${selector.kind === "Name" ? selector.name : "!(...)"}' should not have argument(s).`,
1251
+ };
1252
+ };
1253
+
1254
+ const matchArgument = (
1255
+ arg: Expression,
1256
+ expected: number,
1257
+ index: number,
1258
+ operator: string,
1259
+ operatorRange: SourceRange | undefined,
1260
+ scope: LocalName | undefined,
1261
+ unit: Unit,
1262
+ ) => {
1263
+ const report = (range: SourceRange | undefined, message: string) => {
1264
+ if (range) unit.errors.push({ location: formatRange(range), message });
1265
+ };
1266
+ const reportOperatorArity = (name: string, arity: number) => {
1267
+ const definition =
1268
+ findInstance(operator, scope, unit)?.range ?? findBinding(operator, scope, unit)?.range;
1269
+ if (!definition) return;
1270
+ report(
1271
+ operatorRange,
1272
+ `Operator with incorrect arity passed as argument. \nOperator '${resolveSynonym(name)}' of arity ${arity} is argument number ${index + 1} (counting from 1) to operator \`${formatRange(definition)}', \nbut an operator of arity ${expected} was expected.`,
1273
+ );
1274
+ };
1275
+ const range = arg.location.range;
1276
+ if (expected === 0) {
1277
+ resolveExpressionArgument(arg, scope, unit);
1278
+ return true;
1279
+ }
1280
+ const parenthesized = parenthesizedRanges.get(arg);
1281
+ if (parenthesized) {
1282
+ report(
1283
+ parenthesized,
1284
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
1285
+ );
1286
+ return false;
1287
+ }
1288
+ const reference = selections.get(arg) ?? arg;
1289
+ const argumentError = getSelectorArgumentError(reference);
1290
+ if (argumentError) {
1291
+ report(argumentError.range, argumentError.message);
1292
+ return false;
1293
+ }
1294
+ if (arg.kind === "Lambda") {
1295
+ if (selections.has(arg)) resolveExpression(arg, scope, unit);
1296
+ else resolveLambda(arg, scope, unit);
1297
+ if (findNullError(nullSelections.get(arg))) return false;
1298
+ const isMatched = arg.params.length === expected;
1299
+ if (!isMatched && selections.has(arg)) {
1300
+ report(range, `Expected arity ${expected} but found operator of arity ${arg.params.length}.`);
1301
+ } else if (!isMatched && range && arg.operator === undefined) {
1302
+ report(
1303
+ operatorRange,
1304
+ `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
1305
+ );
1306
+ } else if (!isMatched && arg.operator !== undefined) {
1307
+ reportOperatorArity(arg.operator, arg.params.length);
1308
+ }
1309
+ return isMatched;
1310
+ }
1311
+ if (reference !== arg) {
1312
+ const failed = findNullError(nullSelections.get(arg));
1313
+ if (failed) unit.errors.push(failed);
1314
+ if (!failed) {
1315
+ report(reference.location.range, `Expected arity ${expected} but found operator of arity 0.`);
1316
+ }
1317
+ return false;
1318
+ }
1319
+ if (arg.kind === "Subexpression") {
1320
+ resolveExpression(arg, scope, unit);
1321
+ return false;
1322
+ }
1323
+ if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
1324
+ report(
1325
+ range,
1326
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
1327
+ );
1328
+ return false;
1329
+ }
1330
+ const name = arg.kind === "Identifier" ? arg.name : arg.operator;
1331
+ const argParams = findBinding(name, scope, unit)?.params ?? [];
1332
+ const argArity = getSymbolArity(arg, name, scope, unit);
1333
+ if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
1334
+ report(
1335
+ getSpelledNameRange(arg, name),
1336
+ `Expected arity ${expected} but found operator of arity ${argArity}.`,
1337
+ );
1338
+ }
1339
+ if (arg.kind === "OperatorReference" && argArity !== undefined && argArity !== expected) {
1340
+ reportOperatorArity(name, argArity);
1341
+ }
1342
+ // Deviation from SANY: OpDefNode#matchingOpArgOperand reads as many parameters as a RECURSIVE declaration gives and crashes when the definition has fewer.
1343
+ return argArity === expected && argParams.every((param) => param === 0);
1344
+ };
1345
+
902
1346
  const resolveApply = (
903
1347
  expression: Expression & { kind: "Apply" },
904
1348
  scope: LocalName | undefined,
905
1349
  unit: Unit,
906
1350
  ) => {
907
- if (isInstanceArityReported(expression, scope, unit)) return;
908
1351
  const operator = expression.operator;
909
1352
  const callee = findBinding(operator, scope, unit);
910
- const arity = getSymbolArity(expression, operator, scope, unit);
911
- if (arity === undefined) return;
912
- if (arity !== expression.args.length) {
1353
+ const arity = isInstanceArityReported(expression, scope, unit)
1354
+ ? undefined
1355
+ : getSymbolArity(expression, operator, scope, unit);
1356
+ if (arity !== undefined && arity !== expression.args.length) {
913
1357
  unit.errors.push({
914
1358
  location: formatRange(expression.argumentsRange ?? getSpelledNameRange(expression, operator)),
915
- message: `The operator ${operator} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
1359
+ message: `The operator ${resolveSynonym(operator)} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
916
1360
  });
1361
+ }
1362
+ if (arity !== expression.args.length) {
1363
+ emptyExpressions.add(expression);
917
1364
  return;
918
1365
  }
919
- const params = callee && (callee.kind === "Definition" ? callee.params : []);
1366
+ const params =
1367
+ callee && (callee.kind === "Definition" ? callee.params : expression.args.map(() => 0));
920
1368
  if (params === undefined) {
921
1369
  expression.args.forEach((arg) => resolveArgument(arg, scope, unit));
922
1370
  return;
923
1371
  }
924
- const report = (range: SourceRange | undefined, message: string) => {
925
- if (range) unit.errors.push({ location: formatRange(range), message });
926
- };
927
- expression.args
928
- .map((arg, index) => {
929
- const expected = params[index] ?? 0;
930
- const range = arg.location.range;
931
- if (expected === 0) {
932
- // Deviation from SANY: SANY fails here with an internal error; tla-ts words it as for a name.
933
- if (arg.kind === "Lambda" && arg.operator !== undefined) {
934
- report(range, `The operator ${arg.operator} requires 1 arguments.`);
935
- } else if (arg.kind === "Lambda" && range) {
936
- report(range, "LAMBDA expression used where an expression is required.");
937
- } else if (arg.kind === "OperatorReference") {
938
- const argArity = getSymbolArity(arg, arg.operator, scope, unit);
939
- if (argArity !== undefined) {
940
- report(range, `The operator ${arg.operator} requires ${argArity} arguments.`);
941
- }
942
- } else resolveExpression(arg, scope, unit);
943
- return true;
944
- }
945
- if (arg.kind === "Lambda") {
946
- resolveExpression(arg, scope, unit);
947
- const isMatched = arg.params.length === expected;
948
- if (!isMatched && selections.has(arg)) {
949
- report(
950
- range,
951
- `Expected arity ${expected} but found operator of arity ${arg.params.length}.`,
952
- );
953
- } else if (!isMatched && range && arg.operator === undefined) {
954
- report(
955
- expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator),
956
- `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
957
- );
958
- }
959
- return isMatched;
960
- }
961
- if (arg.kind === "Subexpression") {
962
- resolveExpression(arg, scope, unit);
963
- return true;
964
- }
965
- if (arg.kind === "Apply" && arg.argumentCounts?.at(-1) === 0) {
966
- const selectorIndex = arg.argumentCounts.findIndex((count) => count > 0);
967
- report(
968
- arg.selectorRanges?.[selectorIndex],
969
- `Selector \`${arg.operator.split("!")[selectorIndex]}' should not have argument(s).`,
970
- );
971
- return false;
972
- }
973
- if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
974
- report(
975
- range,
976
- `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
977
- );
978
- return false;
979
- }
980
- const name = arg.kind === "Identifier" ? arg.name : arg.operator;
981
- const argParams = findBinding(name, scope, unit)?.params ?? [];
982
- const argArity = getSymbolArity(arg, name, scope, unit);
983
- if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
984
- report(
985
- getSpelledNameRange(arg, name),
986
- `Expected arity ${expected} but found operator of arity ${argArity}.`,
987
- );
988
- }
989
- return argArity === expected && argParams.every((param) => param === 0);
990
- })
991
- .forEach((isMatched, index) => {
992
- if (!isMatched) {
993
- report(
994
- expression.location.range,
995
- `Argument number ${index + 1} to operator '${operator}' \nshould be a ${params[index]}-parameter operator.`,
996
- );
997
- }
998
- });
1372
+ const operatorRange =
1373
+ expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator);
1374
+ const isSelection = operator === SELECTION_NAME;
1375
+ const matches = expression.args.slice(0, params.length).map((arg, index) => {
1376
+ const source = isSelection ? selectionArguments.get(arg) : undefined;
1377
+ return matchArgument(
1378
+ arg,
1379
+ params[index],
1380
+ source?.index ?? index,
1381
+ source?.operator ?? operator,
1382
+ source?.range ?? operatorRange,
1383
+ scope,
1384
+ isSelection ? { ...unit, isGenerated: false } : unit,
1385
+ );
1386
+ });
1387
+ if (
1388
+ isArgumentCountReported(
1389
+ callee,
1390
+ operator,
1391
+ expression.args.length,
1392
+ expression.location.range,
1393
+ unit,
1394
+ )
1395
+ ) {
1396
+ return;
1397
+ }
1398
+ matches.forEach((isMatched, index) => {
1399
+ if (!isMatched && expression.location.range) {
1400
+ unit.errors.push({
1401
+ location: formatRange(expression.location.range),
1402
+ message: `Argument number ${index + 1} to operator '${isSelection ? "LAMBDA" : operator}' \nshould be a ${params[index]}-parameter operator.`,
1403
+ });
1404
+ }
1405
+ });
999
1406
  };
1000
1407
 
1001
1408
  const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
@@ -1003,20 +1410,61 @@ const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Un
1003
1410
  else resolveExpression(arg, scope, unit);
1004
1411
  };
1005
1412
 
1413
+ const matchApplications = (
1414
+ applications: SelectionArguments[],
1415
+ scope: LocalName | undefined,
1416
+ unit: Unit,
1417
+ ) =>
1418
+ applications.forEach((application) =>
1419
+ application.args
1420
+ .slice(0, application.params.length)
1421
+ .forEach((arg, index) =>
1422
+ matchArgument(
1423
+ arg,
1424
+ application.params[index],
1425
+ index,
1426
+ application.operator,
1427
+ application.range,
1428
+ scope,
1429
+ unit,
1430
+ ),
1431
+ ),
1432
+ );
1433
+
1006
1434
  const isSelectionReported = (expression: Expression, scope: LocalName | undefined, unit: Unit) => {
1007
1435
  const failed = selectionErrors.get(expression);
1008
1436
  if (!failed) return false;
1009
- failed.args.forEach((arg) => resolveArgument(arg, scope, unit));
1010
- unit.errors.push(failed.error);
1437
+ matchApplications(failed.applications, scope, unit);
1438
+ unit.errors.push(findNullError(failed.nulls) ?? failed.error);
1011
1439
  return true;
1012
1440
  };
1013
1441
 
1442
+ const resolveLambda = (
1443
+ expression: Expression & { kind: "Lambda" },
1444
+ scope: LocalName | undefined,
1445
+ unit: Unit,
1446
+ ) =>
1447
+ resolveExpression(
1448
+ expression.body,
1449
+ bindNames(scope, expression.params, expression.paramRanges, unit),
1450
+ {
1451
+ ...unit,
1452
+ labelParams: [...unit.labelParams, ...expression.params],
1453
+ },
1454
+ );
1455
+
1014
1456
  const resolveExpression = (
1015
1457
  expression: Expression,
1016
1458
  scope: LocalName | undefined,
1017
1459
  unit: Unit,
1018
1460
  ): void => {
1019
1461
  if (selections.has(expression) && !unit.isGenerated) {
1462
+ const failed = findNullSelection(nullSelections.get(expression));
1463
+ if (failed) {
1464
+ matchApplications(failed.applications, scope, unit);
1465
+ unit.errors.push(failed.error);
1466
+ return;
1467
+ }
1020
1468
  resolveExpression(expression, scope, { ...unit, isGenerated: true });
1021
1469
  return;
1022
1470
  }
@@ -1030,18 +1478,51 @@ const resolveExpression = (
1030
1478
  case "Number":
1031
1479
  case "Decimal":
1032
1480
  case "String":
1481
+ return;
1033
1482
  case "ExceptAt":
1483
+ if (!unit.isInExcept && expression.location.range) {
1484
+ emptyExpressions.add(expression);
1485
+ unit.errors.push({
1486
+ location: formatRange(expression.location.range),
1487
+ message: "@ used where its meaning is not defined.",
1488
+ });
1489
+ }
1034
1490
  return;
1035
1491
  case "Identifier": {
1036
- if (isInstanceArityReported(expression, scope, unit)) return;
1037
1492
  const name = expression.name;
1038
- const arity = getSymbolArity(expression, name, scope, unit);
1039
- if (arity !== undefined && arity > 0) {
1493
+ const arity = isInstanceArityReported(expression, scope, unit)
1494
+ ? undefined
1495
+ : getSymbolArity(expression, name, scope, unit);
1496
+ if (arity === 0) {
1497
+ const binding = findBinding(name, scope, unit);
1498
+ const kind = binding?.kind;
1499
+ // SANY's selector chooses no operand of a variable, theorem, step or NEW symbol, unlike of a constant or definition.
1500
+ if (
1501
+ kind === "Variable" ||
1502
+ kind === "Theorem" ||
1503
+ kind?.startsWith("New") ||
1504
+ isFact(name, unit)
1505
+ ) {
1506
+ emptyExpressions.add(expression);
1507
+ }
1508
+ const local = lookupLocal(scope, name);
1509
+ if ((local ? local.goal : getGoal(name, unit))?.statement.kind === "AssumeProve") {
1510
+ unit.errors.push({
1511
+ location: formatRange(getSpelledNameRange(expression, name)),
1512
+ message: "ASSUME/PROVE used where an expression is required.",
1513
+ });
1514
+ return;
1515
+ }
1516
+ isArgumentCountReported(binding, name, 0, getSpelledNameRange(expression, name), unit);
1517
+ return;
1518
+ }
1519
+ if (arity !== undefined) {
1040
1520
  unit.errors.push({
1041
1521
  location: formatRange(getSpelledNameRange(expression, name)),
1042
- message: `The operator ${name} requires ${arity} arguments.`,
1522
+ message: `The operator ${resolveSynonym(name)} requires ${arity} arguments.`,
1043
1523
  });
1044
1524
  }
1525
+ emptyExpressions.add(expression);
1045
1526
  return;
1046
1527
  }
1047
1528
  case "OperatorReference":
@@ -1051,11 +1532,14 @@ const resolveExpression = (
1051
1532
  resolveApply(expression, scope, unit);
1052
1533
  return;
1053
1534
  case "Lambda":
1054
- resolveExpression(
1055
- expression.body,
1056
- bindNames(scope, expression.params, expression.paramRanges, unit),
1057
- bindLabelParams(expression.params),
1058
- );
1535
+ if (selections.has(expression)) resolveLambda(expression, scope, unit);
1536
+ else if (expression.location.range) {
1537
+ unresolvedExpressions.add(expression);
1538
+ unit.errors.push({
1539
+ location: formatRange(expression.location.range),
1540
+ message: "LAMBDA expression used where an expression is required.",
1541
+ });
1542
+ }
1059
1543
  return;
1060
1544
  case "And":
1061
1545
  case "Or":
@@ -1078,7 +1562,13 @@ const resolveExpression = (
1078
1562
  case "Let":
1079
1563
  resolveExpression(
1080
1564
  expression.body,
1081
- resolveDefinitions(expression.definitions, scope, unit, expression.instances),
1565
+ resolveDefinitions(
1566
+ expression.definitions,
1567
+ scope,
1568
+ unit,
1569
+ expression.instances,
1570
+ expression.recursive,
1571
+ ),
1082
1572
  unit,
1083
1573
  );
1084
1574
  return;
@@ -1146,9 +1636,30 @@ const resolveExpression = (
1146
1636
  resolveExpression(update.value, scope, { ...unit, isInExcept: true });
1147
1637
  });
1148
1638
  return;
1149
- case "FunctionApplication":
1150
- resolveAll([expression.function, ...expression.args]);
1639
+ case "FunctionApplication": {
1640
+ const applied = expression.function;
1641
+ const name =
1642
+ applied.kind === "Identifier"
1643
+ ? applied.name
1644
+ : applied.kind === "Apply"
1645
+ ? applied.operator
1646
+ : undefined;
1647
+ const arity = name === undefined ? undefined : findBinding(name, scope, unit)?.functionArity;
1648
+ resolveExpression(applied, scope, unit);
1649
+ const count = expression.args.length;
1650
+ if (arity === undefined || count < 2 || arity === count || isEmptyExpression(applied)) {
1651
+ resolveAll(expression.args);
1652
+ return;
1653
+ }
1654
+ emptyExpressions.add(expression);
1655
+ if (expression.location.range) {
1656
+ unit.errors.push({
1657
+ location: formatRange(expression.location.range),
1658
+ message: `Function '${name}' is defined with ${arity} parameters, but is applied to ${count} arguments.`,
1659
+ });
1660
+ }
1151
1661
  return;
1662
+ }
1152
1663
  case "FieldAccess":
1153
1664
  resolveExpression(expression.record, scope, unit);
1154
1665
  return;
@@ -1168,34 +1679,365 @@ const resolveExpression = (
1168
1679
  resolveExpression(expression.body, scope, { ...unit, labelParams: [], labels: new Set() });
1169
1680
  checkLabel(expression, scope, unit);
1170
1681
  return;
1171
- case "Subexpression": {
1172
- if (isSelectionReported(expression, scope, unit)) return;
1173
- expression.selectors
1174
- .flatMap((selector) => ("args" in selector ? selector.args : []))
1175
- .forEach((arg) => resolveArgument(arg, scope, unit));
1176
- checkReference(expression, scope, unit, false);
1682
+ case "Subexpression":
1683
+ if (isSubexpressionReported(expression, scope, unit)) emptyExpressions.add(expression);
1684
+ return;
1685
+ case "Selection":
1686
+ return;
1687
+ }
1688
+ };
1689
+
1690
+ const isPendingSelectionReported = (
1691
+ name: string,
1692
+ args: Expression[],
1693
+ selectorRange: SourceRange | undefined,
1694
+ argumentsRange: SourceRange | undefined,
1695
+ scope: LocalName | undefined,
1696
+ unit: Unit,
1697
+ ) => {
1698
+ const pending = lookupLocal(scope, name) ?? getModuleBinding(name, unit, undefined);
1699
+ if (!pending?.isPending || !selectorRange || !argumentsRange) return false;
1700
+ if (args.length !== pending.arity) {
1701
+ unit.errors.push({
1702
+ location: formatRange(argumentsRange),
1703
+ message: `The operator ${name} requires ${pending.arity} arguments.`,
1704
+ });
1705
+ return true;
1706
+ }
1707
+ args.forEach((arg) => resolveExpression(arg, scope, unit));
1708
+ unit.errors.push({
1709
+ location: formatRange(selectorRange),
1710
+ message: `Subexpression of \`${name}' used inside the operator's definition.`,
1711
+ });
1712
+ return true;
1713
+ };
1714
+
1715
+ const isSubexpressionReported = (
1716
+ expression: Expression & { kind: "Subexpression" },
1717
+ scope: LocalName | undefined,
1718
+ unit: Unit,
1719
+ ) => {
1720
+ if (
1721
+ isInstanceArityReported(expression, scope, unit) ||
1722
+ isSelectionReported(expression, scope, unit)
1723
+ ) {
1724
+ return true;
1725
+ }
1726
+ const head = expression.selectors[0];
1727
+ const range = expression.selectorRanges?.[0];
1728
+ const nameCount = expression.selectors.findIndex((selector) => selector.kind !== "Name");
1729
+ const names = expression.selectors
1730
+ .slice(0, nameCount)
1731
+ .flatMap((selector) => (selector.kind === "Name" ? [selector.name] : []));
1732
+ const symbolIndex = names.findIndex(
1733
+ (_name, index) =>
1734
+ index > 0 &&
1735
+ (findSymbol(names.slice(0, index + 1).join("!"), unit)?.kind ?? "Instance") !== "Instance",
1736
+ );
1737
+ const isInstance =
1738
+ names.length > 1 &&
1739
+ (lookupLocal(scope, names[0]) ?? getModuleBinding(names[0], unit, undefined))?.kind ===
1740
+ "Instance";
1741
+ const lastRange = expression.selectorRanges?.[nameCount - 1];
1742
+ if (isInstance && symbolIndex === -1 && range && lastRange) {
1743
+ unit.errors.push({
1744
+ location: formatRange({ module: range.module, start: range.start, end: lastRange.end }),
1745
+ message: `Unknown operator: \`${resolveSynonym(names.join("!"))}'.`,
1746
+ });
1747
+ return true;
1748
+ }
1749
+ const name = names.slice(0, symbolIndex + 1).join("!");
1750
+ const symbol = symbolIndex > 0 ? findSymbol(name, unit) : undefined;
1751
+ const argumentCount = expression.selectors
1752
+ .slice(0, symbolIndex + 1)
1753
+ .flatMap((selector) => ("args" in selector ? selector.args : [])).length;
1754
+ const argumentRange = expression.argumentRanges?.[symbolIndex] ?? expression.location.range;
1755
+ if (symbol && symbol.arity !== argumentCount && argumentRange) {
1756
+ unit.errors.push({
1757
+ location: formatRange(argumentRange),
1758
+ message: `The operator ${resolveSynonym(name)} requires ${symbol.arity} arguments.`,
1759
+ });
1760
+ return true;
1761
+ }
1762
+ if (head.kind === "Name" && expression.selectors[1].kind !== "Name" && range) {
1763
+ const local = lookupLocal(scope, head.name);
1764
+ const binding = local ?? findSymbol(head.name, unit);
1765
+ if ((binding === undefined && !isFact(head.name, unit)) || binding?.kind === "Instance") {
1766
+ unit.errors.push({
1767
+ location: formatRange(range),
1768
+ message: `Unknown operator: \`${resolveSynonym(head.name)}'.`,
1769
+ });
1770
+ return true;
1771
+ }
1772
+ if (binding && (!SELECTABLE_KINDS.has(binding.kind) || local?.nonFactStep)) {
1773
+ reportUnselectable(head.name, range, unit);
1774
+ return true;
1177
1775
  }
1178
1776
  }
1777
+ if (
1778
+ head.kind === "Name" &&
1779
+ isPendingSelectionReported(
1780
+ head.name,
1781
+ head.args,
1782
+ range,
1783
+ expression.argumentRanges?.[0] ?? expression.location.range,
1784
+ scope,
1785
+ unit,
1786
+ )
1787
+ ) {
1788
+ return true;
1789
+ }
1790
+ expression.selectors
1791
+ .flatMap((selector) => ("args" in selector ? selector.args : []))
1792
+ .forEach((arg) => resolveArgument(arg, scope, unit));
1793
+ const selected = checkReference(expression, scope, unit, false);
1794
+ return selected ? selected.node === undefined : false;
1179
1795
  };
1180
1796
 
1181
- const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) =>
1182
- facts.forEach((fact) => {
1183
- if (
1184
- fact.kind === "ModuleFact" ||
1185
- isInstanceArityReported(fact, scope, unit) ||
1186
- checkReference(fact, scope, unit, true)
1187
- ) {
1188
- return;
1797
+ const reportUnknownModule = (fact: Fact & { kind: "ModuleFact" }, unit: Unit) => {
1798
+ const range = fact.location.range;
1799
+ if (unit.isModuleKnown(fact.name, fact.location) || !range) return;
1800
+ unit.errors.push({
1801
+ location: formatRange({
1802
+ ...range,
1803
+ start: { line: range.end.line, column: range.end.column - fact.name.length + 1 },
1804
+ }),
1805
+ message: `Module \`${fact.name}' used without being extended or instantiated.`,
1806
+ });
1807
+ };
1808
+
1809
+ const checkFact = (fact: Fact, reference: Fact, scope: LocalName | undefined, unit: Unit) => {
1810
+ if (fact.kind === "ModuleFact") {
1811
+ reportUnknownModule(fact, unit);
1812
+ return undefined;
1813
+ }
1814
+ if (fact.kind === "ExceptAt" && fact.location.range) {
1815
+ unit.errors.push({
1816
+ location: formatRange(fact.location.range),
1817
+ message: "Unknown operator: `@'.",
1818
+ });
1819
+ return BUILTIN_LOCATION;
1820
+ }
1821
+ const hidden = getHiddenExpressionLocation(fact, reference, scope, unit);
1822
+ if (selections.has(fact)) {
1823
+ resolveExpression(fact, scope, unit);
1824
+ return hidden;
1825
+ }
1826
+ if (isInstanceArityReported(fact, scope, unit)) return hidden;
1827
+ const selected = checkReference(fact, scope, unit, true);
1828
+ if (selected) {
1829
+ const kind = selected.node?.kind;
1830
+ if (kind === undefined) return BUILTIN_LOCATION;
1831
+ return kind === "AssumeProve" || kind === "NewSymbol"
1832
+ ? undefined
1833
+ : fact.location.range && formatRange(fact.location.range);
1834
+ }
1835
+ if (fact.kind === "Subexpression") {
1836
+ return isSubexpressionReported(fact, scope, unit) ? BUILTIN_LOCATION : hidden;
1837
+ }
1838
+ const name = fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1839
+ if (fact.kind === "Identifier" && lookupLocal(scope, name)?.nonFactStep) {
1840
+ unit.errors.push({
1841
+ location: formatRange(getSpelledNameRange(fact, name)),
1842
+ message: "Step number of non-fact used as a fact",
1843
+ });
1844
+ return BUILTIN_LOCATION;
1845
+ }
1846
+ if (
1847
+ !isFact(name, unit) &&
1848
+ !lookupLocal(scope, name)?.goal &&
1849
+ !(fact.kind === "Identifier" && isInstanceName(name, scope, unit))
1850
+ ) {
1851
+ resolveExpression(fact, scope, unit);
1852
+ }
1853
+ return hidden;
1854
+ };
1855
+
1856
+ const isDefinitionEntry = (def: Fact, scope: LocalName | undefined, unit: Unit) => {
1857
+ if (def.kind === "ModuleFact") {
1858
+ reportUnknownModule(def, unit);
1859
+ return unit.isModuleKnown(def.name, def.location);
1860
+ }
1861
+ const entryErrors = defEntryErrors.get(def) ?? [];
1862
+ unit.errors.push(
1863
+ ...entryErrors.map((error) => ({
1864
+ location: formatSanyLocation(error.location),
1865
+ message: error.message,
1866
+ })),
1867
+ );
1868
+ if (entryErrors.length > 0) return false;
1869
+ const binder = getDefEntryBinder(def);
1870
+ const reference = binder ?? selections.get(def) ?? def;
1871
+ const range = reference.location.range;
1872
+ if (!range) return true;
1873
+ const name =
1874
+ reference.kind === "Identifier"
1875
+ ? reference.name
1876
+ : reference.kind === "Apply" || reference.kind === "OperatorReference"
1877
+ ? reference.operator
1878
+ : "";
1879
+ const local = lookupLocal(scope, name);
1880
+ const binding = local ?? findSymbol(name, unit) ?? getModuleBinding(name, unit, range);
1881
+ if (binding === undefined && isFact(name, unit)) return true;
1882
+ const isDefined =
1883
+ isReference(reference) &&
1884
+ getSelectors(reference).length > 1 &&
1885
+ (binding === undefined || getSelectorArgumentError(reference))
1886
+ ? isDefinitionSelected(def, reference, scope, unit)
1887
+ : name === "" || isDefinitionName(name, local, binding, range, unit);
1888
+ if (isDefined) return true;
1889
+ unit.errors.push({
1890
+ location: formatRange((binder ? def : reference).location.range ?? range),
1891
+ message: "DEF clause entry should describe a defined operator.",
1892
+ });
1893
+ return false;
1894
+ };
1895
+
1896
+ const isDefinitionName = (
1897
+ name: string,
1898
+ local: LocalName | undefined,
1899
+ binding: Binding | undefined,
1900
+ range: SourceRange,
1901
+ unit: Unit,
1902
+ ) => {
1903
+ if (binding === undefined) {
1904
+ unit.errors.push({
1905
+ location: formatRange(range),
1906
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
1907
+ });
1908
+ }
1909
+ if (local?.nonFactStep === "Define") return true;
1910
+ if (local?.nonFactStep) {
1911
+ unit.errors.push({
1912
+ location: formatRange(range),
1913
+ message: "DEF clause entry refers to a non-definition step.",
1914
+ });
1915
+ }
1916
+ return binding !== undefined && SELECTABLE_KINDS.has(binding.kind) && !isStepName(name);
1917
+ };
1918
+
1919
+ const isDefinitionSelected = (
1920
+ def: Expression,
1921
+ reference: Reference,
1922
+ scope: LocalName | undefined,
1923
+ unit: Unit,
1924
+ ) => {
1925
+ const report = (range: SourceRange | undefined, message: string) => {
1926
+ if (range) unit.errors.push({ location: formatRange(range), message });
1927
+ return false;
1928
+ };
1929
+ const argumentError = getSelectorArgumentError(reference);
1930
+ if (argumentError?.index === 0) return report(argumentError.range, argumentError.message);
1931
+ const selectors = getSelectors(reference);
1932
+ const ranges = reference.selectorRanges;
1933
+ const failed = selectionErrors.get(def);
1934
+ if (!failed && !selections.has(def)) {
1935
+ const head = selectors[0];
1936
+ const name = head.kind === "Name" ? head.name : "";
1937
+ const local = lookupLocal(scope, name);
1938
+ const binding = local ?? findSymbol(name, unit);
1939
+ if (binding && (!SELECTABLE_KINDS.has(binding.kind) || local?.nonFactStep) && ranges?.[0]) {
1940
+ reportUnselectable(name, ranges[0], unit);
1941
+ return false;
1942
+ }
1943
+ if (argumentError) return report(argumentError.range, argumentError.message);
1944
+ if (checkReference(reference, scope, unit, false)) return false;
1945
+ const first = ranges?.[0];
1946
+ const last = ranges?.[selectors.findLastIndex((selector) => selector.kind === "Name")];
1947
+ const names = selectors.flatMap((selector) =>
1948
+ selector.kind === "Name" ? [selector.name] : [],
1949
+ );
1950
+ return report(
1951
+ first && last && { ...first, end: last.end },
1952
+ `Unknown operator: \`${resolveSynonym(names.join("!"))}'.`,
1953
+ );
1954
+ }
1955
+ if (argumentError) return report(argumentError.range, argumentError.message);
1956
+ const error = failed
1957
+ ? (findNullError(failed.nulls) ?? failed.error)
1958
+ : findNullError(nullSelections.get(def));
1959
+ if (error) {
1960
+ unit.errors.push(error);
1961
+ return false;
1962
+ }
1963
+ return selectors.at(-1)?.kind === "Name" && selectors.at(-2)?.kind !== "Name";
1964
+ };
1965
+
1966
+ const getHiddenExpressionLocation = (
1967
+ fact: Expression,
1968
+ reference: Fact,
1969
+ scope: LocalName | undefined,
1970
+ unit: Unit,
1971
+ ) => {
1972
+ const range = fact.location.range && formatRange(fact.location.range);
1973
+ if (selections.has(fact)) {
1974
+ return findNullError(nullSelections.get(fact))
1975
+ ? BUILTIN_LOCATION
1976
+ : reference.location.range && formatRange(reference.location.range);
1977
+ }
1978
+ if (selectionErrors.has(fact) || fact.kind === "ExceptAt") return BUILTIN_LOCATION;
1979
+ switch (fact.kind) {
1980
+ case "Number":
1981
+ case "String":
1982
+ case "Decimal":
1983
+ case "Let":
1984
+ case "Label":
1985
+ return undefined;
1986
+ case "Identifier":
1987
+ case "Apply":
1988
+ case "Subexpression": {
1989
+ const first = getSelectors(fact)[0];
1990
+ if (fact.kind === "Subexpression" || first.kind !== "Name") return undefined;
1991
+ const name = fact.kind === "Identifier" ? fact.name : fact.operator;
1992
+ const goal = lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit);
1993
+ if (
1994
+ isFact(name, unit) ||
1995
+ goal ||
1996
+ (isStepName(name) && lookupLocal(scope, name)) ||
1997
+ (fact.kind === "Identifier" && isInstanceName(name, scope, unit))
1998
+ ) {
1999
+ return undefined;
2000
+ }
2001
+ const binding = findBinding(name, scope, unit);
2002
+ const count = fact.kind === "Apply" ? fact.args.length : 0;
2003
+ // Deviation from SANY: UseOrHideNode#factCheck crashes on a fact whose operator Generator#generateExpression could not resolve, where tla-ts reports it like a null node.
2004
+ return binding?.arity === count ? range : BUILTIN_LOCATION;
1189
2005
  }
1190
- const name =
1191
- fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1192
- if (fact.kind === "Identifier" && lookupLocal(scope, name)?.isNonFact) {
2006
+ default:
2007
+ return range;
2008
+ }
2009
+ };
2010
+
2011
+ const checkUseOrHide = (
2012
+ statement: UseOrHide | Extract<Proof, { kind: "By" }>,
2013
+ scope: LocalName | undefined,
2014
+ unit: Unit,
2015
+ ) => {
2016
+ const references = factReferences.get(statement.facts) ?? statement.facts;
2017
+ const hidden = statement.facts.map((fact, index) =>
2018
+ checkFact(fact, references[index], scope, unit),
2019
+ );
2020
+ const factCount = statement.facts.filter(
2021
+ (fact) => fact.kind !== "ModuleFact" || unit.isModuleKnown(fact.name, fact.location),
2022
+ ).length;
2023
+ const defCount = statement.defs.filter((def) => isDefinitionEntry(def, scope, unit)).length;
2024
+ hidden.forEach((location) => {
2025
+ if (location && statement.kind === "Hide") {
1193
2026
  unit.errors.push({
1194
- location: formatRange(getSpelledNameRange(fact, name)),
1195
- message: "Step number of non-fact used as a fact",
2027
+ location,
2028
+ message:
2029
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1196
2030
  });
1197
- } else if (!unit.facts.has(name)) resolveExpression(fact, scope, unit);
2031
+ }
1198
2032
  });
2033
+ const range = statement.location.range;
2034
+ if (factCount + defCount === 0 && range) {
2035
+ unit.errors.push({
2036
+ location: formatRange(range),
2037
+ message: statement.kind === "By" ? "Empty BY" : "Empty USE or HIDE statement.",
2038
+ });
2039
+ }
2040
+ };
1199
2041
 
1200
2042
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
1201
2043
  if (symbol.set) resolveExpression(symbol.set, scope, unit);
@@ -1244,7 +2086,7 @@ const resolveStatement = (
1244
2086
 
1245
2087
  const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, outer: Unit) => {
1246
2088
  const unit = outer.hasLabelScope ? { ...outer, hasLabelScope: false } : outer;
1247
- if (proof?.kind === "By") checkFacts(proof.facts, scope, unit);
2089
+ if (proof?.kind === "By") checkUseOrHide(proof, scope, unit);
1248
2090
  if (proof?.kind !== "Steps") return;
1249
2091
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
1250
2092
  };
@@ -1261,6 +2103,42 @@ const resolveLocalInstance = (instance: Instance, scope: LocalName | undefined,
1261
2103
  );
1262
2104
  };
1263
2105
 
2106
+ const getStepGoal = (body: StepBody, location: SourceLocation): Goal | undefined => {
2107
+ const createGoal = (keyword: string, statement: Expression) => ({
2108
+ statement,
2109
+ isSuffices: false,
2110
+ isInProof: false,
2111
+ keyword,
2112
+ });
2113
+ switch (body.kind) {
2114
+ case "Have":
2115
+ return createGoal("HAVE", { kind: "Tuple", elements: [body.expression], location });
2116
+ case "Case":
2117
+ return createGoal("CASE", { kind: "Tuple", elements: [body.expression], location });
2118
+ case "Witness":
2119
+ return createGoal("WITNESS", { kind: "Tuple", elements: body.expressions, location });
2120
+ case "Take":
2121
+ return createGoal("TAKE", { kind: "Tuple", elements: getBoundSets(body.bounds), location });
2122
+ case "Pick":
2123
+ return createGoal(
2124
+ "PICK",
2125
+ body.bounds.length > 0
2126
+ ? { kind: "Exists", bounds: body.bounds, body: body.body, location }
2127
+ : {
2128
+ kind: "UnboundedQuantifier",
2129
+ quantifier: "Exists",
2130
+ names: body.names,
2131
+ body: body.body,
2132
+ location,
2133
+ },
2134
+ );
2135
+ case "Qed":
2136
+ return createGoal("QED step", { kind: "Tuple", elements: [], location });
2137
+ default:
2138
+ return undefined;
2139
+ }
2140
+ };
2141
+
1264
2142
  const resolveStep = (
1265
2143
  step: ProofStep,
1266
2144
  scope: LocalName | undefined,
@@ -1271,12 +2149,16 @@ const resolveStep = (
1271
2149
  step.name === undefined
1272
2150
  ? unit
1273
2151
  : { ...unit, hasLabelScope: true, labelParams: [], labels: new Set<string>() };
2152
+ const goal = getStepGoal(body, step.location);
1274
2153
  const bindStep = (parent: LocalName | undefined): LocalName | undefined =>
1275
- step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent };
1276
- const bindNonFactStep = (parent: LocalName | undefined): LocalName | undefined =>
2154
+ step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent, goal };
2155
+ const bindNonFactStep = (
2156
+ parent: LocalName | undefined,
2157
+ nonFactStep: LocalName["nonFactStep"],
2158
+ ): LocalName | undefined =>
1277
2159
  step.name === undefined
1278
2160
  ? parent
1279
- : { name: step.name, arity: 0, kind: "Theorem", parent, isNonFact: true };
2161
+ : { name: step.name, arity: 0, kind: "Theorem", parent, nonFactStep };
1280
2162
  switch (body.kind) {
1281
2163
  case "Assert": {
1282
2164
  const assumed = resolveStatement(body.statement, scope, stepUnit);
@@ -1286,17 +2168,32 @@ const resolveStep = (
1286
2168
  resolveProof(step.proof, proofScope, unit);
1287
2169
  return body.isSuffices ? assumed : scope;
1288
2170
  }
1289
- const goal = { statement: body.statement, isSuffices: body.isSuffices, isInProof: true };
1290
- resolveProof(step.proof, { name, arity: 0, kind: "Theorem", parent: proofScope, goal }, unit);
1291
- goal.isInProof = false;
1292
- return { name, arity: 0, kind: "Theorem", parent: body.isSuffices ? assumed : scope, goal };
2171
+ const assertion = {
2172
+ statement: body.statement,
2173
+ isSuffices: body.isSuffices,
2174
+ isInProof: true,
2175
+ keyword: body.isSuffices && body.statement.kind !== "AssumeProve" ? "SUFFICES" : undefined,
2176
+ };
2177
+ resolveProof(
2178
+ step.proof,
2179
+ { name, arity: 0, kind: "Theorem", parent: proofScope, goal: assertion },
2180
+ unit,
2181
+ );
2182
+ assertion.isInProof = false;
2183
+ return {
2184
+ name,
2185
+ arity: 0,
2186
+ kind: "Theorem",
2187
+ parent: body.isSuffices ? assumed : scope,
2188
+ goal: assertion,
2189
+ };
1293
2190
  }
1294
2191
  case "Use":
1295
2192
  case "Hide":
1296
- checkFacts(body.facts, scope, unit);
1297
- return bindNonFactStep(scope);
2193
+ checkUseOrHide(body, scope, unit);
2194
+ return bindNonFactStep(scope, body.kind);
1298
2195
  case "Instance":
1299
- return bindNonFactStep(resolveLocalInstance(body, scope, stepUnit));
2196
+ return bindNonFactStep(resolveLocalInstance(body, scope, stepUnit), body.kind);
1300
2197
  case "Define":
1301
2198
  return bindNonFactStep(
1302
2199
  body.definitions.reduce(
@@ -1306,6 +2203,7 @@ const resolveStep = (
1306
2203
  : resolveDefinitions([definition], current, unit),
1307
2204
  scope,
1308
2205
  ),
2206
+ body.kind,
1309
2207
  );
1310
2208
  case "Have":
1311
2209
  case "Case":
@@ -1378,6 +2276,7 @@ export interface ModuleUnit {
1378
2276
  bound: Symbols;
1379
2277
  definitions: Map<string, Definition>;
1380
2278
  getKey: (definition: Definition) => string;
2279
+ isModuleKnown: (name: string, location: SourceLocation) => boolean;
1381
2280
  instanced: Map<Instance, Symbols>;
1382
2281
  facts: Set<string>;
1383
2282
  reports: ModuleReport[];
@@ -1416,18 +2315,94 @@ const checkSubstitutions = (
1416
2315
  (parent, param) => ({ name: param.name, arity: param.arity, kind: "Parameter", parent }),
1417
2316
  outer,
1418
2317
  );
2318
+ const reportArity = (declaration: Declaration, location: string) =>
2319
+ unit.errors.push({
2320
+ location,
2321
+ message: `An operator must be substituted for symbol '${resolveSynonym(declaration.name)}', and it must have arity ${declaration.arity}.`,
2322
+ });
1419
2323
  const resolveSubstitute = (declaration: Declaration, expression: Expression) => {
1420
- if (declaration.arity === 0 || expression.kind !== "Identifier") {
2324
+ const range = expression.location.range;
2325
+ if (declaration.arity === 0) {
2326
+ resolveExpressionArgument(expression, scope, unit);
2327
+ return;
2328
+ }
2329
+ const parenthesized = parenthesizedRanges.get(expression);
2330
+ const reference = parenthesized ? undefined : selections.get(expression);
2331
+ if (reference) {
2332
+ const arity = expression.kind === "Lambda" ? expression.params.length : 0;
2333
+ const failed = findNullError(nullSelections.get(expression));
2334
+ if (expression.kind === "Lambda") resolveExpression(expression, scope, unit);
2335
+ else if (failed) unit.errors.push(failed);
2336
+ if (!failed && arity !== declaration.arity && reference.location.range) {
2337
+ unit.errors.push({
2338
+ location: formatRange(reference.location.range),
2339
+ message: `Expected arity ${declaration.arity} but found operator of arity ${arity}.`,
2340
+ });
2341
+ }
2342
+ if (failed || arity !== declaration.arity) reportArity(declaration, BUILTIN_LOCATION);
2343
+ return;
2344
+ }
2345
+ if (expression.kind === "Subexpression" && !parenthesized) {
1421
2346
  resolveExpression(expression, scope, unit);
2347
+ reportArity(declaration, BUILTIN_LOCATION);
2348
+ return;
2349
+ }
2350
+ if (expression.kind === "Lambda" && !parenthesized) {
2351
+ resolveLambda(expression, scope, unit);
2352
+ if (expression.params.length !== declaration.arity && range) {
2353
+ reportArity(declaration, formatRange(range));
2354
+ }
2355
+ return;
2356
+ }
2357
+ if (expression.kind === "OperatorReference" && !parenthesized) {
2358
+ const arity = getSymbolArity(expression, expression.operator, scope, unit);
2359
+ if (arity === undefined) reportArity(declaration, BUILTIN_LOCATION);
2360
+ else if (arity !== declaration.arity && range) reportArity(declaration, formatRange(range));
2361
+ return;
2362
+ }
2363
+ if (expression.kind !== "Identifier" || parenthesized) {
2364
+ const errorRange = parenthesized ?? range;
2365
+ if (errorRange) {
2366
+ unit.errors.push({
2367
+ location: formatRange(errorRange),
2368
+ message: `Arity ${declaration.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${resolveSynonym(declaration.name)}'.`,
2369
+ });
2370
+ }
2371
+ reportArity(declaration, BUILTIN_LOCATION);
1422
2372
  return;
1423
2373
  }
1424
2374
  const arity = getSymbolArity(expression, expression.name, scope, unit);
1425
2375
  if (arity !== undefined && arity !== declaration.arity) {
1426
- throw new TlaSyntaxError(
1427
- `An operator must be substituted for symbol '${declaration.name}', and it must have arity ${declaration.arity} in the instance of ${instance.module} at line ${instance.location.line}, column ${instance.location.column}`,
1428
- );
2376
+ unit.errors.push({
2377
+ location: formatRange(getSpelledNameRange(expression, expression.name)),
2378
+ message: `Expected arity ${declaration.arity} but found operator of arity ${arity}.`,
2379
+ });
1429
2380
  }
2381
+ if (arity !== declaration.arity) reportArity(declaration, BUILTIN_LOCATION);
1430
2382
  };
2383
+ const instanceRange = instance.location.range;
2384
+ const isFound = (declaration: Declaration) =>
2385
+ lookupLocal(scope, declaration.name) !== undefined ||
2386
+ findSymbol(declaration.name, unit) !== undefined;
2387
+ const implicit = declarations.filter(isFound).map((declaration) => {
2388
+ const expression: Expression & { kind: "Identifier" } = {
2389
+ kind: "Identifier",
2390
+ name: declaration.name,
2391
+ location: instance.location,
2392
+ };
2393
+ return { declaration, expression };
2394
+ });
2395
+ implicit
2396
+ .filter((item) => item.declaration.arity === 0)
2397
+ .forEach((item) => {
2398
+ const arity = getSymbolArity(item.expression, item.declaration.name, scope, unit);
2399
+ if (arity && instanceRange) {
2400
+ unit.errors.push({
2401
+ location: formatRange(instanceRange),
2402
+ message: `Wrong number of arguments (0) given to operator '${resolveSynonym(item.declaration.name)}', \nwhich requires ${arity} arguments.`,
2403
+ });
2404
+ }
2405
+ });
1431
2406
  const substitutions = new Map<string, Expression>();
1432
2407
  instance.substitutions.forEach((substitution) => {
1433
2408
  const name = substitution.name;
@@ -1450,30 +2425,29 @@ const checkSubstitutions = (
1450
2425
  });
1451
2426
  }
1452
2427
  });
1453
- const implicit = declarations.filter((declaration) => !substitutions.has(declaration.name));
1454
- const isMissing = (declaration: Declaration) =>
1455
- !lookupLocal(scope, declaration.name) && !findSymbol(declaration.name, unit);
1456
2428
  implicit
1457
- .filter((declaration) => !isMissing(declaration))
2429
+ .filter((item) => !substitutions.has(item.declaration.name))
2430
+ .forEach((item) => {
2431
+ const arity =
2432
+ item.declaration.arity === 0
2433
+ ? 0
2434
+ : getSymbolArity(item.expression, item.declaration.name, scope, unit);
2435
+ if (arity !== item.declaration.arity && instanceRange) {
2436
+ reportArity(item.declaration, formatRange(instanceRange));
2437
+ }
2438
+ substitutions.set(item.declaration.name, item.expression);
2439
+ });
2440
+ declarations
2441
+ .filter((declaration) => !substitutions.has(declaration.name))
1458
2442
  .forEach((declaration) => {
1459
- const expression: Expression = {
1460
- kind: "Identifier",
1461
- name: declaration.name,
1462
- location: instance.location,
1463
- };
1464
- resolveSubstitute(declaration, expression);
1465
- substitutions.set(declaration.name, expression);
2443
+ const declared = declaration.location.range;
2444
+ if (instanceRange && declared) {
2445
+ unit.errors.push({
2446
+ location: formatRange(instanceRange),
2447
+ message: `Substitution missing for symbol ${resolveSynonym(declaration.name)} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
2448
+ });
2449
+ }
1466
2450
  });
1467
- implicit.filter(isMissing).forEach((declaration) => {
1468
- const range = instance.location.range;
1469
- const declared = declaration.location.range;
1470
- if (range && declared) {
1471
- unit.errors.push({
1472
- location: formatRange(range),
1473
- message: `Substitution missing for symbol ${declaration.name} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
1474
- });
1475
- }
1476
- });
1477
2451
  return substitutions;
1478
2452
  };
1479
2453
 
@@ -1481,7 +2455,7 @@ const resolveInstance = (instance: Instance, scope: LocalName | undefined, unit:
1481
2455
  const instanced = unit.getInstance(instance);
1482
2456
  checkSubstitutions(instance, instanced.declarations, instanced.instancer, scope, unit);
1483
2457
  return [...instanced.symbols].reduce(
1484
- (parent, [name, symbol]) => bindName(parent, name, symbol, unit),
2458
+ (parent, entry) => bindName(parent, entry[0], entry[1], unit),
1485
2459
  scope,
1486
2460
  );
1487
2461
  };
@@ -1493,6 +2467,12 @@ export const resolveSubstitutions = (
1493
2467
  unit: ModuleUnit,
1494
2468
  ) => {
1495
2469
  const imported = createSymbols(module, unit.imported);
2470
+ const positions = new Map(
2471
+ [...module.constants, ...module.variables].map((declaration) => [
2472
+ declaration.name,
2473
+ declaration.location,
2474
+ ]),
2475
+ );
1496
2476
  const report: ModuleReport = { location: instance.location, errors: [], warnings: [] };
1497
2477
  unit.reports.push(report);
1498
2478
  return checkSubstitutions(instance, declarations, module.name, undefined, {
@@ -1500,12 +2480,16 @@ export const resolveSubstitutions = (
1500
2480
  getInstance: unit.getInstance,
1501
2481
  definitions: unit.definitions,
1502
2482
  getKey: unit.getKey,
2483
+ isModuleKnown: unit.isModuleKnown,
1503
2484
  location: instance.location,
1504
2485
  self: undefined,
1505
2486
  facts: new Set(),
1506
2487
  goals: new Map(),
1507
2488
  bindings: new Map(
1508
- [...imported].map(([name, symbol]) => [name, { ...symbol, position: MODULE_START }]),
2489
+ [...imported].map((entry) => [
2490
+ entry[0],
2491
+ { ...entry[1], position: positions.get(entry[0]) ?? MODULE_START },
2492
+ ]),
1509
2493
  ),
1510
2494
  errors: report.errors,
1511
2495
  warnings: report.warnings,
@@ -1535,13 +2519,7 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1535
2519
  }
1536
2520
  };
1537
2521
  units
1538
- .toSorted((left, right) =>
1539
- isBefore(left.location, right.location)
1540
- ? -1
1541
- : isBefore(right.location, left.location)
1542
- ? 1
1543
- : 0,
1544
- )
2522
+ .toSorted((left, right) => compareLocations(left.location, right.location))
1545
2523
  .forEach((unit) => {
1546
2524
  const reported: SanyError[] = [];
1547
2525
  const warned: SanyError[] = [];
@@ -1561,21 +2539,27 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1561
2539
 
1562
2540
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
1563
2541
  const symbols = createSymbols(module, unit.imported);
1564
- const facts = new Set([
1565
- ...unit.facts,
1566
- ...[...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
1567
- ]);
1568
2542
  const goals = new Map(
1569
2543
  module.theorems.flatMap((theorem): [string, Goal][] =>
1570
2544
  theorem.name !== undefined && theorem.statement.kind === "AssumeProve"
1571
- ? [[theorem.name, { statement: theorem.statement, isSuffices: false, isInProof: false }]]
2545
+ ? [
2546
+ [
2547
+ theorem.name,
2548
+ {
2549
+ statement: theorem.statement,
2550
+ isSuffices: false,
2551
+ isInProof: false,
2552
+ keyword: undefined,
2553
+ },
2554
+ ],
2555
+ ]
1572
2556
  : [],
1573
2557
  ),
1574
2558
  );
1575
2559
  const bindings = new Map<string, ModuleBinding>(
1576
- [...CORE_SYMBOLS, ...unit.bound].map(([name, symbol]) => [
1577
- name,
1578
- { ...symbol, position: MODULE_START },
2560
+ [...CORE_SYMBOLS, ...unit.bound].map((entry) => [
2561
+ entry[0],
2562
+ { ...entry[1], position: MODULE_START },
1579
2563
  ]),
1580
2564
  );
1581
2565
  const recursive = new Set<Binding>();
@@ -1593,9 +2577,10 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1593
2577
  getInstance: unit.getInstance,
1594
2578
  definitions: unit.definitions,
1595
2579
  getKey: unit.getKey,
2580
+ isModuleKnown: unit.isModuleKnown,
1596
2581
  location,
1597
2582
  self,
1598
- facts,
2583
+ facts: unit.facts,
1599
2584
  goals,
1600
2585
  bindings,
1601
2586
  errors,
@@ -1620,6 +2605,37 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1620
2605
  );
1621
2606
  return collectSemanticErrors(
1622
2607
  [
2608
+ ...module.units.flatMap((item): SemanticUnit[] => {
2609
+ const section =
2610
+ item.kind === "Variables"
2611
+ ? { type: "A VARIABLE declaration", location: item.location }
2612
+ : item.kind === "Constants"
2613
+ ? { type: "A declaration", location: item.location }
2614
+ : item.kind === "Module"
2615
+ ? { type: "A MODULE ", location: item.module.location }
2616
+ : item.kind === "Theorem"
2617
+ ? { type: "A THEOREM", location: item.theorem.location }
2618
+ : item.kind === "Assumption"
2619
+ ? { type: "An ASSUME", location: item.assumption.location }
2620
+ : item.kind === "Use"
2621
+ ? { type: "A USE or HIDE", location: item.use.location }
2622
+ : undefined;
2623
+ const range = section?.location.range;
2624
+ if (!section || !range) return [];
2625
+ return [
2626
+ {
2627
+ location: section.location,
2628
+ check: (errors) => {
2629
+ if (declarations.some((declared) => declared.binding?.isPending)) {
2630
+ errors.push({
2631
+ location: formatRange(range),
2632
+ message: `${section.type} may not appear within a recursive definition section.`,
2633
+ });
2634
+ }
2635
+ },
2636
+ },
2637
+ ];
2638
+ }),
1623
2639
  ...unit.reports.map((report) => ({
1624
2640
  location: report.location,
1625
2641
  check: (errors: SanyError[], warnings: SanyError[]) => {
@@ -1636,6 +2652,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1636
2652
  const binding: ModuleBinding = {
1637
2653
  kind: "Definition",
1638
2654
  arity: declaration.arity,
2655
+ params: Array(declaration.arity).fill(0),
1639
2656
  range: declaration.location.range,
1640
2657
  position: declaration.location,
1641
2658
  isPending: true,
@@ -1701,7 +2718,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1701
2718
  ),
1702
2719
  ...module.uses.map((use) =>
1703
2720
  createCheck(use.location, undefined, false, (inner) =>
1704
- checkFacts(use.facts, undefined, inner),
2721
+ checkUseOrHide(use, undefined, inner),
1705
2722
  ),
1706
2723
  ),
1707
2724
  {
@@ -1712,7 +2729,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1712
2729
  if (range && (!item.binding || item.binding.isPending)) {
1713
2730
  errors.push({
1714
2731
  location: formatRange(range),
1715
- message: `Symbol ${item.declaration.name} declared in RECURSIVE statement but not defined.`,
2732
+ message: `Symbol ${resolveSynonym(item.declaration.name)} declared in RECURSIVE statement but not defined.`,
1716
2733
  });
1717
2734
  }
1718
2735
  }),