tla-ts 0.0.10-dev.99796fe03 → 0.0.10-dev.a17d6d9fa

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 (226) hide show
  1. package/dist/compile.cjs +3 -3
  2. package/dist/compile.js +1 -1
  3. package/dist/deciders.cjs +36 -36
  4. package/dist/deciders.js +54 -54
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.cts +3 -2
  7. package/dist/index.d.ts +3 -2
  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 +60 -60
  14. package/dist/prove.js +78 -78
  15. package/dist/run.cjs +42 -44
  16. package/dist/run.js +44 -46
  17. package/dist/tlapm.cjs +1 -1
  18. package/dist/tlapm.js +2 -2
  19. package/dist/transfer.cjs +43 -43
  20. package/dist/transfer.js +39 -39
  21. package/dist/worker.cjs +6 -6
  22. package/dist/worker.js +6 -6
  23. package/package.json +1 -1
  24. package/src/ast.ts +1 -0
  25. package/src/bags.ts +50 -29
  26. package/src/builtins.ts +4 -3
  27. package/src/check-failure.ts +1 -1
  28. package/src/check-trace.ts +90 -51
  29. package/src/check.ts +367 -178
  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 +1 -2
  33. package/src/cli/tlc.ts +16 -10
  34. package/src/cli/xml-exporter.ts +1 -1
  35. package/src/codegen.ts +26 -9
  36. package/src/dependencies.ts +49 -9
  37. package/src/dfid.ts +22 -10
  38. package/src/environment.ts +58 -33
  39. package/src/errors.ts +7 -0
  40. package/src/evaluate.ts +117 -41
  41. package/src/exit-codes.ts +4 -2
  42. package/src/instances.ts +5 -5
  43. package/src/java-hash.ts +14 -0
  44. package/src/java-overrides.ts +2 -2
  45. package/src/levels.ts +138 -90
  46. package/src/liveness-checker.ts +81 -33
  47. package/src/liveness.ts +49 -11
  48. package/src/obligations/index.ts +1 -1
  49. package/src/obligations/normalize.ts +1 -4
  50. package/src/obligations/printer.ts +5 -5
  51. package/src/parallel-worker.ts +8 -2
  52. package/src/parallel.ts +5 -0
  53. package/src/parser.ts +112 -145
  54. package/src/prover/isabelle/isar/attrib.ts +4 -4
  55. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  56. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  57. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  58. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  59. package/src/prover/isabelle/pure/term.ts +3 -3
  60. package/src/prover/prep/md5.ts +26 -29
  61. package/src/prover/smt/rewrite.ts +2 -7
  62. package/src/prover/smt/simplify.ts +1 -1
  63. package/src/prover/smt/solver/arith-rewriter.ts +11 -3
  64. package/src/prover/smt/solver/array-rewriter.ts +12 -2
  65. package/src/prover/smt/solver/asserted-formulas.ts +169 -58
  66. package/src/prover/smt/solver/ast-lt.ts +1 -1
  67. package/src/prover/smt/solver/ast.ts +63 -14
  68. package/src/prover/smt/solver/auf-solver.ts +23 -12
  69. package/src/prover/smt/solver/bit-blast-tactic.ts +26 -0
  70. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  71. package/src/prover/smt/solver/bound-simplifier.ts +11 -13
  72. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  73. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  74. package/src/prover/smt/solver/card2bv.ts +32 -18
  75. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +39 -24
  76. package/src/prover/smt/solver/context.ts +47 -9
  77. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  78. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  79. package/src/prover/smt/solver/dependent-expr-state.ts +9 -4
  80. package/src/prover/smt/solver/diff-neq.ts +1 -2
  81. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  82. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  83. package/src/prover/smt/solver/elim-uncnstr.ts +5 -8
  84. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  85. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  86. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  87. package/src/prover/smt/solver/euf/egraph.ts +4 -11
  88. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  89. package/src/prover/smt/solver/euf/mam.ts +1 -5
  90. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  91. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  92. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  93. package/src/prover/smt/solver/factor.ts +36 -14
  94. package/src/prover/smt/solver/fd-solver.ts +2 -0
  95. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  96. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  97. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  98. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  99. package/src/prover/smt/solver/goal.ts +6 -3
  100. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  101. package/src/prover/smt/solver/hashtable.ts +4 -0
  102. package/src/prover/smt/solver/internalizer.ts +1 -1
  103. package/src/prover/smt/solver/logic-tactics.ts +9 -2
  104. package/src/prover/smt/solver/lp/lp-settings.ts +5 -1
  105. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  106. package/src/prover/smt/solver/lp/nla-grobner.ts +2 -2
  107. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  108. package/src/prover/smt/solver/lp/pdd.ts +2 -3
  109. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  110. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  111. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  112. package/src/prover/smt/solver/model-evaluator.ts +2 -0
  113. package/src/prover/smt/solver/model-generator.ts +85 -43
  114. package/src/prover/smt/solver/mpf.ts +2 -4
  115. package/src/prover/smt/solver/mus.ts +2 -3
  116. package/src/prover/smt/solver/muz/dl-context.ts +10 -4
  117. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  118. package/src/prover/smt/solver/muz/dl-rule.ts +2 -2
  119. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  120. package/src/prover/smt/solver/muz/horn-tactic.ts +1 -1
  121. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  122. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  123. package/src/prover/smt/solver/nlqsat.ts +1 -1
  124. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  125. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  126. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  127. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  128. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  129. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  130. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  131. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  132. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  133. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  134. package/src/prover/smt/solver/nnf.ts +6 -2
  135. package/src/prover/smt/solver/opt-context.ts +20 -7
  136. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  137. package/src/prover/smt/solver/opt-pareto.ts +19 -0
  138. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  139. package/src/prover/smt/solver/opt-solver.ts +9 -5
  140. package/src/prover/smt/solver/optsmt.ts +1 -1
  141. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  142. package/src/prover/smt/solver/poly-rewriter.ts +75 -18
  143. package/src/prover/smt/solver/probes.ts +88 -23
  144. package/src/prover/smt/solver/proto-model.ts +8 -8
  145. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  146. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  147. package/src/prover/smt/solver/qe-lite.ts +2 -2
  148. package/src/prover/smt/solver/qe.ts +3 -2
  149. package/src/prover/smt/solver/qsat.ts +16 -6
  150. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  151. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  152. package/src/prover/smt/solver/rewriter.ts +31 -25
  153. package/src/prover/smt/solver/rlimit.ts +4 -0
  154. package/src/prover/smt/solver/sat/config.ts +1 -1
  155. package/src/prover/smt/solver/sat/goal2sat.ts +0 -1
  156. package/src/prover/smt/solver/sat/inc-sat-solver.ts +39 -5
  157. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  158. package/src/prover/smt/solver/sat/pb-solver.ts +1 -1
  159. package/src/prover/smt/solver/sat/sat-tactic.ts +13 -5
  160. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  161. package/src/prover/smt/solver/sat/solver.ts +25 -47
  162. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  163. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  164. package/src/prover/smt/solver/seq-derive.ts +2 -2
  165. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  166. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  167. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  168. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  169. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  170. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  171. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  172. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  173. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  174. package/src/prover/smt/solver/smt-kernel.ts +39 -5
  175. package/src/prover/smt/solver/smt-setup.ts +96 -10
  176. package/src/prover/smt/solver/smtlib-parser.ts +584 -223
  177. package/src/prover/smt/solver/smtlib-script.ts +509 -154
  178. package/src/prover/smt/solver/solve-eqs.ts +36 -37
  179. package/src/prover/smt/solver/solver.ts +18 -3
  180. package/src/prover/smt/solver/tactic.ts +284 -168
  181. package/src/prover/smt/solver/theory-bv.ts +13 -3
  182. package/src/prover/smt/solver/theory-fpa.ts +1 -1
  183. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -0
  184. package/src/prover/smt/solver/theory-lra-internalize.ts +2 -0
  185. package/src/prover/smt/solver/theory-lra-propagate.ts +11 -3
  186. package/src/prover/smt/solver/theory-lra.ts +1 -1
  187. package/src/prover/smt/solver/theory-pb.ts +24 -7
  188. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  189. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  190. package/src/prover/smt/solver/tseitin-cnf.ts +1 -0
  191. package/src/prover/tlapm/cache.ts +8 -8
  192. package/src/prover/zenon/index-table.ts +5 -2
  193. package/src/prover/zenon/isar-case.ts +1 -1
  194. package/src/prover/zenon/isar.ts +2 -2
  195. package/src/prover/zenon/phrase.ts +1 -1
  196. package/src/resolve.ts +959 -243
  197. package/src/runtime.ts +7 -1
  198. package/src/sany/builtins.ts +10 -10
  199. package/src/sany/generation.ts +2 -13
  200. package/src/sany/generator-definitions.ts +3 -1
  201. package/src/sany/generator-expressions.ts +36 -30
  202. package/src/sany/generator-proofs.ts +5 -3
  203. package/src/sany/generator.ts +2 -1
  204. package/src/sany/lexer.ts +3 -3
  205. package/src/sany/modules.ts +4 -2
  206. package/src/sany/nodes.ts +1 -1
  207. package/src/sany/selectors.ts +11 -6
  208. package/src/sany/xml.ts +2 -3
  209. package/src/search.ts +166 -101
  210. package/src/simulate.ts +110 -50
  211. package/src/spec-description.ts +5 -6
  212. package/src/standard-modules.ts +15 -6
  213. package/src/subexpressions.ts +398 -108
  214. package/src/successors.ts +4 -2
  215. package/src/symmetry.ts +1 -1
  216. package/src/tlc/jar-data.ts +10 -0
  217. package/src/tlc/messages.ts +3 -3
  218. package/src/tlc/order.ts +14 -3
  219. package/src/tlc/random.ts +2 -1
  220. package/src/tlc/replay.ts +3 -2
  221. package/src/tlc/tlc-operators.ts +10 -8
  222. package/src/tlc/tlcext-operators.ts +44 -15
  223. package/src/tlc/trace-spec.ts +9 -22
  224. package/src/typed-tier.ts +32 -25
  225. package/src/typescript/types.ts +2 -2
  226. package/src/values.ts +135 -78
package/src/resolve.ts CHANGED
@@ -18,9 +18,12 @@ 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 { resolveSynonym } from "./tlc/jar-data";
24
27
 
25
28
  export type SymbolKind =
26
29
  | "Builtin"
@@ -49,6 +52,7 @@ interface Goal {
49
52
  statement: Expression | AssumeProve;
50
53
  isSuffices: boolean;
51
54
  isInProof: boolean;
55
+ keyword: string | undefined;
52
56
  }
53
57
 
54
58
  interface LocalName extends Binding {
@@ -84,8 +88,16 @@ interface Unit {
84
88
  isGenerated: boolean;
85
89
  }
86
90
 
87
- interface SelectionError {
91
+ export interface SelectionArguments {
92
+ operator: string;
93
+ range: SourceRange | undefined;
88
94
  args: Expression[];
95
+ params: number[];
96
+ }
97
+
98
+ interface SelectionError {
99
+ applications: SelectionArguments[];
100
+ nulls: NullSelection[];
89
101
  error: SanyError;
90
102
  }
91
103
 
@@ -99,8 +111,40 @@ type Reference = Expression & { kind: "Identifier" | "Apply" | "Subexpression" }
99
111
 
100
112
  export const LOCAL_RESOLUTION = { kind: "Local" } as const;
101
113
 
114
+ export const SELECTION_NAME = "$subexpression";
115
+
116
+ export interface NullSelection {
117
+ node: Expression;
118
+ error: SanyError;
119
+ isEmpty: boolean;
120
+ }
121
+
122
+ interface SelectionArgument {
123
+ operator: string;
124
+ index: number;
125
+ range: SourceRange | undefined;
126
+ }
127
+
102
128
  export const selections = new WeakSet<Expression>();
103
129
  export const selectionErrors = new WeakMap<Expression, SelectionError>();
130
+ export const operatorSelectionErrors = new WeakMap<Expression, SanyError>();
131
+ export const factReferences = new WeakMap<Fact[], Fact[]>();
132
+ export const selectionArguments = new WeakMap<Expression, SelectionArgument>();
133
+ export const nullSelections = new WeakMap<Expression, NullSelection[]>();
134
+ export const selectionSources = new WeakMap<Expression, Expression>();
135
+ const unresolvedExpressions = new WeakSet<Expression>();
136
+ const emptyExpressions = new WeakSet<Expression>();
137
+
138
+ // SANY's failed selection is an operator application with no operands.
139
+ const isEmptyExpression = (expression: Expression): boolean =>
140
+ emptyExpressions.has(expression) || findNullError(nullSelections.get(expression)) !== undefined;
141
+
142
+ const findNullError = (nulls: NullSelection[] | undefined) =>
143
+ nulls?.find((selection) =>
144
+ selection.isEmpty
145
+ ? isEmptyExpression(selection.node)
146
+ : unresolvedExpressions.has(selection.node),
147
+ )?.error;
104
148
 
105
149
  const renamedArities = new WeakMap<Expression, number>();
106
150
 
@@ -111,13 +155,20 @@ const isKey = (name: string) => {
111
155
  return index > 0 && index < name.length - 1;
112
156
  };
113
157
 
114
- const CORE_SYMBOLS: Symbols = new Map(
115
- ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2, kind: "Builtin" }]),
116
- );
158
+ const CORE_SYMBOLS: Symbols = new Map([
159
+ ...["~>", "-+->", "\\cdot", "\\X"].map((name): [string, ModuleSymbol] => [
160
+ name,
161
+ { key: name, arity: 2, kind: "Builtin" },
162
+ ]),
163
+ ["'", { key: "'", arity: 1, kind: "Builtin" }],
164
+ ]);
117
165
 
118
166
  export const isBefore = (left: SourceLocation, right: SourceLocation) =>
119
167
  left.line < right.line || (left.line === right.line && left.column < right.column);
120
168
 
169
+ const compareLocations = (left: SourceLocation, right: SourceLocation) =>
170
+ isBefore(left, right) ? -1 : isBefore(right, left) ? 1 : 0;
171
+
121
172
  export const getArity = (definition: Definition) =>
122
173
  definition.kind === "Operator" ? definition.params.length : 0;
123
174
 
@@ -157,7 +208,7 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
157
208
  if (current.kind === "Builtin") {
158
209
  unit.errors.push({
159
210
  location,
160
- message: `Symbol ${name} is a built-in operator, and cannot be redefined.`,
211
+ message: `Symbol ${resolveSynonym(name)} is a built-in operator, and cannot be redefined.`,
161
212
  });
162
213
  } else if (
163
214
  added.kind === "Parameter" ||
@@ -166,12 +217,12 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
166
217
  ) {
167
218
  unit.errors.push({
168
219
  location,
169
- message: `Multiply-defined symbol '${name}': this definition or declaration conflicts \nwith the one at ${existing}.`,
220
+ message: `Multiply-defined symbol '${resolveSynonym(name)}': this definition or declaration conflicts \nwith the one at ${existing}.`,
170
221
  });
171
222
  } else {
172
223
  unit.warnings.push({
173
224
  location,
174
- message: `Multiple declarations or definitions for symbol ${name}. \nThis duplicates the one at ${existing}.`,
225
+ message: `Multiple declarations or definitions for symbol ${resolveSynonym(name)}. \nThis duplicates the one at ${existing}.`,
175
226
  });
176
227
  }
177
228
  return false;
@@ -233,23 +284,38 @@ const getVisibleDefinition = (name: string, unit: Unit) => {
233
284
  const isVisible =
234
285
  definition !== undefined &&
235
286
  (definition === unit.self
236
- ? definition.kind === "Function" || definition.isRecursive
237
- : definition.isRecursive || isBefore(definition.location, unit.location));
287
+ ? definition.isRecursive
288
+ : definition.isRecursive
289
+ ? getModuleBinding(name, unit, undefined) !== undefined
290
+ : isBefore(definition.location, unit.location));
238
291
  return isVisible ? definition : undefined;
239
292
  };
240
293
 
241
294
  const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
242
295
  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);
296
+ if (definition) {
297
+ const declared = definition.isRecursive ? unit.bindings.get(name) : undefined;
298
+ return {
299
+ key: unit.getKey(definition),
300
+ arity: declared?.arity ?? getArity(definition),
301
+ params: declared?.params ?? getParamArities(definition),
302
+ kind: "Definition",
303
+ range: definition.location.range,
304
+ };
305
+ }
306
+ const binding = getModuleBinding(name, unit, undefined);
307
+ if (binding?.isPending) {
308
+ return { key: name, arity: binding.arity, params: binding.params, kind: binding.kind };
309
+ }
310
+ return binding ? unit.imported.get(name) : undefined;
251
311
  };
252
312
 
313
+ const isFact = (name: string, unit: Unit) =>
314
+ unit.facts.has(name) || unit.bindings.get(name)?.kind === "Theorem";
315
+
316
+ const getGoal = (name: string, unit: Unit) =>
317
+ unit.bindings.get(name)?.kind === "Theorem" ? unit.goals.get(name) : undefined;
318
+
253
319
  const findBinding = (name: string, scope: LocalName | undefined, unit: Unit): Binding | undefined =>
254
320
  lookupLocal(scope, name) ?? findSymbol(name, unit);
255
321
 
@@ -271,12 +337,22 @@ const getSpelledNameRange = (
271
337
  };
272
338
 
273
339
  const getFixity = (expression: Expression) => {
274
- if (expression.kind !== "Apply") return undefined;
340
+ if (expression.kind !== "Apply" || expression.argumentsRange) return undefined;
275
341
  if (expression.args.length === 2) return "infix";
276
342
  if (expression.args.length !== 1) return undefined;
277
- return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
343
+ return expression.operator === "-." ? "prefix" : "postfix";
278
344
  };
279
345
 
346
+ const BUILTIN_LOCATION = "In module --TLA+ BUILTINS--";
347
+
348
+ const SELECTABLE_KINDS = new Set<SymbolKind>(["Definition", "Instance", "Theorem"]);
349
+
350
+ const reportUnselectable = (name: string, range: SourceRange, unit: Unit) =>
351
+ unit.errors.push({
352
+ location: formatRange(range),
353
+ message: `Cannot take subexpression of \`${resolveSynonym(name)}'.`,
354
+ });
355
+
280
356
  const isOperatorSymbol = (name: string) => !/^[\p{L}\d_]/u.test(name);
281
357
 
282
358
  const isStepName = (name: string) =>
@@ -453,7 +529,6 @@ const checkSelection = (
453
529
  reference: Reference,
454
530
  selectors: Selector[],
455
531
  goal: Goal,
456
- scope: LocalName | undefined,
457
532
  unit: Unit,
458
533
  isFact: boolean,
459
534
  ) => {
@@ -462,6 +537,7 @@ const checkSelection = (
462
537
  (index === undefined ? undefined : reference.selectorRanges?.[index]) ??
463
538
  reference.location.range;
464
539
  if (range) unit.errors.push({ location: formatRange(range), message });
540
+ return undefined;
465
541
  };
466
542
  const isOutOfScope = goal.isSuffices === goal.isInProof;
467
543
  const statement = goal.statement;
@@ -470,6 +546,8 @@ const checkSelection = (
470
546
  isGoal: true,
471
547
  isSufficesOpen: goal.isSuffices,
472
548
  };
549
+ let params = 0;
550
+ let args = 0;
473
551
  for (const [offset, selector] of selectors.slice(1).entries()) {
474
552
  const index = offset + 1;
475
553
  const node = state.node;
@@ -479,9 +557,7 @@ const checkSelection = (
479
557
  node.kind !== "NewSymbol" &&
480
558
  node.kind !== "AssumeProve" &&
481
559
  getLabelBody(node).kind === "Let";
482
- return isLet
483
- ? undefined
484
- : report(index - 1, "A name selector here must be from a LET clause.");
560
+ return isLet ? node : report(index - 1, "A name selector here must be from a LET clause.");
485
561
  }
486
562
  const clauses =
487
563
  statement.kind === "AssumeProve"
@@ -519,10 +595,18 @@ const checkSelection = (
519
595
  state.isSufficesOpen = false;
520
596
  continue;
521
597
  }
522
- if (selector.kind !== "Operand") return;
523
- const operand = getOperandName(selector.operand);
598
+ if (selector.kind === "Colon") return node;
599
+ const operand =
600
+ selector.kind === "Operand"
601
+ ? getOperandName(selector.operand)
602
+ : selector.kind === "At"
603
+ ? "@"
604
+ : "!(...)";
605
+ const getPosition = (count: number) =>
606
+ selector.kind === "Operand" ? getOperandIndex(selector.operand, count) : -1;
607
+ const unexpectedNull = `An unexpected null node specified by '${operand}'.\nThis is probably due to a previous error.`;
524
608
  if (state.isSufficesOpen) {
525
- if (getOperandIndex(selector.operand, 1) !== 0) {
609
+ if (getPosition(1) !== 0) {
526
610
  return report(
527
611
  index,
528
612
  node.kind === "AssumeProve"
@@ -533,20 +617,37 @@ const checkSelection = (
533
617
  state.isSufficesOpen = false;
534
618
  continue;
535
619
  }
536
- if (node.kind === "NewSymbol") return;
620
+ if (node.kind === "NewSymbol") return node;
537
621
  if (node.kind !== "AssumeProve") {
538
622
  const expression = getLabelBody(node);
623
+ if (unresolvedExpressions.has(expression)) {
624
+ return report(
625
+ index,
626
+ "Subexpression selection failed, probably due to an error in the selected expression.",
627
+ );
628
+ }
539
629
  if (["Number", "Decimal", "String"].includes(expression.kind)) {
540
630
  return report(index, "Selecting subexpression of expression that has none.");
541
631
  }
542
- const kind =
543
- expression.kind === "Identifier"
544
- ? findBinding(expression.name, scope, unit)?.kind
545
- : undefined;
546
- if (kind === "Variable" || kind?.startsWith("New")) {
632
+ if (isEmptyExpression(expression)) {
547
633
  return report(index, `Choosing operand \`${operand}' of subexpression with no operands.`);
548
634
  }
549
- const sets = getBinder(expression)?.sets;
635
+ const binder = getBinder(expression);
636
+ if (binder && selector.kind !== "Operand") {
637
+ const count = selector.kind === "Bound" ? selector.args.length : 0;
638
+ if (selector.kind === "Bound" && count !== binder.names.length) {
639
+ return report(
640
+ index,
641
+ `Selector with ${count} argument(s) used for quantifier with ${binder.names.length} bound identifier(s).`,
642
+ );
643
+ }
644
+ params += binder.names.length;
645
+ args += count;
646
+ state.node = binder.body;
647
+ state.isGoal = false;
648
+ continue;
649
+ }
650
+ const sets = binder?.sets;
550
651
  const operands =
551
652
  expression.kind === "Identifier"
552
653
  ? []
@@ -554,18 +655,21 @@ const checkSelection = (
554
655
  ? sets.length > 0
555
656
  ? sets
556
657
  : undefined
557
- : expression.kind === "Except"
558
- ? undefined
559
- : getOperands(expression);
560
- if (!operands) return;
561
- const position = getOperandIndex(selector.operand, operands.length);
658
+ : getOperands(expression);
659
+ if (!operands) return node;
660
+ const isExcept = expression.kind === "Except";
661
+ const position = getPosition(isExcept ? expression.updates.length + 1 : operands.length);
562
662
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
663
+ if (isExcept && position > 0) {
664
+ return report(index, "Selecting subexpression of an EXCEPT not yet implemented.");
665
+ }
563
666
  state.node = operands[position];
564
667
  state.isGoal = false;
668
+ if (unresolvedExpressions.has(state.node)) return report(index, unexpectedNull);
565
669
  continue;
566
670
  }
567
671
  const clauses = [...node.assumptions, node.conclusion];
568
- const position = getOperandIndex(selector.operand, clauses.length);
672
+ const position = getPosition(clauses.length);
569
673
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
570
674
  if (isInScopeOfDeclaration(node, position) && (!state.isGoal || isOutOfScope)) {
571
675
  return report(index, `Accessing ASSUME/PROVE clause ${SCOPE_MESSAGE}`);
@@ -576,14 +680,24 @@ const checkSelection = (
576
680
  }
577
681
  state.node = clause;
578
682
  state.isGoal = false;
683
+ if (
684
+ clause.kind !== "NewSymbol" &&
685
+ clause.kind !== "AssumeProve" &&
686
+ unresolvedExpressions.has(clause)
687
+ ) {
688
+ return report(index, unexpectedNull);
689
+ }
579
690
  }
580
- if (isFact) return;
581
691
  if (state.node.kind === "AssumeProve") {
582
- report(undefined, "Selected ASSUME/PROVE instead of expression.");
692
+ return isFact ? state.node : report(undefined, "Selected ASSUME/PROVE instead of expression.");
583
693
  }
584
694
  if (state.node.kind === "NewSymbol") {
585
- report(undefined, "Selected a NEW declaration as an expression or operator.");
695
+ return isFact
696
+ ? state.node
697
+ : report(undefined, "Selected a NEW declaration as an expression or operator.");
586
698
  }
699
+ if (params !== args) return report(undefined, `Expected ${params} arguments but found ${args}.`);
700
+ return state.node;
587
701
  };
588
702
 
589
703
  const isLabelReported = (label: LabelExpression, unit: Unit) => {
@@ -659,10 +773,9 @@ const checkReference = (
659
773
  const first = selectors[0];
660
774
  const goal =
661
775
  selectors.length > 1 && first.kind === "Name"
662
- ? (lookupLocal(scope, first.name)?.goal ?? unit.goals.get(first.name))
776
+ ? (lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit))
663
777
  : undefined;
664
- if (goal) checkSelection(expression, selectors, goal, scope, unit, isFact);
665
- return goal !== undefined;
778
+ return goal && { node: checkSelection(expression, selectors, goal, unit, isFact) };
666
779
  };
667
780
 
668
781
  const getSymbolArity = (
@@ -684,6 +797,14 @@ const getSymbolArity = (
684
797
  });
685
798
  return undefined;
686
799
  }
800
+ const keyword = local?.goal?.keyword;
801
+ if (keyword) {
802
+ unit.errors.push({
803
+ location: formatRange(getSpelledNameRange(expression, name)),
804
+ message: `${keyword} proof step selected instead of expression.`,
805
+ });
806
+ return undefined;
807
+ }
687
808
  if (checkReference(expression, scope, unit, false) || (isStepName(name) && local)) {
688
809
  return expression.kind === "Apply" ? expression.args.length : 0;
689
810
  }
@@ -697,29 +818,55 @@ const getSymbolArity = (
697
818
  return symbol.arity;
698
819
  }
699
820
  const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
700
- const isSelected =
821
+ const selected =
822
+ prefix === "" ? undefined : (lookupLocal(scope, prefix) ?? findSymbol(prefix, unit));
823
+ if (selected && !SELECTABLE_KINDS.has(selected.kind)) {
824
+ reportUnselectable(
825
+ prefix,
826
+ (expression.kind !== "OperatorReference" && expression.selectorRanges?.[0]) ||
827
+ getSpelledNameRange(expression, name),
828
+ unit,
829
+ );
830
+ return undefined;
831
+ }
832
+ if (
833
+ expression.kind !== "OperatorReference" &&
701
834
  prefix !== "" &&
702
- (lookupLocal(scope, prefix) !== undefined ||
703
- findSymbol(prefix, unit) !== undefined ||
704
- unit.facts.has(prefix));
705
- if (isSelected) {
835
+ isPendingSelectionReported(
836
+ prefix,
837
+ expression.kind === "Apply" && expression.argumentCounts
838
+ ? expression.args.slice(0, expression.argumentCounts[0])
839
+ : [],
840
+ expression.selectorRanges?.[0],
841
+ (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ?? location.range,
842
+ scope,
843
+ unit,
844
+ )
845
+ ) {
846
+ return undefined;
847
+ }
848
+ if (selected || (prefix !== "" && isFact(prefix, unit))) {
706
849
  return expression.kind === "Apply" ? expression.args.length : 0;
707
850
  }
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}'.` });
851
+ const fixity = getFixity(expression);
852
+ const isOperatorApplication = expression.kind === "OperatorReference" || fixity !== undefined;
853
+ if (!isOperatorSymbol(name) || isStepName(name) || !isOperatorApplication) {
854
+ unit.errors.push({
855
+ location: formatRange(getSpelledNameRange(expression, name)),
856
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
857
+ });
716
858
  return undefined;
717
859
  }
860
+ const spelling = expression.spelling ?? name;
718
861
  unit.errors.push({
719
- location: range,
862
+ location: formatRange(
863
+ fixity === "prefix" && spelling === "-."
864
+ ? getNameRange(location, "-")
865
+ : getSpelledNameRange(expression, name),
866
+ ),
720
867
  message: `Could not find declaration or definition of symbol '${spelling}'.`,
721
868
  });
722
- const fixity = getFixity(expression);
869
+ if (fixity) unresolvedExpressions.add(expression);
723
870
  if (fixity && location.range) {
724
871
  unit.errors.push({
725
872
  location: formatRange(location.range),
@@ -774,15 +921,30 @@ const resolveDefinition = (
774
921
  const isDeclared = current?.isPending === true && recursive.has(current);
775
922
  if (current?.isPending && !isDeclared) {
776
923
  report(
777
- `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${name} defined at wrong LET/IN level.`,
924
+ `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${resolveSynonym(name)} defined at wrong LET/IN level.`,
778
925
  );
779
926
  } else if (current && !isDeclared) {
780
927
  report(
781
928
  definition.kind === "Function"
782
929
  ? `Function name \`${name}' already defined or declared.`
783
- : `Operator ${name} already defined or declared.`,
930
+ : `Operator ${resolveSynonym(name)} already defined or declared.`,
931
+ );
932
+ } else if (current && definition.kind === "Function" && current.arity > 0) {
933
+ report(`Function ${resolveSynonym(name)} has operator arguments in its RECURSIVE declaration.`);
934
+ } else if (
935
+ current &&
936
+ definition.kind === "Operator" &&
937
+ // Deviation from SANY: Generator#processOperator compares only the last parameter's arity with the RECURSIVE declaration's.
938
+ (current.arity !== definition.params.length ||
939
+ definition.params.some((param) => param.arity > 0))
940
+ ) {
941
+ report(
942
+ `Definition of ${resolveSynonym(name)} has different arity than its RECURSIVE declaration.`,
784
943
  );
785
944
  }
945
+ if (current && isDeclared && definition.kind === "Operator") {
946
+ current.params = getParamArities(definition);
947
+ }
786
948
  if (definition.kind === "Function") {
787
949
  resolveExpression(
788
950
  definition.body,
@@ -793,8 +955,10 @@ const resolveDefinition = (
793
955
  definition.isSelfReferential = isReferenced(definition.body, name);
794
956
  } else resolveExpression(definition.body, inner, unit);
795
957
  if (current && isDeclared) {
796
- current.isPending = false;
797
- current.range = range;
958
+ if (definition.kind === "Operator" || current.arity === 0) {
959
+ current.isPending = false;
960
+ current.range = range;
961
+ }
798
962
  return false;
799
963
  }
800
964
  return definition.kind === "Function"
@@ -812,10 +976,15 @@ const resolveDefinitions = (
812
976
  scope: LocalName | undefined,
813
977
  unit: Unit,
814
978
  instances: Instance[] = [],
979
+ declarations: Declaration[] = [],
815
980
  ) => {
816
981
  const recursive = new Set<Binding>();
817
982
  const declared = definitions
818
- .filter((definition) => definition.isRecursive)
983
+ .filter(
984
+ (definition) =>
985
+ definition.isRecursive &&
986
+ declarations.every((declaration) => declaration.name !== definition.name),
987
+ )
819
988
  .reduce<LocalName | undefined>((parent, definition) => {
820
989
  if (lookupLocal(parent, definition.name)?.isPending) return parent;
821
990
  const local: LocalName = {
@@ -829,20 +998,47 @@ const resolveDefinitions = (
829
998
  recursive.add(local);
830
999
  return local;
831
1000
  }, scope);
832
- const pending = unit.isGenerated ? [] : [...instances];
833
- const resolveInstances = (
1001
+ const declaredLocals = new Map<Declaration, LocalName | undefined>();
1002
+ const bindDeclaration = (parent: LocalName | undefined, declaration: Declaration) => {
1003
+ const binding: Binding = {
1004
+ kind: "Definition",
1005
+ arity: declaration.arity,
1006
+ params: Array(declaration.arity).fill(0),
1007
+ range: declaration.location.range,
1008
+ };
1009
+ const local: LocalName | undefined = isBindable(
1010
+ declaration.name,
1011
+ lookupLocal(parent, declaration.name) ??
1012
+ getModuleBinding(declaration.name, unit, binding.range),
1013
+ binding,
1014
+ unit,
1015
+ )
1016
+ ? { ...binding, name: declaration.name, parent, isPending: true }
1017
+ : undefined;
1018
+ if (local) recursive.add(local);
1019
+ declaredLocals.set(declaration, local);
1020
+ return local ?? parent;
1021
+ };
1022
+ const pending = [...(unit.isGenerated ? [] : instances), ...declarations].toSorted(
1023
+ (left, right) => compareLocations(left.location, right.location),
1024
+ );
1025
+ const resolvePending = (
834
1026
  current: LocalName | undefined,
835
- isDue: (instance: Instance) => boolean,
1027
+ isDue: (item: Instance | Declaration) => boolean,
836
1028
  ) => {
837
- const count = pending.findIndex((instance) => !isDue(instance));
1029
+ const count = pending.findIndex((item) => !isDue(item));
838
1030
  return pending
839
1031
  .splice(0, count === -1 ? pending.length : count)
840
- .reduce((parent, instance) => resolveLocalInstance(instance, parent, unit), current);
1032
+ .reduce(
1033
+ (parent, item) =>
1034
+ "kind" in item ? resolveLocalInstance(item, parent, unit) : bindDeclaration(parent, item),
1035
+ current,
1036
+ );
841
1037
  };
842
1038
  const resolved = definitions.reduce<LocalName | undefined>((previous, definition) => {
843
1039
  const current = isKey(definition.name)
844
1040
  ? previous
845
- : resolveInstances(previous, (instance) => !isBefore(definition.location, instance.location));
1041
+ : resolvePending(previous, (item) => !isBefore(definition.location, item.location));
846
1042
  const local: LocalName = {
847
1043
  name: definition.name,
848
1044
  arity: getArity(definition),
@@ -862,7 +1058,17 @@ const resolveDefinitions = (
862
1058
  ? { ...local, params: getParamArities(definition) }
863
1059
  : current;
864
1060
  }, declared);
865
- return resolveInstances(resolved, () => true);
1061
+ const resolvedScope = resolvePending(resolved, () => true);
1062
+ declaredLocals.forEach((local, declaration) => {
1063
+ const range = declaration.location.range;
1064
+ if (range && !unit.isGenerated && (!local || local.isPending)) {
1065
+ unit.errors.push({
1066
+ location: formatRange(range),
1067
+ message: `Symbol ${resolveSynonym(declaration.name)} declared in RECURSIVE statement but not defined.`,
1068
+ });
1069
+ }
1070
+ });
1071
+ return resolvedScope;
866
1072
  };
867
1073
 
868
1074
  const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) => {
@@ -871,7 +1077,9 @@ const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) =>
871
1077
  prefix === name
872
1078
  ? undefined
873
1079
  : (lookupLocal(scope, prefix) ?? getModuleBinding(prefix, unit, undefined));
874
- return binding?.kind === "Instance" ? { name: prefix, arity: binding.arity } : undefined;
1080
+ return binding?.kind === "Instance"
1081
+ ? { name: prefix, arity: binding.arity, range: binding.range }
1082
+ : undefined;
875
1083
  };
876
1084
 
877
1085
  const isInstanceArityReported = (
@@ -879,16 +1087,22 @@ const isInstanceArityReported = (
879
1087
  scope: LocalName | undefined,
880
1088
  unit: Unit,
881
1089
  ) => {
882
- if (expression.kind !== "Identifier" && expression.kind !== "Apply") return false;
1090
+ if (!isReference(expression)) return false;
1091
+ const selectors = getSelectors(expression);
1092
+ const nameCount = selectors.findIndex((selector) => selector.kind !== "Name");
883
1093
  const instance = findInstance(
884
- expression.kind === "Identifier" ? expression.name : expression.operator,
1094
+ selectors
1095
+ .slice(0, nameCount === -1 ? selectors.length : nameCount)
1096
+ .flatMap((selector) => (selector.kind === "Name" ? [selector.name] : []))
1097
+ .join("!"),
885
1098
  scope,
886
1099
  unit,
887
1100
  );
888
- const count = expression.kind === "Apply" ? (expression.argumentCounts?.[0] ?? 0) : 0;
1101
+ const first = selectors[0];
1102
+ const count = first.kind === "Name" ? first.args.length : 0;
889
1103
  if (!instance || count === instance.arity) return false;
890
1104
  const range =
891
- (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ??
1105
+ (expression.kind === "Identifier" ? undefined : expression.argumentRanges?.[0]) ??
892
1106
  expression.location.range;
893
1107
  if (range) {
894
1108
  unit.errors.push({
@@ -899,103 +1113,183 @@ const isInstanceArityReported = (
899
1113
  return true;
900
1114
  };
901
1115
 
1116
+ const isArgumentCountReported = (
1117
+ callee: Binding | undefined,
1118
+ name: string,
1119
+ count: number,
1120
+ range: SourceRange | undefined,
1121
+ unit: Unit,
1122
+ ) => {
1123
+ const params = callee?.kind === "Definition" ? callee.params : undefined;
1124
+ if (!callee || !params || params.length === callee.arity) return false;
1125
+ if (range && !unit.isGenerated) {
1126
+ unit.errors.push({
1127
+ location: formatRange(range),
1128
+ message: `Wrong number of arguments (${count}) given to operator '${resolveSynonym(name)}', \nwhich requires ${params.length} arguments.`,
1129
+ });
1130
+ }
1131
+ return true;
1132
+ };
1133
+
1134
+ const resolveExpressionArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
1135
+ const range = arg.location.range;
1136
+ const report = (message: string) => {
1137
+ if (range) unit.errors.push({ location: formatRange(range), message });
1138
+ };
1139
+ const selectionError = operatorSelectionErrors.get(arg);
1140
+ // Deviation from SANY: SANY names its internal node kind here, where tla-ts words it as for a name.
1141
+ if (arg.kind === "Lambda" && arg.operator !== undefined) {
1142
+ report(`The operator ${resolveSynonym(arg.operator)} requires 1 arguments.`);
1143
+ } else if (selectionError) {
1144
+ unit.errors.push(selectionError);
1145
+ } else if (arg.kind === "Lambda" && range) {
1146
+ unresolvedExpressions.add(arg);
1147
+ report("LAMBDA expression used where an expression is required.");
1148
+ } else if (arg.kind === "OperatorReference") {
1149
+ const argArity = getSymbolArity(arg, arg.operator, scope, unit);
1150
+ if (argArity !== undefined) {
1151
+ report(`The operator ${resolveSynonym(arg.operator)} requires ${argArity} arguments.`);
1152
+ }
1153
+ } else resolveExpression(arg, scope, unit);
1154
+ };
1155
+
1156
+ const matchArgument = (
1157
+ arg: Expression,
1158
+ expected: number,
1159
+ index: number,
1160
+ operator: string,
1161
+ operatorRange: SourceRange | undefined,
1162
+ scope: LocalName | undefined,
1163
+ unit: Unit,
1164
+ ) => {
1165
+ const report = (range: SourceRange | undefined, message: string) => {
1166
+ if (range) unit.errors.push({ location: formatRange(range), message });
1167
+ };
1168
+ const reportOperatorArity = (name: string, arity: number) => {
1169
+ const definition =
1170
+ findInstance(operator, scope, unit)?.range ?? findBinding(operator, scope, unit)?.range;
1171
+ if (!definition) return;
1172
+ report(
1173
+ operatorRange,
1174
+ `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.`,
1175
+ );
1176
+ };
1177
+ const range = arg.location.range;
1178
+ if (expected === 0) {
1179
+ resolveExpressionArgument(arg, scope, unit);
1180
+ return true;
1181
+ }
1182
+ if (arg.kind === "Lambda") {
1183
+ if (selections.has(arg)) resolveExpression(arg, scope, unit);
1184
+ else resolveLambda(arg, scope, unit);
1185
+ const isMatched = arg.params.length === expected;
1186
+ if (!isMatched && selections.has(arg)) {
1187
+ report(range, `Expected arity ${expected} but found operator of arity ${arg.params.length}.`);
1188
+ } else if (!isMatched && range && arg.operator === undefined) {
1189
+ report(
1190
+ operatorRange,
1191
+ `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
1192
+ );
1193
+ } else if (!isMatched && arg.operator !== undefined) {
1194
+ reportOperatorArity(arg.operator, arg.params.length);
1195
+ }
1196
+ return isMatched;
1197
+ }
1198
+ if (arg.kind === "Subexpression") {
1199
+ resolveExpression(arg, scope, unit);
1200
+ return true;
1201
+ }
1202
+ if (arg.kind === "Apply" && arg.argumentCounts?.at(-1) === 0) {
1203
+ const selectorIndex = arg.argumentCounts.findIndex((count) => count > 0);
1204
+ report(
1205
+ arg.selectorRanges?.[selectorIndex],
1206
+ `Selector \`${arg.operator.split("!")[selectorIndex]}' should not have argument(s).`,
1207
+ );
1208
+ return false;
1209
+ }
1210
+ if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
1211
+ report(
1212
+ range,
1213
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
1214
+ );
1215
+ return false;
1216
+ }
1217
+ const name = arg.kind === "Identifier" ? arg.name : arg.operator;
1218
+ const argParams = findBinding(name, scope, unit)?.params ?? [];
1219
+ const argArity = getSymbolArity(arg, name, scope, unit);
1220
+ if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
1221
+ report(
1222
+ getSpelledNameRange(arg, name),
1223
+ `Expected arity ${expected} but found operator of arity ${argArity}.`,
1224
+ );
1225
+ }
1226
+ if (arg.kind === "OperatorReference" && argArity !== undefined && argArity !== expected) {
1227
+ reportOperatorArity(name, argArity);
1228
+ }
1229
+ // Deviation from SANY: OpDefNode#matchingOpArgOperand reads as many parameters as a RECURSIVE declaration gives and crashes when the definition has fewer.
1230
+ return argArity === expected && argParams.every((param) => param === 0);
1231
+ };
1232
+
902
1233
  const resolveApply = (
903
1234
  expression: Expression & { kind: "Apply" },
904
1235
  scope: LocalName | undefined,
905
1236
  unit: Unit,
906
1237
  ) => {
907
- if (isInstanceArityReported(expression, scope, unit)) return;
908
1238
  const operator = expression.operator;
909
1239
  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) {
1240
+ const arity = isInstanceArityReported(expression, scope, unit)
1241
+ ? undefined
1242
+ : getSymbolArity(expression, operator, scope, unit);
1243
+ if (arity !== undefined && arity !== expression.args.length) {
913
1244
  unit.errors.push({
914
1245
  location: formatRange(expression.argumentsRange ?? getSpelledNameRange(expression, operator)),
915
- message: `The operator ${operator} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
1246
+ message: `The operator ${resolveSynonym(operator)} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
916
1247
  });
1248
+ }
1249
+ if (arity !== expression.args.length) {
1250
+ emptyExpressions.add(expression);
917
1251
  return;
918
1252
  }
919
- const params = callee && (callee.kind === "Definition" ? callee.params : []);
1253
+ const params =
1254
+ callee && (callee.kind === "Definition" ? callee.params : expression.args.map(() => 0));
920
1255
  if (params === undefined) {
921
1256
  expression.args.forEach((arg) => resolveArgument(arg, scope, unit));
922
1257
  return;
923
1258
  }
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
- });
1259
+ const operatorRange =
1260
+ expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator);
1261
+ const isSelection = operator === SELECTION_NAME;
1262
+ const matches = expression.args.slice(0, params.length).map((arg, index) => {
1263
+ const source = isSelection ? selectionArguments.get(arg) : undefined;
1264
+ return matchArgument(
1265
+ arg,
1266
+ params[index],
1267
+ source?.index ?? index,
1268
+ source?.operator ?? operator,
1269
+ source?.range ?? operatorRange,
1270
+ scope,
1271
+ isSelection ? { ...unit, isGenerated: false } : unit,
1272
+ );
1273
+ });
1274
+ if (
1275
+ isArgumentCountReported(
1276
+ callee,
1277
+ operator,
1278
+ expression.args.length,
1279
+ expression.location.range,
1280
+ unit,
1281
+ )
1282
+ ) {
1283
+ return;
1284
+ }
1285
+ matches.forEach((isMatched, index) => {
1286
+ if (!isMatched && expression.location.range) {
1287
+ unit.errors.push({
1288
+ location: formatRange(expression.location.range),
1289
+ message: `Argument number ${index + 1} to operator '${isSelection ? "LAMBDA" : operator}' \nshould be a ${params[index]}-parameter operator.`,
1290
+ });
1291
+ }
1292
+ });
999
1293
  };
1000
1294
 
1001
1295
  const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
@@ -1006,17 +1300,56 @@ const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Un
1006
1300
  const isSelectionReported = (expression: Expression, scope: LocalName | undefined, unit: Unit) => {
1007
1301
  const failed = selectionErrors.get(expression);
1008
1302
  if (!failed) return false;
1009
- failed.args.forEach((arg) => resolveArgument(arg, scope, unit));
1010
- unit.errors.push(failed.error);
1303
+ failed.applications.forEach((application) =>
1304
+ application.args
1305
+ .slice(0, application.params.length)
1306
+ .forEach((arg, index) =>
1307
+ matchArgument(
1308
+ arg,
1309
+ application.params[index],
1310
+ index,
1311
+ application.operator,
1312
+ application.range,
1313
+ scope,
1314
+ unit,
1315
+ ),
1316
+ ),
1317
+ );
1318
+ unit.errors.push(findNullError(failed.nulls) ?? failed.error);
1011
1319
  return true;
1012
1320
  };
1013
1321
 
1322
+ const resolveLambda = (
1323
+ expression: Expression & { kind: "Lambda" },
1324
+ scope: LocalName | undefined,
1325
+ unit: Unit,
1326
+ ) =>
1327
+ resolveExpression(
1328
+ expression.body,
1329
+ bindNames(scope, expression.params, expression.paramRanges, unit),
1330
+ {
1331
+ ...unit,
1332
+ labelParams: [...unit.labelParams, ...expression.params],
1333
+ },
1334
+ );
1335
+
1014
1336
  const resolveExpression = (
1015
1337
  expression: Expression,
1016
1338
  scope: LocalName | undefined,
1017
1339
  unit: Unit,
1018
1340
  ): void => {
1019
1341
  if (selections.has(expression) && !unit.isGenerated) {
1342
+ const failed = findNullError(nullSelections.get(expression));
1343
+ if (failed) {
1344
+ unit.errors.push(failed);
1345
+ return;
1346
+ }
1347
+ const source = selectionSources.get(expression);
1348
+ if (source) {
1349
+ Object.assign(expression, source);
1350
+ const arity = renamedArities.get(source);
1351
+ if (arity !== undefined) renamedArities.set(expression, arity);
1352
+ }
1020
1353
  resolveExpression(expression, scope, { ...unit, isGenerated: true });
1021
1354
  return;
1022
1355
  }
@@ -1030,18 +1363,43 @@ const resolveExpression = (
1030
1363
  case "Number":
1031
1364
  case "Decimal":
1032
1365
  case "String":
1366
+ return;
1033
1367
  case "ExceptAt":
1368
+ if (!unit.isInExcept && expression.location.range) {
1369
+ emptyExpressions.add(expression);
1370
+ unit.errors.push({
1371
+ location: formatRange(expression.location.range),
1372
+ message: "@ used where its meaning is not defined.",
1373
+ });
1374
+ }
1034
1375
  return;
1035
1376
  case "Identifier": {
1036
- if (isInstanceArityReported(expression, scope, unit)) return;
1037
1377
  const name = expression.name;
1038
- const arity = getSymbolArity(expression, name, scope, unit);
1039
- if (arity !== undefined && arity > 0) {
1378
+ const arity = isInstanceArityReported(expression, scope, unit)
1379
+ ? undefined
1380
+ : getSymbolArity(expression, name, scope, unit);
1381
+ if (arity === 0) {
1382
+ const binding = findBinding(name, scope, unit);
1383
+ const kind = binding?.kind;
1384
+ // SANY's selector chooses no operand of a variable, theorem, step or NEW symbol, unlike of a constant or definition.
1385
+ if (
1386
+ kind === "Variable" ||
1387
+ kind === "Theorem" ||
1388
+ kind?.startsWith("New") ||
1389
+ isFact(name, unit)
1390
+ ) {
1391
+ emptyExpressions.add(expression);
1392
+ }
1393
+ isArgumentCountReported(binding, name, 0, getSpelledNameRange(expression, name), unit);
1394
+ return;
1395
+ }
1396
+ if (arity !== undefined) {
1040
1397
  unit.errors.push({
1041
1398
  location: formatRange(getSpelledNameRange(expression, name)),
1042
- message: `The operator ${name} requires ${arity} arguments.`,
1399
+ message: `The operator ${resolveSynonym(name)} requires ${arity} arguments.`,
1043
1400
  });
1044
1401
  }
1402
+ emptyExpressions.add(expression);
1045
1403
  return;
1046
1404
  }
1047
1405
  case "OperatorReference":
@@ -1051,11 +1409,14 @@ const resolveExpression = (
1051
1409
  resolveApply(expression, scope, unit);
1052
1410
  return;
1053
1411
  case "Lambda":
1054
- resolveExpression(
1055
- expression.body,
1056
- bindNames(scope, expression.params, expression.paramRanges, unit),
1057
- bindLabelParams(expression.params),
1058
- );
1412
+ if (selections.has(expression)) resolveLambda(expression, scope, unit);
1413
+ else if (expression.location.range) {
1414
+ unresolvedExpressions.add(expression);
1415
+ unit.errors.push({
1416
+ location: formatRange(expression.location.range),
1417
+ message: "LAMBDA expression used where an expression is required.",
1418
+ });
1419
+ }
1059
1420
  return;
1060
1421
  case "And":
1061
1422
  case "Or":
@@ -1078,7 +1439,13 @@ const resolveExpression = (
1078
1439
  case "Let":
1079
1440
  resolveExpression(
1080
1441
  expression.body,
1081
- resolveDefinitions(expression.definitions, scope, unit, expression.instances),
1442
+ resolveDefinitions(
1443
+ expression.definitions,
1444
+ scope,
1445
+ unit,
1446
+ expression.instances,
1447
+ expression.recursive,
1448
+ ),
1082
1449
  unit,
1083
1450
  );
1084
1451
  return;
@@ -1168,34 +1535,237 @@ const resolveExpression = (
1168
1535
  resolveExpression(expression.body, scope, { ...unit, labelParams: [], labels: new Set() });
1169
1536
  checkLabel(expression, scope, unit);
1170
1537
  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);
1538
+ case "Subexpression":
1539
+ if (isSubexpressionReported(expression, scope, unit)) emptyExpressions.add(expression);
1540
+ return;
1541
+ }
1542
+ };
1543
+
1544
+ const isPendingSelectionReported = (
1545
+ name: string,
1546
+ args: Expression[],
1547
+ selectorRange: SourceRange | undefined,
1548
+ argumentsRange: SourceRange | undefined,
1549
+ scope: LocalName | undefined,
1550
+ unit: Unit,
1551
+ ) => {
1552
+ const pending = lookupLocal(scope, name) ?? getModuleBinding(name, unit, undefined);
1553
+ if (!pending?.isPending || !selectorRange || !argumentsRange) return false;
1554
+ if (args.length !== pending.arity) {
1555
+ unit.errors.push({
1556
+ location: formatRange(argumentsRange),
1557
+ message: `The operator ${name} requires ${pending.arity} arguments.`,
1558
+ });
1559
+ return true;
1560
+ }
1561
+ args.forEach((arg) => resolveExpression(arg, scope, unit));
1562
+ unit.errors.push({
1563
+ location: formatRange(selectorRange),
1564
+ message: `Subexpression of \`${name}' used inside the operator's definition.`,
1565
+ });
1566
+ return true;
1567
+ };
1568
+
1569
+ const isSubexpressionReported = (
1570
+ expression: Expression & { kind: "Subexpression" },
1571
+ scope: LocalName | undefined,
1572
+ unit: Unit,
1573
+ ) => {
1574
+ if (
1575
+ isInstanceArityReported(expression, scope, unit) ||
1576
+ isSelectionReported(expression, scope, unit)
1577
+ ) {
1578
+ return true;
1579
+ }
1580
+ const head = expression.selectors[0];
1581
+ const range = expression.selectorRanges?.[0];
1582
+ const nameCount = expression.selectors.findIndex((selector) => selector.kind !== "Name");
1583
+ const names = expression.selectors
1584
+ .slice(0, nameCount)
1585
+ .flatMap((selector) => (selector.kind === "Name" ? [selector.name] : []));
1586
+ const symbolIndex = names.findIndex(
1587
+ (_name, index) => index > 0 && findSymbol(names.slice(0, index + 1).join("!"), unit),
1588
+ );
1589
+ const isInstance =
1590
+ names.length > 1 &&
1591
+ (lookupLocal(scope, names[0]) ?? getModuleBinding(names[0], unit, undefined))?.kind ===
1592
+ "Instance";
1593
+ const lastRange = expression.selectorRanges?.[nameCount - 1];
1594
+ if (isInstance && symbolIndex === -1 && range && lastRange) {
1595
+ unit.errors.push({
1596
+ location: formatRange({ module: range.module, start: range.start, end: lastRange.end }),
1597
+ message: `Unknown operator: \`${resolveSynonym(names.join("!"))}'.`,
1598
+ });
1599
+ return true;
1600
+ }
1601
+ const name = names.slice(0, symbolIndex + 1).join("!");
1602
+ const symbol = symbolIndex > 0 ? findSymbol(name, unit) : undefined;
1603
+ const argumentCount = expression.selectors
1604
+ .slice(0, symbolIndex + 1)
1605
+ .flatMap((selector) => ("args" in selector ? selector.args : [])).length;
1606
+ const argumentRange = expression.argumentRanges?.[symbolIndex] ?? expression.location.range;
1607
+ if (symbol && symbol.arity !== argumentCount && argumentRange) {
1608
+ unit.errors.push({
1609
+ location: formatRange(argumentRange),
1610
+ message: `The operator ${resolveSynonym(name)} requires ${symbol.arity} arguments.`,
1611
+ });
1612
+ return true;
1613
+ }
1614
+ if (head.kind === "Name" && expression.selectors[1].kind !== "Name" && range) {
1615
+ const local = lookupLocal(scope, head.name);
1616
+ const binding = local ?? findSymbol(head.name, unit);
1617
+ if ((binding === undefined && !isFact(head.name, unit)) || binding?.kind === "Instance") {
1618
+ unit.errors.push({
1619
+ location: formatRange(range),
1620
+ message: `Unknown operator: \`${resolveSynonym(head.name)}'.`,
1621
+ });
1622
+ return true;
1623
+ }
1624
+ if (binding && (!SELECTABLE_KINDS.has(binding.kind) || local?.isNonFact)) {
1625
+ reportUnselectable(head.name, range, unit);
1626
+ return true;
1177
1627
  }
1178
1628
  }
1629
+ if (
1630
+ head.kind === "Name" &&
1631
+ isPendingSelectionReported(
1632
+ head.name,
1633
+ head.args,
1634
+ range,
1635
+ expression.argumentRanges?.[0] ?? expression.location.range,
1636
+ scope,
1637
+ unit,
1638
+ )
1639
+ ) {
1640
+ return true;
1641
+ }
1642
+ expression.selectors
1643
+ .flatMap((selector) => ("args" in selector ? selector.args : []))
1644
+ .forEach((arg) => resolveArgument(arg, scope, unit));
1645
+ const selected = checkReference(expression, scope, unit, false);
1646
+ return selected ? selected.node === undefined : false;
1179
1647
  };
1180
1648
 
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;
1649
+ const checkFact = (fact: Fact, reference: Fact, scope: LocalName | undefined, unit: Unit) => {
1650
+ if (fact.kind === "ModuleFact") return undefined;
1651
+ if (fact.kind === "ExceptAt" && fact.location.range) {
1652
+ unit.errors.push({
1653
+ location: formatRange(fact.location.range),
1654
+ message: "Unknown operator: `@'.",
1655
+ });
1656
+ return BUILTIN_LOCATION;
1657
+ }
1658
+ const hidden = getHiddenExpressionLocation(fact, reference, scope, unit);
1659
+ if (isInstanceArityReported(fact, scope, unit)) return hidden;
1660
+ const selected = checkReference(fact, scope, unit, true);
1661
+ if (selected) {
1662
+ const kind = selected.node?.kind;
1663
+ if (kind === undefined) return BUILTIN_LOCATION;
1664
+ return kind === "AssumeProve" || kind === "NewSymbol"
1665
+ ? undefined
1666
+ : fact.location.range && formatRange(fact.location.range);
1667
+ }
1668
+ if (fact.kind === "Subexpression") {
1669
+ return isSubexpressionReported(fact, scope, unit) ? BUILTIN_LOCATION : hidden;
1670
+ }
1671
+ const name = fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1672
+ if (fact.kind === "Identifier" && lookupLocal(scope, name)?.isNonFact) {
1673
+ unit.errors.push({
1674
+ location: formatRange(getSpelledNameRange(fact, name)),
1675
+ message: "Step number of non-fact used as a fact",
1676
+ });
1677
+ return BUILTIN_LOCATION;
1678
+ }
1679
+ if (!isFact(name, unit) && !lookupLocal(scope, name)?.goal) resolveExpression(fact, scope, unit);
1680
+ return hidden;
1681
+ };
1682
+
1683
+ const isDefinitionEntry = (def: Fact, scope: LocalName | undefined, unit: Unit) => {
1684
+ const range = def.location.range;
1685
+ const name =
1686
+ def.kind === "Identifier" ? def.name : def.kind === "OperatorReference" ? def.operator : "";
1687
+ if (name === "" || !range) return true;
1688
+ const binding =
1689
+ lookupLocal(scope, name) ?? findSymbol(name, unit) ?? getModuleBinding(name, unit, range);
1690
+ if (binding === undefined && (isFact(name, unit) || isStepName(name))) return true;
1691
+ if (binding === undefined) {
1692
+ unit.errors.push({
1693
+ location: formatRange(range),
1694
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
1695
+ });
1696
+ }
1697
+ if (binding && SELECTABLE_KINDS.has(binding.kind) && !isStepName(name)) return true;
1698
+ unit.errors.push({
1699
+ location: formatRange(range),
1700
+ message: "DEF clause entry should describe a defined operator.",
1701
+ });
1702
+ return false;
1703
+ };
1704
+
1705
+ const getHiddenExpressionLocation = (
1706
+ fact: Expression,
1707
+ reference: Fact,
1708
+ scope: LocalName | undefined,
1709
+ unit: Unit,
1710
+ ) => {
1711
+ const range = fact.location.range && formatRange(fact.location.range);
1712
+ if (selections.has(fact)) {
1713
+ return reference.location.range && formatRange(reference.location.range);
1714
+ }
1715
+ if (selectionErrors.has(fact) || fact.kind === "ExceptAt") return BUILTIN_LOCATION;
1716
+ switch (fact.kind) {
1717
+ case "Number":
1718
+ case "String":
1719
+ case "Decimal":
1720
+ case "Let":
1721
+ case "Label":
1722
+ return undefined;
1723
+ case "Identifier":
1724
+ case "Apply":
1725
+ case "Subexpression": {
1726
+ const first = getSelectors(fact)[0];
1727
+ if (fact.kind === "Subexpression" || first.kind !== "Name") return undefined;
1728
+ const name = fact.kind === "Identifier" ? fact.name : fact.operator;
1729
+ const goal = lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit);
1730
+ if (isFact(name, unit) || goal || (isStepName(name) && lookupLocal(scope, name))) {
1731
+ return undefined;
1732
+ }
1733
+ const binding = findBinding(name, scope, unit);
1734
+ const count = fact.kind === "Apply" ? fact.args.length : 0;
1735
+ return binding?.arity === count ? range : BUILTIN_LOCATION;
1189
1736
  }
1190
- const name =
1191
- fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1192
- if (fact.kind === "Identifier" && lookupLocal(scope, name)?.isNonFact) {
1737
+ default:
1738
+ return range;
1739
+ }
1740
+ };
1741
+
1742
+ const checkUseOrHide = (
1743
+ statement: UseOrHide | Extract<Proof, { kind: "By" }>,
1744
+ scope: LocalName | undefined,
1745
+ unit: Unit,
1746
+ ) => {
1747
+ const references = factReferences.get(statement.facts) ?? statement.facts;
1748
+ const hidden = statement.facts.map((fact, index) =>
1749
+ checkFact(fact, references[index], scope, unit),
1750
+ );
1751
+ const defCount = statement.defs.filter((def) => isDefinitionEntry(def, scope, unit)).length;
1752
+ hidden.forEach((location) => {
1753
+ if (location && statement.kind === "Hide") {
1193
1754
  unit.errors.push({
1194
- location: formatRange(getSpelledNameRange(fact, name)),
1195
- message: "Step number of non-fact used as a fact",
1755
+ location,
1756
+ message:
1757
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1196
1758
  });
1197
- } else if (!unit.facts.has(name)) resolveExpression(fact, scope, unit);
1759
+ }
1198
1760
  });
1761
+ const range = statement.location.range;
1762
+ if (statement.facts.length + defCount === 0 && range) {
1763
+ unit.errors.push({
1764
+ location: formatRange(range),
1765
+ message: statement.kind === "By" ? "Empty BY" : "Empty USE or HIDE statement.",
1766
+ });
1767
+ }
1768
+ };
1199
1769
 
1200
1770
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
1201
1771
  if (symbol.set) resolveExpression(symbol.set, scope, unit);
@@ -1244,7 +1814,7 @@ const resolveStatement = (
1244
1814
 
1245
1815
  const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, outer: Unit) => {
1246
1816
  const unit = outer.hasLabelScope ? { ...outer, hasLabelScope: false } : outer;
1247
- if (proof?.kind === "By") checkFacts(proof.facts, scope, unit);
1817
+ if (proof?.kind === "By") checkUseOrHide(proof, scope, unit);
1248
1818
  if (proof?.kind !== "Steps") return;
1249
1819
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
1250
1820
  };
@@ -1261,6 +1831,42 @@ const resolveLocalInstance = (instance: Instance, scope: LocalName | undefined,
1261
1831
  );
1262
1832
  };
1263
1833
 
1834
+ const getStepGoal = (body: StepBody, location: SourceLocation): Goal | undefined => {
1835
+ const createGoal = (keyword: string, statement: Expression) => ({
1836
+ statement,
1837
+ isSuffices: false,
1838
+ isInProof: false,
1839
+ keyword,
1840
+ });
1841
+ switch (body.kind) {
1842
+ case "Have":
1843
+ return createGoal("HAVE", { kind: "Tuple", elements: [body.expression], location });
1844
+ case "Case":
1845
+ return createGoal("CASE", { kind: "Tuple", elements: [body.expression], location });
1846
+ case "Witness":
1847
+ return createGoal("WITNESS", { kind: "Tuple", elements: body.expressions, location });
1848
+ case "Take":
1849
+ return createGoal("TAKE", { kind: "Tuple", elements: getBoundSets(body.bounds), location });
1850
+ case "Pick":
1851
+ return createGoal(
1852
+ "PICK",
1853
+ body.bounds.length > 0
1854
+ ? { kind: "Exists", bounds: body.bounds, body: body.body, location }
1855
+ : {
1856
+ kind: "UnboundedQuantifier",
1857
+ quantifier: "Exists",
1858
+ names: body.names,
1859
+ body: body.body,
1860
+ location,
1861
+ },
1862
+ );
1863
+ case "Qed":
1864
+ return createGoal("QED step", { kind: "Tuple", elements: [], location });
1865
+ default:
1866
+ return undefined;
1867
+ }
1868
+ };
1869
+
1264
1870
  const resolveStep = (
1265
1871
  step: ProofStep,
1266
1872
  scope: LocalName | undefined,
@@ -1271,8 +1877,9 @@ const resolveStep = (
1271
1877
  step.name === undefined
1272
1878
  ? unit
1273
1879
  : { ...unit, hasLabelScope: true, labelParams: [], labels: new Set<string>() };
1880
+ const goal = getStepGoal(body, step.location);
1274
1881
  const bindStep = (parent: LocalName | undefined): LocalName | undefined =>
1275
- step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent };
1882
+ step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent, goal };
1276
1883
  const bindNonFactStep = (parent: LocalName | undefined): LocalName | undefined =>
1277
1884
  step.name === undefined
1278
1885
  ? parent
@@ -1286,14 +1893,29 @@ const resolveStep = (
1286
1893
  resolveProof(step.proof, proofScope, unit);
1287
1894
  return body.isSuffices ? assumed : scope;
1288
1895
  }
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 };
1896
+ const assertion = {
1897
+ statement: body.statement,
1898
+ isSuffices: body.isSuffices,
1899
+ isInProof: true,
1900
+ keyword: body.isSuffices && body.statement.kind !== "AssumeProve" ? "SUFFICES" : undefined,
1901
+ };
1902
+ resolveProof(
1903
+ step.proof,
1904
+ { name, arity: 0, kind: "Theorem", parent: proofScope, goal: assertion },
1905
+ unit,
1906
+ );
1907
+ assertion.isInProof = false;
1908
+ return {
1909
+ name,
1910
+ arity: 0,
1911
+ kind: "Theorem",
1912
+ parent: body.isSuffices ? assumed : scope,
1913
+ goal: assertion,
1914
+ };
1293
1915
  }
1294
1916
  case "Use":
1295
1917
  case "Hide":
1296
- checkFacts(body.facts, scope, unit);
1918
+ checkUseOrHide(body, scope, unit);
1297
1919
  return bindNonFactStep(scope);
1298
1920
  case "Instance":
1299
1921
  return bindNonFactStep(resolveLocalInstance(body, scope, stepUnit));
@@ -1416,18 +2038,72 @@ const checkSubstitutions = (
1416
2038
  (parent, param) => ({ name: param.name, arity: param.arity, kind: "Parameter", parent }),
1417
2039
  outer,
1418
2040
  );
2041
+ const reportArity = (declaration: Declaration, location: string) =>
2042
+ unit.errors.push({
2043
+ location,
2044
+ message: `An operator must be substituted for symbol '${resolveSynonym(declaration.name)}', and it must have arity ${declaration.arity}.`,
2045
+ });
1419
2046
  const resolveSubstitute = (declaration: Declaration, expression: Expression) => {
1420
- if (declaration.arity === 0 || expression.kind !== "Identifier") {
1421
- resolveExpression(expression, scope, unit);
2047
+ const range = expression.location.range;
2048
+ if (declaration.arity === 0) {
2049
+ resolveExpressionArgument(expression, scope, unit);
2050
+ return;
2051
+ }
2052
+ if (expression.kind === "Lambda") {
2053
+ resolveLambda(expression, scope, unit);
2054
+ if (expression.params.length !== declaration.arity && range) {
2055
+ reportArity(declaration, formatRange(range));
2056
+ }
2057
+ return;
2058
+ }
2059
+ if (expression.kind === "OperatorReference") {
2060
+ const arity = getSymbolArity(expression, expression.operator, scope, unit);
2061
+ if (arity === undefined) reportArity(declaration, BUILTIN_LOCATION);
2062
+ else if (arity !== declaration.arity && range) reportArity(declaration, formatRange(range));
2063
+ return;
2064
+ }
2065
+ if (expression.kind !== "Identifier") {
2066
+ if (range) {
2067
+ unit.errors.push({
2068
+ location: formatRange(range),
2069
+ message: `Arity ${declaration.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${resolveSynonym(declaration.name)}'.`,
2070
+ });
2071
+ }
2072
+ reportArity(declaration, BUILTIN_LOCATION);
1422
2073
  return;
1423
2074
  }
1424
2075
  const arity = getSymbolArity(expression, expression.name, scope, unit);
1425
2076
  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
- );
2077
+ unit.errors.push({
2078
+ location: formatRange(getSpelledNameRange(expression, expression.name)),
2079
+ message: `Expected arity ${declaration.arity} but found operator of arity ${arity}.`,
2080
+ });
1429
2081
  }
2082
+ if (arity !== declaration.arity) reportArity(declaration, BUILTIN_LOCATION);
1430
2083
  };
2084
+ const instanceRange = instance.location.range;
2085
+ const isFound = (declaration: Declaration) =>
2086
+ lookupLocal(scope, declaration.name) !== undefined ||
2087
+ findSymbol(declaration.name, unit) !== undefined;
2088
+ const implicit = declarations.filter(isFound).map((declaration) => {
2089
+ const expression: Expression & { kind: "Identifier" } = {
2090
+ kind: "Identifier",
2091
+ name: declaration.name,
2092
+ location: instance.location,
2093
+ };
2094
+ return { declaration, expression };
2095
+ });
2096
+ implicit
2097
+ .filter((item) => item.declaration.arity === 0)
2098
+ .forEach((item) => {
2099
+ const arity = getSymbolArity(item.expression, item.declaration.name, scope, unit);
2100
+ if (arity && instanceRange) {
2101
+ unit.errors.push({
2102
+ location: formatRange(instanceRange),
2103
+ message: `Wrong number of arguments (0) given to operator '${resolveSynonym(item.declaration.name)}', \nwhich requires ${arity} arguments.`,
2104
+ });
2105
+ }
2106
+ });
1431
2107
  const substitutions = new Map<string, Expression>();
1432
2108
  instance.substitutions.forEach((substitution) => {
1433
2109
  const name = substitution.name;
@@ -1450,30 +2126,29 @@ const checkSubstitutions = (
1450
2126
  });
1451
2127
  }
1452
2128
  });
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
2129
  implicit
1457
- .filter((declaration) => !isMissing(declaration))
2130
+ .filter((item) => !substitutions.has(item.declaration.name))
2131
+ .forEach((item) => {
2132
+ const arity =
2133
+ item.declaration.arity === 0
2134
+ ? 0
2135
+ : getSymbolArity(item.expression, item.declaration.name, scope, unit);
2136
+ if (arity !== item.declaration.arity && instanceRange) {
2137
+ reportArity(item.declaration, formatRange(instanceRange));
2138
+ }
2139
+ substitutions.set(item.declaration.name, item.expression);
2140
+ });
2141
+ declarations
2142
+ .filter((declaration) => !substitutions.has(declaration.name))
1458
2143
  .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);
2144
+ const declared = declaration.location.range;
2145
+ if (instanceRange && declared) {
2146
+ unit.errors.push({
2147
+ location: formatRange(instanceRange),
2148
+ message: `Substitution missing for symbol ${resolveSynonym(declaration.name)} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
2149
+ });
2150
+ }
1466
2151
  });
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
2152
  return substitutions;
1478
2153
  };
1479
2154
 
@@ -1481,7 +2156,7 @@ const resolveInstance = (instance: Instance, scope: LocalName | undefined, unit:
1481
2156
  const instanced = unit.getInstance(instance);
1482
2157
  checkSubstitutions(instance, instanced.declarations, instanced.instancer, scope, unit);
1483
2158
  return [...instanced.symbols].reduce(
1484
- (parent, [name, symbol]) => bindName(parent, name, symbol, unit),
2159
+ (parent, entry) => bindName(parent, entry[0], entry[1], unit),
1485
2160
  scope,
1486
2161
  );
1487
2162
  };
@@ -1493,6 +2168,12 @@ export const resolveSubstitutions = (
1493
2168
  unit: ModuleUnit,
1494
2169
  ) => {
1495
2170
  const imported = createSymbols(module, unit.imported);
2171
+ const positions = new Map(
2172
+ [...module.constants, ...module.variables].map((declaration) => [
2173
+ declaration.name,
2174
+ declaration.location,
2175
+ ]),
2176
+ );
1496
2177
  const report: ModuleReport = { location: instance.location, errors: [], warnings: [] };
1497
2178
  unit.reports.push(report);
1498
2179
  return checkSubstitutions(instance, declarations, module.name, undefined, {
@@ -1505,7 +2186,10 @@ export const resolveSubstitutions = (
1505
2186
  facts: new Set(),
1506
2187
  goals: new Map(),
1507
2188
  bindings: new Map(
1508
- [...imported].map(([name, symbol]) => [name, { ...symbol, position: MODULE_START }]),
2189
+ [...imported].map((entry) => [
2190
+ entry[0],
2191
+ { ...entry[1], position: positions.get(entry[0]) ?? MODULE_START },
2192
+ ]),
1509
2193
  ),
1510
2194
  errors: report.errors,
1511
2195
  warnings: report.warnings,
@@ -1535,13 +2219,7 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1535
2219
  }
1536
2220
  };
1537
2221
  units
1538
- .toSorted((left, right) =>
1539
- isBefore(left.location, right.location)
1540
- ? -1
1541
- : isBefore(right.location, left.location)
1542
- ? 1
1543
- : 0,
1544
- )
2222
+ .toSorted((left, right) => compareLocations(left.location, right.location))
1545
2223
  .forEach((unit) => {
1546
2224
  const reported: SanyError[] = [];
1547
2225
  const warned: SanyError[] = [];
@@ -1561,21 +2239,27 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1561
2239
 
1562
2240
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
1563
2241
  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
2242
  const goals = new Map(
1569
2243
  module.theorems.flatMap((theorem): [string, Goal][] =>
1570
2244
  theorem.name !== undefined && theorem.statement.kind === "AssumeProve"
1571
- ? [[theorem.name, { statement: theorem.statement, isSuffices: false, isInProof: false }]]
2245
+ ? [
2246
+ [
2247
+ theorem.name,
2248
+ {
2249
+ statement: theorem.statement,
2250
+ isSuffices: false,
2251
+ isInProof: false,
2252
+ keyword: undefined,
2253
+ },
2254
+ ],
2255
+ ]
1572
2256
  : [],
1573
2257
  ),
1574
2258
  );
1575
2259
  const bindings = new Map<string, ModuleBinding>(
1576
- [...CORE_SYMBOLS, ...unit.bound].map(([name, symbol]) => [
1577
- name,
1578
- { ...symbol, position: MODULE_START },
2260
+ [...CORE_SYMBOLS, ...unit.bound].map((entry) => [
2261
+ entry[0],
2262
+ { ...entry[1], position: MODULE_START },
1579
2263
  ]),
1580
2264
  );
1581
2265
  const recursive = new Set<Binding>();
@@ -1595,7 +2279,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1595
2279
  getKey: unit.getKey,
1596
2280
  location,
1597
2281
  self,
1598
- facts,
2282
+ facts: unit.facts,
1599
2283
  goals,
1600
2284
  bindings,
1601
2285
  errors,
@@ -1620,6 +2304,37 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1620
2304
  );
1621
2305
  return collectSemanticErrors(
1622
2306
  [
2307
+ ...module.units.flatMap((item): SemanticUnit[] => {
2308
+ const section =
2309
+ item.kind === "Variables"
2310
+ ? { type: "A VARIABLE declaration", location: item.location }
2311
+ : item.kind === "Constants"
2312
+ ? { type: "A declaration", location: item.location }
2313
+ : item.kind === "Module"
2314
+ ? { type: "A MODULE ", location: item.module.location }
2315
+ : item.kind === "Theorem"
2316
+ ? { type: "A THEOREM", location: item.theorem.location }
2317
+ : item.kind === "Assumption"
2318
+ ? { type: "An ASSUME", location: item.assumption.location }
2319
+ : item.kind === "Use"
2320
+ ? { type: "A USE or HIDE", location: item.use.location }
2321
+ : undefined;
2322
+ const range = section?.location.range;
2323
+ if (!section || !range) return [];
2324
+ return [
2325
+ {
2326
+ location: section.location,
2327
+ check: (errors) => {
2328
+ if (declarations.some((declared) => declared.binding?.isPending)) {
2329
+ errors.push({
2330
+ location: formatRange(range),
2331
+ message: `${section.type} may not appear within a recursive definition section.`,
2332
+ });
2333
+ }
2334
+ },
2335
+ },
2336
+ ];
2337
+ }),
1623
2338
  ...unit.reports.map((report) => ({
1624
2339
  location: report.location,
1625
2340
  check: (errors: SanyError[], warnings: SanyError[]) => {
@@ -1636,6 +2351,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1636
2351
  const binding: ModuleBinding = {
1637
2352
  kind: "Definition",
1638
2353
  arity: declaration.arity,
2354
+ params: Array(declaration.arity).fill(0),
1639
2355
  range: declaration.location.range,
1640
2356
  position: declaration.location,
1641
2357
  isPending: true,
@@ -1701,7 +2417,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1701
2417
  ),
1702
2418
  ...module.uses.map((use) =>
1703
2419
  createCheck(use.location, undefined, false, (inner) =>
1704
- checkFacts(use.facts, undefined, inner),
2420
+ checkUseOrHide(use, undefined, inner),
1705
2421
  ),
1706
2422
  ),
1707
2423
  {
@@ -1712,7 +2428,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1712
2428
  if (range && (!item.binding || item.binding.isPending)) {
1713
2429
  errors.push({
1714
2430
  location: formatRange(range),
1715
- message: `Symbol ${item.declaration.name} declared in RECURSIVE statement but not defined.`,
2431
+ message: `Symbol ${resolveSynonym(item.declaration.name)} declared in RECURSIVE statement but not defined.`,
1716
2432
  });
1717
2433
  }
1718
2434
  }),