tla-ts 0.0.10-dev.09e53c2a6 → 0.0.10-dev.11307be75

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 (214) 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 +2 -1
  7. package/dist/index.d.ts +2 -1
  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 +43 -43
  14. package/dist/prove.js +78 -78
  15. package/dist/run.cjs +33 -35
  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 +38 -38
  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 +46 -28
  26. package/src/check-trace.ts +2 -16
  27. package/src/check.ts +152 -64
  28. package/src/cli/runtime-invariants.ts +20 -56
  29. package/src/cli/tlc-arguments.ts +2 -2
  30. package/src/cli/tlc-output.ts +1 -2
  31. package/src/cli/tlc.ts +13 -8
  32. package/src/cli/xml-exporter.ts +1 -1
  33. package/src/codegen.ts +9 -5
  34. package/src/dependencies.ts +49 -9
  35. package/src/dfid.ts +9 -2
  36. package/src/environment.ts +57 -33
  37. package/src/errors.ts +7 -0
  38. package/src/evaluate.ts +92 -32
  39. package/src/exit-codes.ts +4 -2
  40. package/src/instances.ts +5 -5
  41. package/src/java-overrides.ts +2 -2
  42. package/src/levels.ts +138 -90
  43. package/src/liveness-checker.ts +43 -4
  44. package/src/liveness.ts +1 -1
  45. package/src/obligations/index.ts +1 -1
  46. package/src/obligations/normalize.ts +1 -4
  47. package/src/obligations/printer.ts +5 -5
  48. package/src/parallel-worker.ts +8 -2
  49. package/src/parallel.ts +5 -0
  50. package/src/parser.ts +106 -144
  51. package/src/prover/isabelle/isar/attrib.ts +4 -4
  52. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  53. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  54. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  55. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  56. package/src/prover/isabelle/pure/term.ts +3 -3
  57. package/src/prover/prep/md5.ts +26 -29
  58. package/src/prover/smt/rewrite.ts +2 -7
  59. package/src/prover/smt/simplify.ts +1 -1
  60. package/src/prover/smt/solver/asserted-formulas.ts +66 -1
  61. package/src/prover/smt/solver/ast-lt.ts +1 -1
  62. package/src/prover/smt/solver/ast.ts +58 -11
  63. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  64. package/src/prover/smt/solver/bound-simplifier.ts +2 -3
  65. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  66. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  67. package/src/prover/smt/solver/card2bv.ts +3 -5
  68. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +2 -3
  69. package/src/prover/smt/solver/context.ts +24 -3
  70. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  71. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  72. package/src/prover/smt/solver/dependent-expr-state.ts +9 -4
  73. package/src/prover/smt/solver/diff-neq.ts +1 -2
  74. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  75. package/src/prover/smt/solver/elim-uncnstr.ts +4 -7
  76. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  77. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  78. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  79. package/src/prover/smt/solver/euf/egraph.ts +4 -10
  80. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  81. package/src/prover/smt/solver/euf/mam.ts +1 -5
  82. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  83. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  84. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  85. package/src/prover/smt/solver/factor.ts +36 -14
  86. package/src/prover/smt/solver/fd-solver.ts +2 -0
  87. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  88. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  89. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  90. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  91. package/src/prover/smt/solver/goal.ts +6 -3
  92. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  93. package/src/prover/smt/solver/hashtable.ts +4 -0
  94. package/src/prover/smt/solver/logic-tactics.ts +9 -2
  95. package/src/prover/smt/solver/lp/containers.ts +7 -1
  96. package/src/prover/smt/solver/lp/cross-nested.ts +1 -3
  97. package/src/prover/smt/solver/lp/lp-settings.ts +1 -1
  98. package/src/prover/smt/solver/lp/nex-creator.ts +3 -2
  99. package/src/prover/smt/solver/lp/nex.ts +2 -1
  100. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  101. package/src/prover/smt/solver/lp/nla-grobner.ts +158 -80
  102. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  103. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -2
  104. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -20
  105. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -39
  106. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  107. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  108. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  109. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  110. package/src/prover/smt/solver/model-generator.ts +3 -1
  111. package/src/prover/smt/solver/mpf.ts +2 -4
  112. package/src/prover/smt/solver/mus.ts +2 -3
  113. package/src/prover/smt/solver/muz/dl-context.ts +10 -4
  114. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  115. package/src/prover/smt/solver/muz/dl-rule.ts +2 -2
  116. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  117. package/src/prover/smt/solver/muz/horn-tactic.ts +1 -1
  118. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  119. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  120. package/src/prover/smt/solver/nlqsat.ts +1 -1
  121. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  122. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  123. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  124. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  125. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  126. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  127. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  128. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  129. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  130. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  131. package/src/prover/smt/solver/nnf.ts +6 -2
  132. package/src/prover/smt/solver/opt-context.ts +9 -3
  133. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  134. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  135. package/src/prover/smt/solver/opt-solver.ts +6 -3
  136. package/src/prover/smt/solver/optsmt.ts +1 -1
  137. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  138. package/src/prover/smt/solver/poly-rewriter.ts +74 -18
  139. package/src/prover/smt/solver/probes.ts +88 -23
  140. package/src/prover/smt/solver/proto-model.ts +4 -6
  141. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  142. package/src/prover/smt/solver/qe-lite.ts +2 -2
  143. package/src/prover/smt/solver/qe.ts +3 -2
  144. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  145. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  146. package/src/prover/smt/solver/rlimit.ts +4 -0
  147. package/src/prover/smt/solver/sat/config.ts +1 -1
  148. package/src/prover/smt/solver/sat/inc-sat-solver.ts +26 -1
  149. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  150. package/src/prover/smt/solver/sat/pb-solver.ts +1 -1
  151. package/src/prover/smt/solver/sat/sat-tactic.ts +4 -3
  152. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  153. package/src/prover/smt/solver/sat/solver.ts +25 -47
  154. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  155. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  156. package/src/prover/smt/solver/seq-derive.ts +4 -7
  157. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  158. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  159. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  160. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  161. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  162. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  163. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  164. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  165. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  166. package/src/prover/smt/solver/smt-kernel.ts +9 -3
  167. package/src/prover/smt/solver/smt-setup.ts +68 -6
  168. package/src/prover/smt/solver/smtlib-parser.ts +558 -220
  169. package/src/prover/smt/solver/smtlib-script.ts +495 -153
  170. package/src/prover/smt/solver/solve-eqs.ts +13 -21
  171. package/src/prover/smt/solver/tactic.ts +219 -130
  172. package/src/prover/smt/solver/theory-bv.ts +2 -2
  173. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -1
  174. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -0
  175. package/src/prover/smt/solver/theory-lra-propagate.ts +6 -4
  176. package/src/prover/smt/solver/theory-lra.ts +0 -1
  177. package/src/prover/smt/solver/theory-pb.ts +24 -7
  178. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  179. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  180. package/src/prover/tlapm/cache.ts +8 -8
  181. package/src/prover/zenon/equality-rules.ts +24 -0
  182. package/src/prover/zenon/expr.ts +21 -0
  183. package/src/prover/zenon/index-table.ts +7 -2
  184. package/src/prover/zenon/isar-case.ts +1 -1
  185. package/src/prover/zenon/isar.ts +2 -2
  186. package/src/prover/zenon/phrase.ts +1 -1
  187. package/src/prover/zenon/rules.ts +2 -1
  188. package/src/resolve.ts +779 -225
  189. package/src/runtime.ts +3 -1
  190. package/src/sany/builtins.ts +10 -10
  191. package/src/sany/generation.ts +2 -13
  192. package/src/sany/generator-definitions.ts +3 -1
  193. package/src/sany/generator-expressions.ts +36 -30
  194. package/src/sany/generator-proofs.ts +5 -3
  195. package/src/sany/generator.ts +2 -1
  196. package/src/sany/lexer.ts +3 -3
  197. package/src/sany/modules.ts +4 -2
  198. package/src/sany/nodes.ts +1 -1
  199. package/src/sany/selectors.ts +11 -6
  200. package/src/sany/xml.ts +2 -3
  201. package/src/search.ts +51 -22
  202. package/src/spec-description.ts +2 -2
  203. package/src/subexpressions.ts +337 -102
  204. package/src/successors.ts +1 -0
  205. package/src/symmetry.ts +1 -1
  206. package/src/tlc/jar-data.ts +10 -0
  207. package/src/tlc/messages.ts +3 -3
  208. package/src/tlc/order.ts +14 -3
  209. package/src/tlc/tlc-operators.ts +3 -1
  210. package/src/tlc/tlcext-operators.ts +18 -5
  211. package/src/tlc/trace-spec.ts +5 -5
  212. package/src/typed-tier.ts +29 -23
  213. package/src/typescript/types.ts +2 -2
  214. package/src/values.ts +46 -27
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,15 @@ 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[];
89
100
  error: SanyError;
90
101
  }
91
102
 
@@ -99,8 +110,17 @@ type Reference = Expression & { kind: "Identifier" | "Apply" | "Subexpression" }
99
110
 
100
111
  export const LOCAL_RESOLUTION = { kind: "Local" } as const;
101
112
 
113
+ export interface NullSelection {
114
+ node: Expression;
115
+ error: SanyError;
116
+ }
117
+
102
118
  export const selections = new WeakSet<Expression>();
103
119
  export const selectionErrors = new WeakMap<Expression, SelectionError>();
120
+ export const operatorSelectionErrors = new WeakMap<Expression, SanyError>();
121
+ export const factReferences = new WeakMap<Fact[], Fact[]>();
122
+ export const nullSelections = new WeakMap<Expression, NullSelection[]>();
123
+ const unresolvedExpressions = new WeakSet<Expression>();
104
124
 
105
125
  const renamedArities = new WeakMap<Expression, number>();
106
126
 
@@ -111,13 +131,20 @@ const isKey = (name: string) => {
111
131
  return index > 0 && index < name.length - 1;
112
132
  };
113
133
 
114
- const CORE_SYMBOLS: Symbols = new Map(
115
- ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2, kind: "Builtin" }]),
116
- );
134
+ const CORE_SYMBOLS: Symbols = new Map([
135
+ ...["~>", "-+->", "\\cdot", "\\X"].map((name): [string, ModuleSymbol] => [
136
+ name,
137
+ { key: name, arity: 2, kind: "Builtin" },
138
+ ]),
139
+ ["'", { key: "'", arity: 1, kind: "Builtin" }],
140
+ ]);
117
141
 
118
142
  export const isBefore = (left: SourceLocation, right: SourceLocation) =>
119
143
  left.line < right.line || (left.line === right.line && left.column < right.column);
120
144
 
145
+ const compareLocations = (left: SourceLocation, right: SourceLocation) =>
146
+ isBefore(left, right) ? -1 : isBefore(right, left) ? 1 : 0;
147
+
121
148
  export const getArity = (definition: Definition) =>
122
149
  definition.kind === "Operator" ? definition.params.length : 0;
123
150
 
@@ -157,7 +184,7 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
157
184
  if (current.kind === "Builtin") {
158
185
  unit.errors.push({
159
186
  location,
160
- message: `Symbol ${name} is a built-in operator, and cannot be redefined.`,
187
+ message: `Symbol ${resolveSynonym(name)} is a built-in operator, and cannot be redefined.`,
161
188
  });
162
189
  } else if (
163
190
  added.kind === "Parameter" ||
@@ -166,12 +193,12 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
166
193
  ) {
167
194
  unit.errors.push({
168
195
  location,
169
- message: `Multiply-defined symbol '${name}': this definition or declaration conflicts \nwith the one at ${existing}.`,
196
+ message: `Multiply-defined symbol '${resolveSynonym(name)}': this definition or declaration conflicts \nwith the one at ${existing}.`,
170
197
  });
171
198
  } else {
172
199
  unit.warnings.push({
173
200
  location,
174
- message: `Multiple declarations or definitions for symbol ${name}. \nThis duplicates the one at ${existing}.`,
201
+ message: `Multiple declarations or definitions for symbol ${resolveSynonym(name)}. \nThis duplicates the one at ${existing}.`,
175
202
  });
176
203
  }
177
204
  return false;
@@ -233,23 +260,35 @@ const getVisibleDefinition = (name: string, unit: Unit) => {
233
260
  const isVisible =
234
261
  definition !== undefined &&
235
262
  (definition === unit.self
236
- ? definition.kind === "Function" || definition.isRecursive
237
- : definition.isRecursive || isBefore(definition.location, unit.location));
263
+ ? definition.isRecursive
264
+ : definition.isRecursive
265
+ ? getModuleBinding(name, unit, undefined) !== undefined
266
+ : isBefore(definition.location, unit.location));
238
267
  return isVisible ? definition : undefined;
239
268
  };
240
269
 
241
270
  const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
242
271
  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);
272
+ if (definition) {
273
+ const declared = definition.isRecursive ? unit.bindings.get(name) : undefined;
274
+ return {
275
+ key: unit.getKey(definition),
276
+ arity: declared?.arity ?? getArity(definition),
277
+ params: declared?.params ?? getParamArities(definition),
278
+ kind: "Definition",
279
+ };
280
+ }
281
+ const binding = getModuleBinding(name, unit, undefined);
282
+ if (binding?.isPending) return { key: name, arity: binding.arity, kind: binding.kind };
283
+ return binding ? unit.imported.get(name) : undefined;
251
284
  };
252
285
 
286
+ const isFact = (name: string, unit: Unit) =>
287
+ unit.facts.has(name) || unit.bindings.get(name)?.kind === "Theorem";
288
+
289
+ const getGoal = (name: string, unit: Unit) =>
290
+ unit.bindings.get(name)?.kind === "Theorem" ? unit.goals.get(name) : undefined;
291
+
253
292
  const findBinding = (name: string, scope: LocalName | undefined, unit: Unit): Binding | undefined =>
254
293
  lookupLocal(scope, name) ?? findSymbol(name, unit);
255
294
 
@@ -271,12 +310,22 @@ const getSpelledNameRange = (
271
310
  };
272
311
 
273
312
  const getFixity = (expression: Expression) => {
274
- if (expression.kind !== "Apply") return undefined;
313
+ if (expression.kind !== "Apply" || expression.argumentsRange) return undefined;
275
314
  if (expression.args.length === 2) return "infix";
276
315
  if (expression.args.length !== 1) return undefined;
277
316
  return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
278
317
  };
279
318
 
319
+ const BUILTIN_LOCATION = "In module --TLA+ BUILTINS--";
320
+
321
+ const SELECTABLE_KINDS = new Set<SymbolKind>(["Definition", "Instance", "Theorem"]);
322
+
323
+ const reportUnselectable = (name: string, range: SourceRange, unit: Unit) =>
324
+ unit.errors.push({
325
+ location: formatRange(range),
326
+ message: `Cannot take subexpression of \`${resolveSynonym(name)}'.`,
327
+ });
328
+
280
329
  const isOperatorSymbol = (name: string) => !/^[\p{L}\d_]/u.test(name);
281
330
 
282
331
  const isStepName = (name: string) =>
@@ -462,6 +511,7 @@ const checkSelection = (
462
511
  (index === undefined ? undefined : reference.selectorRanges?.[index]) ??
463
512
  reference.location.range;
464
513
  if (range) unit.errors.push({ location: formatRange(range), message });
514
+ return undefined;
465
515
  };
466
516
  const isOutOfScope = goal.isSuffices === goal.isInProof;
467
517
  const statement = goal.statement;
@@ -479,9 +529,7 @@ const checkSelection = (
479
529
  node.kind !== "NewSymbol" &&
480
530
  node.kind !== "AssumeProve" &&
481
531
  getLabelBody(node).kind === "Let";
482
- return isLet
483
- ? undefined
484
- : report(index - 1, "A name selector here must be from a LET clause.");
532
+ return isLet ? node : report(index - 1, "A name selector here must be from a LET clause.");
485
533
  }
486
534
  const clauses =
487
535
  statement.kind === "AssumeProve"
@@ -519,10 +567,17 @@ const checkSelection = (
519
567
  state.isSufficesOpen = false;
520
568
  continue;
521
569
  }
522
- if (selector.kind !== "Operand") return;
523
- const operand = getOperandName(selector.operand);
570
+ if (selector.kind === "Colon") return node;
571
+ const operand =
572
+ selector.kind === "Operand"
573
+ ? getOperandName(selector.operand)
574
+ : selector.kind === "At"
575
+ ? "@"
576
+ : "!(...)";
577
+ const getPosition = (count: number) =>
578
+ selector.kind === "Operand" ? getOperandIndex(selector.operand, count) : -1;
524
579
  if (state.isSufficesOpen) {
525
- if (getOperandIndex(selector.operand, 1) !== 0) {
580
+ if (getPosition(1) !== 0) {
526
581
  return report(
527
582
  index,
528
583
  node.kind === "AssumeProve"
@@ -533,7 +588,7 @@ const checkSelection = (
533
588
  state.isSufficesOpen = false;
534
589
  continue;
535
590
  }
536
- if (node.kind === "NewSymbol") return;
591
+ if (node.kind === "NewSymbol") return node;
537
592
  if (node.kind !== "AssumeProve") {
538
593
  const expression = getLabelBody(node);
539
594
  if (["Number", "Decimal", "String"].includes(expression.kind)) {
@@ -547,6 +602,7 @@ const checkSelection = (
547
602
  return report(index, `Choosing operand \`${operand}' of subexpression with no operands.`);
548
603
  }
549
604
  const sets = getBinder(expression)?.sets;
605
+ if (sets && selector.kind !== "Operand") return node;
550
606
  const operands =
551
607
  expression.kind === "Identifier"
552
608
  ? []
@@ -557,15 +613,15 @@ const checkSelection = (
557
613
  : expression.kind === "Except"
558
614
  ? undefined
559
615
  : getOperands(expression);
560
- if (!operands) return;
561
- const position = getOperandIndex(selector.operand, operands.length);
616
+ if (!operands) return node;
617
+ const position = getPosition(operands.length);
562
618
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
563
619
  state.node = operands[position];
564
620
  state.isGoal = false;
565
621
  continue;
566
622
  }
567
623
  const clauses = [...node.assumptions, node.conclusion];
568
- const position = getOperandIndex(selector.operand, clauses.length);
624
+ const position = getPosition(clauses.length);
569
625
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
570
626
  if (isInScopeOfDeclaration(node, position) && (!state.isGoal || isOutOfScope)) {
571
627
  return report(index, `Accessing ASSUME/PROVE clause ${SCOPE_MESSAGE}`);
@@ -577,13 +633,14 @@ const checkSelection = (
577
633
  state.node = clause;
578
634
  state.isGoal = false;
579
635
  }
580
- if (isFact) return;
636
+ if (isFact) return state.node;
581
637
  if (state.node.kind === "AssumeProve") {
582
- report(undefined, "Selected ASSUME/PROVE instead of expression.");
638
+ return report(undefined, "Selected ASSUME/PROVE instead of expression.");
583
639
  }
584
640
  if (state.node.kind === "NewSymbol") {
585
- report(undefined, "Selected a NEW declaration as an expression or operator.");
641
+ return report(undefined, "Selected a NEW declaration as an expression or operator.");
586
642
  }
643
+ return state.node;
587
644
  };
588
645
 
589
646
  const isLabelReported = (label: LabelExpression, unit: Unit) => {
@@ -659,10 +716,9 @@ const checkReference = (
659
716
  const first = selectors[0];
660
717
  const goal =
661
718
  selectors.length > 1 && first.kind === "Name"
662
- ? (lookupLocal(scope, first.name)?.goal ?? unit.goals.get(first.name))
719
+ ? (lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit))
663
720
  : undefined;
664
- if (goal) checkSelection(expression, selectors, goal, scope, unit, isFact);
665
- return goal !== undefined;
721
+ return goal && { node: checkSelection(expression, selectors, goal, scope, unit, isFact) };
666
722
  };
667
723
 
668
724
  const getSymbolArity = (
@@ -684,6 +740,14 @@ const getSymbolArity = (
684
740
  });
685
741
  return undefined;
686
742
  }
743
+ const keyword = local?.goal?.keyword;
744
+ if (keyword) {
745
+ unit.errors.push({
746
+ location: formatRange(getSpelledNameRange(expression, name)),
747
+ message: `${keyword} proof step selected instead of expression.`,
748
+ });
749
+ return undefined;
750
+ }
687
751
  if (checkReference(expression, scope, unit, false) || (isStepName(name) && local)) {
688
752
  return expression.kind === "Apply" ? expression.args.length : 0;
689
753
  }
@@ -697,29 +761,39 @@ const getSymbolArity = (
697
761
  return symbol.arity;
698
762
  }
699
763
  const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
700
- const isSelected =
701
- prefix !== "" &&
702
- (lookupLocal(scope, prefix) !== undefined ||
703
- findSymbol(prefix, unit) !== undefined ||
704
- unit.facts.has(prefix));
705
- if (isSelected) {
764
+ const selected =
765
+ prefix === "" ? undefined : (lookupLocal(scope, prefix) ?? findSymbol(prefix, unit));
766
+ if (selected && !SELECTABLE_KINDS.has(selected.kind)) {
767
+ reportUnselectable(
768
+ prefix,
769
+ (expression.kind !== "OperatorReference" && expression.selectorRanges?.[0]) ||
770
+ getSpelledNameRange(expression, name),
771
+ unit,
772
+ );
773
+ return undefined;
774
+ }
775
+ if (selected || (prefix !== "" && isFact(prefix, unit))) {
706
776
  return expression.kind === "Apply" ? expression.args.length : 0;
707
777
  }
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}'.` });
778
+ const fixity = getFixity(expression);
779
+ const isOperatorApplication = expression.kind === "OperatorReference" || fixity !== undefined;
780
+ if (!isOperatorSymbol(name) || isStepName(name) || !isOperatorApplication) {
781
+ unit.errors.push({
782
+ location: formatRange(getSpelledNameRange(expression, name)),
783
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
784
+ });
716
785
  return undefined;
717
786
  }
787
+ const spelling = expression.spelling ?? name;
718
788
  unit.errors.push({
719
- location: range,
789
+ location: formatRange(
790
+ fixity === "prefix" && spelling === "-."
791
+ ? getNameRange(location, "-")
792
+ : getSpelledNameRange(expression, name),
793
+ ),
720
794
  message: `Could not find declaration or definition of symbol '${spelling}'.`,
721
795
  });
722
- const fixity = getFixity(expression);
796
+ if (fixity) unresolvedExpressions.add(expression);
723
797
  if (fixity && location.range) {
724
798
  unit.errors.push({
725
799
  location: formatRange(location.range),
@@ -774,15 +848,30 @@ const resolveDefinition = (
774
848
  const isDeclared = current?.isPending === true && recursive.has(current);
775
849
  if (current?.isPending && !isDeclared) {
776
850
  report(
777
- `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${name} defined at wrong LET/IN level.`,
851
+ `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${resolveSynonym(name)} defined at wrong LET/IN level.`,
778
852
  );
779
853
  } else if (current && !isDeclared) {
780
854
  report(
781
855
  definition.kind === "Function"
782
856
  ? `Function name \`${name}' already defined or declared.`
783
- : `Operator ${name} already defined or declared.`,
857
+ : `Operator ${resolveSynonym(name)} already defined or declared.`,
858
+ );
859
+ } else if (current && definition.kind === "Function" && current.arity > 0) {
860
+ report(`Function ${resolveSynonym(name)} has operator arguments in its RECURSIVE declaration.`);
861
+ } else if (
862
+ current &&
863
+ definition.kind === "Operator" &&
864
+ // Deviation from SANY: Generator#processOperator compares only the last parameter's arity with the RECURSIVE declaration's.
865
+ (current.arity !== definition.params.length ||
866
+ definition.params.some((param) => param.arity > 0))
867
+ ) {
868
+ report(
869
+ `Definition of ${resolveSynonym(name)} has different arity than its RECURSIVE declaration.`,
784
870
  );
785
871
  }
872
+ if (current && isDeclared && definition.kind === "Operator") {
873
+ current.params = getParamArities(definition);
874
+ }
786
875
  if (definition.kind === "Function") {
787
876
  resolveExpression(
788
877
  definition.body,
@@ -793,8 +882,10 @@ const resolveDefinition = (
793
882
  definition.isSelfReferential = isReferenced(definition.body, name);
794
883
  } else resolveExpression(definition.body, inner, unit);
795
884
  if (current && isDeclared) {
796
- current.isPending = false;
797
- current.range = range;
885
+ if (definition.kind === "Operator" || current.arity === 0) {
886
+ current.isPending = false;
887
+ current.range = range;
888
+ }
798
889
  return false;
799
890
  }
800
891
  return definition.kind === "Function"
@@ -812,10 +903,15 @@ const resolveDefinitions = (
812
903
  scope: LocalName | undefined,
813
904
  unit: Unit,
814
905
  instances: Instance[] = [],
906
+ declarations: Declaration[] = [],
815
907
  ) => {
816
908
  const recursive = new Set<Binding>();
817
909
  const declared = definitions
818
- .filter((definition) => definition.isRecursive)
910
+ .filter(
911
+ (definition) =>
912
+ definition.isRecursive &&
913
+ declarations.every((declaration) => declaration.name !== definition.name),
914
+ )
819
915
  .reduce<LocalName | undefined>((parent, definition) => {
820
916
  if (lookupLocal(parent, definition.name)?.isPending) return parent;
821
917
  const local: LocalName = {
@@ -829,20 +925,47 @@ const resolveDefinitions = (
829
925
  recursive.add(local);
830
926
  return local;
831
927
  }, scope);
832
- const pending = unit.isGenerated ? [] : [...instances];
833
- const resolveInstances = (
928
+ const declaredLocals = new Map<Declaration, LocalName | undefined>();
929
+ const bindDeclaration = (parent: LocalName | undefined, declaration: Declaration) => {
930
+ const binding: Binding = {
931
+ kind: "Definition",
932
+ arity: declaration.arity,
933
+ params: Array(declaration.arity).fill(0),
934
+ range: declaration.location.range,
935
+ };
936
+ const local: LocalName | undefined = isBindable(
937
+ declaration.name,
938
+ lookupLocal(parent, declaration.name) ??
939
+ getModuleBinding(declaration.name, unit, binding.range),
940
+ binding,
941
+ unit,
942
+ )
943
+ ? { ...binding, name: declaration.name, parent, isPending: true }
944
+ : undefined;
945
+ if (local) recursive.add(local);
946
+ declaredLocals.set(declaration, local);
947
+ return local ?? parent;
948
+ };
949
+ const pending = [...(unit.isGenerated ? [] : instances), ...declarations].toSorted(
950
+ (left, right) => compareLocations(left.location, right.location),
951
+ );
952
+ const resolvePending = (
834
953
  current: LocalName | undefined,
835
- isDue: (instance: Instance) => boolean,
954
+ isDue: (item: Instance | Declaration) => boolean,
836
955
  ) => {
837
- const count = pending.findIndex((instance) => !isDue(instance));
956
+ const count = pending.findIndex((item) => !isDue(item));
838
957
  return pending
839
958
  .splice(0, count === -1 ? pending.length : count)
840
- .reduce((parent, instance) => resolveLocalInstance(instance, parent, unit), current);
959
+ .reduce(
960
+ (parent, item) =>
961
+ "kind" in item ? resolveLocalInstance(item, parent, unit) : bindDeclaration(parent, item),
962
+ current,
963
+ );
841
964
  };
842
965
  const resolved = definitions.reduce<LocalName | undefined>((previous, definition) => {
843
966
  const current = isKey(definition.name)
844
967
  ? previous
845
- : resolveInstances(previous, (instance) => !isBefore(definition.location, instance.location));
968
+ : resolvePending(previous, (item) => !isBefore(definition.location, item.location));
846
969
  const local: LocalName = {
847
970
  name: definition.name,
848
971
  arity: getArity(definition),
@@ -862,7 +985,17 @@ const resolveDefinitions = (
862
985
  ? { ...local, params: getParamArities(definition) }
863
986
  : current;
864
987
  }, declared);
865
- return resolveInstances(resolved, () => true);
988
+ const resolvedScope = resolvePending(resolved, () => true);
989
+ declaredLocals.forEach((local, declaration) => {
990
+ const range = declaration.location.range;
991
+ if (range && !unit.isGenerated && (!local || local.isPending)) {
992
+ unit.errors.push({
993
+ location: formatRange(range),
994
+ message: `Symbol ${resolveSynonym(declaration.name)} declared in RECURSIVE statement but not defined.`,
995
+ });
996
+ }
997
+ });
998
+ return resolvedScope;
866
999
  };
867
1000
 
868
1001
  const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) => {
@@ -879,16 +1012,22 @@ const isInstanceArityReported = (
879
1012
  scope: LocalName | undefined,
880
1013
  unit: Unit,
881
1014
  ) => {
882
- if (expression.kind !== "Identifier" && expression.kind !== "Apply") return false;
1015
+ if (!isReference(expression)) return false;
1016
+ const selectors = getSelectors(expression);
1017
+ const nameCount = selectors.findIndex((selector) => selector.kind !== "Name");
883
1018
  const instance = findInstance(
884
- expression.kind === "Identifier" ? expression.name : expression.operator,
1019
+ selectors
1020
+ .slice(0, nameCount === -1 ? selectors.length : nameCount)
1021
+ .flatMap((selector) => (selector.kind === "Name" ? [selector.name] : []))
1022
+ .join("!"),
885
1023
  scope,
886
1024
  unit,
887
1025
  );
888
- const count = expression.kind === "Apply" ? (expression.argumentCounts?.[0] ?? 0) : 0;
1026
+ const first = selectors[0];
1027
+ const count = first.kind === "Name" ? first.args.length : 0;
889
1028
  if (!instance || count === instance.arity) return false;
890
1029
  const range =
891
- (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ??
1030
+ (expression.kind === "Identifier" ? undefined : expression.argumentRanges?.[0]) ??
892
1031
  expression.location.range;
893
1032
  if (range) {
894
1033
  unit.errors.push({
@@ -899,6 +1038,103 @@ const isInstanceArityReported = (
899
1038
  return true;
900
1039
  };
901
1040
 
1041
+ const isArgumentCountReported = (
1042
+ callee: Binding | undefined,
1043
+ name: string,
1044
+ count: number,
1045
+ range: SourceRange | undefined,
1046
+ unit: Unit,
1047
+ ) => {
1048
+ const params = callee?.kind === "Definition" ? callee.params : undefined;
1049
+ if (!callee || !params || params.length === callee.arity) return false;
1050
+ if (range && !unit.isGenerated) {
1051
+ unit.errors.push({
1052
+ location: formatRange(range),
1053
+ message: `Wrong number of arguments (${count}) given to operator '${resolveSynonym(name)}', \nwhich requires ${params.length} arguments.`,
1054
+ });
1055
+ }
1056
+ return true;
1057
+ };
1058
+
1059
+ const matchArgument = (
1060
+ arg: Expression,
1061
+ expected: number,
1062
+ index: number,
1063
+ operator: string,
1064
+ operatorRange: SourceRange | undefined,
1065
+ scope: LocalName | undefined,
1066
+ unit: Unit,
1067
+ ) => {
1068
+ const report = (range: SourceRange | undefined, message: string) => {
1069
+ if (range) unit.errors.push({ location: formatRange(range), message });
1070
+ };
1071
+ const range = arg.location.range;
1072
+ if (expected === 0) {
1073
+ const selectionError = operatorSelectionErrors.get(arg);
1074
+ // Deviation from SANY: SANY names its internal node kind here, where tla-ts words it as for a name.
1075
+ if (arg.kind === "Lambda" && arg.operator !== undefined) {
1076
+ report(range, `The operator ${resolveSynonym(arg.operator)} requires 1 arguments.`);
1077
+ } else if (selectionError) {
1078
+ unit.errors.push(selectionError);
1079
+ } else if (arg.kind === "Lambda" && range) {
1080
+ report(range, "LAMBDA expression used where an expression is required.");
1081
+ } else if (arg.kind === "OperatorReference") {
1082
+ const argArity = getSymbolArity(arg, arg.operator, scope, unit);
1083
+ if (argArity !== undefined) {
1084
+ report(
1085
+ range,
1086
+ `The operator ${resolveSynonym(arg.operator)} requires ${argArity} arguments.`,
1087
+ );
1088
+ }
1089
+ } else resolveExpression(arg, scope, unit);
1090
+ return true;
1091
+ }
1092
+ if (arg.kind === "Lambda") {
1093
+ if (selections.has(arg)) resolveExpression(arg, scope, unit);
1094
+ else resolveLambda(arg, scope, unit);
1095
+ const isMatched = arg.params.length === expected;
1096
+ if (!isMatched && selections.has(arg)) {
1097
+ report(range, `Expected arity ${expected} but found operator of arity ${arg.params.length}.`);
1098
+ } else if (!isMatched && range && arg.operator === undefined) {
1099
+ report(
1100
+ operatorRange,
1101
+ `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
1102
+ );
1103
+ }
1104
+ return isMatched;
1105
+ }
1106
+ if (arg.kind === "Subexpression") {
1107
+ resolveExpression(arg, scope, unit);
1108
+ return true;
1109
+ }
1110
+ if (arg.kind === "Apply" && arg.argumentCounts?.at(-1) === 0) {
1111
+ const selectorIndex = arg.argumentCounts.findIndex((count) => count > 0);
1112
+ report(
1113
+ arg.selectorRanges?.[selectorIndex],
1114
+ `Selector \`${arg.operator.split("!")[selectorIndex]}' should not have argument(s).`,
1115
+ );
1116
+ return false;
1117
+ }
1118
+ if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
1119
+ report(
1120
+ range,
1121
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
1122
+ );
1123
+ return false;
1124
+ }
1125
+ const name = arg.kind === "Identifier" ? arg.name : arg.operator;
1126
+ const argParams = findBinding(name, scope, unit)?.params ?? [];
1127
+ const argArity = getSymbolArity(arg, name, scope, unit);
1128
+ if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
1129
+ report(
1130
+ getSpelledNameRange(arg, name),
1131
+ `Expected arity ${expected} but found operator of arity ${argArity}.`,
1132
+ );
1133
+ }
1134
+ // Deviation from SANY: OpDefNode#matchingOpArgOperand reads as many parameters as a RECURSIVE declaration gives and crashes when the definition has fewer.
1135
+ return argArity === expected && argParams.every((param) => param === 0);
1136
+ };
1137
+
902
1138
  const resolveApply = (
903
1139
  expression: Expression & { kind: "Apply" },
904
1140
  scope: LocalName | undefined,
@@ -912,90 +1148,42 @@ const resolveApply = (
912
1148
  if (arity !== expression.args.length) {
913
1149
  unit.errors.push({
914
1150
  location: formatRange(expression.argumentsRange ?? getSpelledNameRange(expression, operator)),
915
- message: `The operator ${operator} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
1151
+ message: `The operator ${resolveSynonym(operator)} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
916
1152
  });
917
1153
  return;
918
1154
  }
919
- const params = callee && (callee.kind === "Definition" ? callee.params : []);
1155
+ const params =
1156
+ callee && (callee.kind === "Definition" ? callee.params : expression.args.map(() => 0));
920
1157
  if (params === undefined) {
921
1158
  expression.args.forEach((arg) => resolveArgument(arg, scope, unit));
922
1159
  return;
923
1160
  }
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
- });
1161
+ const operatorRange =
1162
+ expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator);
1163
+ const matches = expression.args
1164
+ .slice(0, params.length)
1165
+ .map((arg, index) =>
1166
+ matchArgument(arg, params[index], index, operator, operatorRange, scope, unit),
1167
+ );
1168
+ if (
1169
+ isArgumentCountReported(
1170
+ callee,
1171
+ operator,
1172
+ expression.args.length,
1173
+ expression.location.range,
1174
+ unit,
1175
+ )
1176
+ ) {
1177
+ return;
1178
+ }
1179
+ matches.forEach((isMatched, index) => {
1180
+ if (!isMatched && expression.location.range) {
1181
+ unit.errors.push({
1182
+ location: formatRange(expression.location.range),
1183
+ message: `Argument number ${index + 1} to operator '${operator}' \nshould be a ${params[index]}-parameter operator.`,
1184
+ });
1185
+ }
1186
+ });
999
1187
  };
1000
1188
 
1001
1189
  const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
@@ -1006,18 +1194,50 @@ const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Un
1006
1194
  const isSelectionReported = (expression: Expression, scope: LocalName | undefined, unit: Unit) => {
1007
1195
  const failed = selectionErrors.get(expression);
1008
1196
  if (!failed) return false;
1009
- failed.args.forEach((arg) => resolveArgument(arg, scope, unit));
1197
+ failed.applications.forEach((application) =>
1198
+ application.args
1199
+ .slice(0, application.params.length)
1200
+ .forEach((arg, index) =>
1201
+ matchArgument(
1202
+ arg,
1203
+ application.params[index],
1204
+ index,
1205
+ application.operator,
1206
+ application.range,
1207
+ scope,
1208
+ unit,
1209
+ ),
1210
+ ),
1211
+ );
1010
1212
  unit.errors.push(failed.error);
1011
1213
  return true;
1012
1214
  };
1013
1215
 
1216
+ const resolveLambda = (
1217
+ expression: Expression & { kind: "Lambda" },
1218
+ scope: LocalName | undefined,
1219
+ unit: Unit,
1220
+ ) =>
1221
+ resolveExpression(
1222
+ expression.body,
1223
+ bindNames(scope, expression.params, expression.paramRanges, unit),
1224
+ {
1225
+ ...unit,
1226
+ labelParams: [...unit.labelParams, ...expression.params],
1227
+ },
1228
+ );
1229
+
1014
1230
  const resolveExpression = (
1015
1231
  expression: Expression,
1016
1232
  scope: LocalName | undefined,
1017
1233
  unit: Unit,
1018
1234
  ): void => {
1019
1235
  if (selections.has(expression) && !unit.isGenerated) {
1020
- resolveExpression(expression, scope, { ...unit, isGenerated: true });
1236
+ const failed = nullSelections
1237
+ .get(expression)
1238
+ ?.find((selection) => unresolvedExpressions.has(selection.node));
1239
+ if (failed) unit.errors.push(failed.error);
1240
+ else resolveExpression(expression, scope, { ...unit, isGenerated: true });
1021
1241
  return;
1022
1242
  }
1023
1243
  const resolveAll = (expressions: Expression[]) =>
@@ -1030,16 +1250,31 @@ const resolveExpression = (
1030
1250
  case "Number":
1031
1251
  case "Decimal":
1032
1252
  case "String":
1253
+ return;
1033
1254
  case "ExceptAt":
1255
+ if (!unit.isInExcept && expression.location.range) {
1256
+ unit.errors.push({
1257
+ location: formatRange(expression.location.range),
1258
+ message: "@ used where its meaning is not defined.",
1259
+ });
1260
+ }
1034
1261
  return;
1035
1262
  case "Identifier": {
1036
1263
  if (isInstanceArityReported(expression, scope, unit)) return;
1037
1264
  const name = expression.name;
1038
1265
  const arity = getSymbolArity(expression, name, scope, unit);
1039
- if (arity !== undefined && arity > 0) {
1266
+ if (arity === 0) {
1267
+ isArgumentCountReported(
1268
+ findBinding(name, scope, unit),
1269
+ name,
1270
+ 0,
1271
+ getSpelledNameRange(expression, name),
1272
+ unit,
1273
+ );
1274
+ } else if (arity !== undefined) {
1040
1275
  unit.errors.push({
1041
1276
  location: formatRange(getSpelledNameRange(expression, name)),
1042
- message: `The operator ${name} requires ${arity} arguments.`,
1277
+ message: `The operator ${resolveSynonym(name)} requires ${arity} arguments.`,
1043
1278
  });
1044
1279
  }
1045
1280
  return;
@@ -1051,11 +1286,13 @@ const resolveExpression = (
1051
1286
  resolveApply(expression, scope, unit);
1052
1287
  return;
1053
1288
  case "Lambda":
1054
- resolveExpression(
1055
- expression.body,
1056
- bindNames(scope, expression.params, expression.paramRanges, unit),
1057
- bindLabelParams(expression.params),
1058
- );
1289
+ if (selections.has(expression)) resolveLambda(expression, scope, unit);
1290
+ else if (expression.location.range) {
1291
+ unit.errors.push({
1292
+ location: formatRange(expression.location.range),
1293
+ message: "LAMBDA expression used where an expression is required.",
1294
+ });
1295
+ }
1059
1296
  return;
1060
1297
  case "And":
1061
1298
  case "Or":
@@ -1078,7 +1315,13 @@ const resolveExpression = (
1078
1315
  case "Let":
1079
1316
  resolveExpression(
1080
1317
  expression.body,
1081
- resolveDefinitions(expression.definitions, scope, unit, expression.instances),
1318
+ resolveDefinitions(
1319
+ expression.definitions,
1320
+ scope,
1321
+ unit,
1322
+ expression.instances,
1323
+ expression.recursive,
1324
+ ),
1082
1325
  unit,
1083
1326
  );
1084
1327
  return;
@@ -1168,34 +1411,199 @@ const resolveExpression = (
1168
1411
  resolveExpression(expression.body, scope, { ...unit, labelParams: [], labels: new Set() });
1169
1412
  checkLabel(expression, scope, unit);
1170
1413
  return;
1414
+ case "Subexpression":
1415
+ isSubexpressionReported(expression, scope, unit);
1416
+ return;
1417
+ }
1418
+ };
1419
+
1420
+ const isSubexpressionReported = (
1421
+ expression: Expression & { kind: "Subexpression" },
1422
+ scope: LocalName | undefined,
1423
+ unit: Unit,
1424
+ ) => {
1425
+ if (
1426
+ isInstanceArityReported(expression, scope, unit) ||
1427
+ isSelectionReported(expression, scope, unit)
1428
+ ) {
1429
+ return true;
1430
+ }
1431
+ expression.selectors
1432
+ .flatMap((selector) => ("args" in selector ? selector.args : []))
1433
+ .forEach((arg) => resolveArgument(arg, scope, unit));
1434
+ const selected = checkReference(expression, scope, unit, false);
1435
+ if (selected) return selected.node === undefined;
1436
+ const head = expression.selectors[0];
1437
+ const range = expression.selectorRanges?.[0];
1438
+ const nameCount = expression.selectors.findIndex((selector) => selector.kind !== "Name");
1439
+ const names = expression.selectors
1440
+ .slice(0, nameCount)
1441
+ .flatMap((selector) => (selector.kind === "Name" ? [selector.name] : []));
1442
+ const symbolIndex = names.findIndex(
1443
+ (_name, index) => index > 0 && findSymbol(names.slice(0, index + 1).join("!"), unit),
1444
+ );
1445
+ const isInstance =
1446
+ names.length > 1 &&
1447
+ (lookupLocal(scope, names[0]) ?? getModuleBinding(names[0], unit, undefined))?.kind ===
1448
+ "Instance";
1449
+ const lastRange = expression.selectorRanges?.[nameCount - 1];
1450
+ if (isInstance && symbolIndex === -1 && range && lastRange) {
1451
+ unit.errors.push({
1452
+ location: formatRange({ module: range.module, start: range.start, end: lastRange.end }),
1453
+ message: `Unknown operator: \`${resolveSynonym(names.join("!"))}'.`,
1454
+ });
1455
+ return true;
1456
+ }
1457
+ const name = names.slice(0, symbolIndex + 1).join("!");
1458
+ const symbol = symbolIndex > 0 ? findSymbol(name, unit) : undefined;
1459
+ const argumentCount = expression.selectors
1460
+ .slice(0, symbolIndex + 1)
1461
+ .flatMap((selector) => ("args" in selector ? selector.args : [])).length;
1462
+ const argumentRange = expression.argumentRanges?.[symbolIndex] ?? expression.location.range;
1463
+ if (symbol && symbol.arity !== argumentCount && argumentRange) {
1464
+ unit.errors.push({
1465
+ location: formatRange(argumentRange),
1466
+ message: `The operator ${resolveSynonym(name)} requires ${symbol.arity} arguments.`,
1467
+ });
1468
+ return true;
1469
+ }
1470
+ if (head.kind !== "Name" || expression.selectors[1].kind === "Name" || !range) return false;
1471
+ const local = lookupLocal(scope, head.name);
1472
+ const binding = local ?? findSymbol(head.name, unit);
1473
+ if ((binding === undefined && !isFact(head.name, unit)) || binding?.kind === "Instance") {
1474
+ unit.errors.push({
1475
+ location: formatRange(range),
1476
+ message: `Unknown operator: \`${resolveSynonym(head.name)}'.`,
1477
+ });
1478
+ return true;
1479
+ }
1480
+ if (binding && (!SELECTABLE_KINDS.has(binding.kind) || local?.isNonFact)) {
1481
+ reportUnselectable(head.name, range, unit);
1482
+ return true;
1483
+ }
1484
+ return false;
1485
+ };
1486
+
1487
+ const checkFact = (fact: Fact, reference: Fact, scope: LocalName | undefined, unit: Unit) => {
1488
+ if (fact.kind === "ModuleFact") return undefined;
1489
+ if (fact.kind === "ExceptAt" && fact.location.range) {
1490
+ unit.errors.push({
1491
+ location: formatRange(fact.location.range),
1492
+ message: "Unknown operator: `@'.",
1493
+ });
1494
+ return BUILTIN_LOCATION;
1495
+ }
1496
+ const hidden = getHiddenExpressionLocation(fact, reference, scope, unit);
1497
+ if (isInstanceArityReported(fact, scope, unit)) return hidden;
1498
+ const selected = checkReference(fact, scope, unit, true);
1499
+ if (selected) {
1500
+ const kind = selected.node?.kind;
1501
+ if (kind === undefined) return BUILTIN_LOCATION;
1502
+ return kind === "AssumeProve" || kind === "NewSymbol"
1503
+ ? undefined
1504
+ : fact.location.range && formatRange(fact.location.range);
1505
+ }
1506
+ if (fact.kind === "Subexpression") {
1507
+ return isSubexpressionReported(fact, scope, unit) ? BUILTIN_LOCATION : hidden;
1508
+ }
1509
+ const name = fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1510
+ if (fact.kind === "Identifier" && lookupLocal(scope, name)?.isNonFact) {
1511
+ unit.errors.push({
1512
+ location: formatRange(getSpelledNameRange(fact, name)),
1513
+ message: "Step number of non-fact used as a fact",
1514
+ });
1515
+ return BUILTIN_LOCATION;
1516
+ }
1517
+ if (!isFact(name, unit) && !lookupLocal(scope, name)?.goal) resolveExpression(fact, scope, unit);
1518
+ return hidden;
1519
+ };
1520
+
1521
+ const isDefinitionEntry = (def: Fact, scope: LocalName | undefined, unit: Unit) => {
1522
+ const range = def.location.range;
1523
+ const name =
1524
+ def.kind === "Identifier" ? def.name : def.kind === "OperatorReference" ? def.operator : "";
1525
+ if (name === "" || !range) return true;
1526
+ const binding =
1527
+ lookupLocal(scope, name) ?? findSymbol(name, unit) ?? getModuleBinding(name, unit, range);
1528
+ if (binding === undefined && (isFact(name, unit) || isStepName(name))) return true;
1529
+ if (binding === undefined) {
1530
+ unit.errors.push({
1531
+ location: formatRange(range),
1532
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
1533
+ });
1534
+ }
1535
+ if (binding && SELECTABLE_KINDS.has(binding.kind) && !isStepName(name)) return true;
1536
+ unit.errors.push({
1537
+ location: formatRange(range),
1538
+ message: "DEF clause entry should describe a defined operator.",
1539
+ });
1540
+ return false;
1541
+ };
1542
+
1543
+ const getHiddenExpressionLocation = (
1544
+ fact: Expression,
1545
+ reference: Fact,
1546
+ scope: LocalName | undefined,
1547
+ unit: Unit,
1548
+ ) => {
1549
+ const range = fact.location.range && formatRange(fact.location.range);
1550
+ if (selections.has(fact)) {
1551
+ return reference.location.range && formatRange(reference.location.range);
1552
+ }
1553
+ if (selectionErrors.has(fact) || fact.kind === "ExceptAt") return BUILTIN_LOCATION;
1554
+ switch (fact.kind) {
1555
+ case "Number":
1556
+ case "String":
1557
+ case "Decimal":
1558
+ case "Let":
1559
+ case "Label":
1560
+ return undefined;
1561
+ case "Identifier":
1562
+ case "Apply":
1171
1563
  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);
1564
+ const first = getSelectors(fact)[0];
1565
+ if (fact.kind === "Subexpression" || first.kind !== "Name") return undefined;
1566
+ const name = fact.kind === "Identifier" ? fact.name : fact.operator;
1567
+ const goal = lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit);
1568
+ if (isFact(name, unit) || goal || (isStepName(name) && lookupLocal(scope, name))) {
1569
+ return undefined;
1570
+ }
1571
+ const binding = findBinding(name, scope, unit);
1572
+ const count = fact.kind === "Apply" ? fact.args.length : 0;
1573
+ return binding?.arity === count ? range : BUILTIN_LOCATION;
1177
1574
  }
1575
+ default:
1576
+ return range;
1178
1577
  }
1179
1578
  };
1180
1579
 
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;
1189
- }
1190
- const name =
1191
- fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1192
- if (fact.kind === "Identifier" && lookupLocal(scope, name)?.isNonFact) {
1580
+ const checkUseOrHide = (
1581
+ statement: UseOrHide | Extract<Proof, { kind: "By" }>,
1582
+ scope: LocalName | undefined,
1583
+ unit: Unit,
1584
+ ) => {
1585
+ const references = factReferences.get(statement.facts) ?? statement.facts;
1586
+ const hidden = statement.facts.map((fact, index) =>
1587
+ checkFact(fact, references[index], scope, unit),
1588
+ );
1589
+ const defCount = statement.defs.filter((def) => isDefinitionEntry(def, scope, unit)).length;
1590
+ hidden.forEach((location) => {
1591
+ if (location && statement.kind === "Hide") {
1193
1592
  unit.errors.push({
1194
- location: formatRange(getSpelledNameRange(fact, name)),
1195
- message: "Step number of non-fact used as a fact",
1593
+ location,
1594
+ message:
1595
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1196
1596
  });
1197
- } else if (!unit.facts.has(name)) resolveExpression(fact, scope, unit);
1597
+ }
1198
1598
  });
1599
+ const range = statement.location.range;
1600
+ if (statement.facts.length + defCount === 0 && range) {
1601
+ unit.errors.push({
1602
+ location: formatRange(range),
1603
+ message: statement.kind === "By" ? "Empty BY" : "Empty USE or HIDE statement.",
1604
+ });
1605
+ }
1606
+ };
1199
1607
 
1200
1608
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
1201
1609
  if (symbol.set) resolveExpression(symbol.set, scope, unit);
@@ -1244,7 +1652,7 @@ const resolveStatement = (
1244
1652
 
1245
1653
  const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, outer: Unit) => {
1246
1654
  const unit = outer.hasLabelScope ? { ...outer, hasLabelScope: false } : outer;
1247
- if (proof?.kind === "By") checkFacts(proof.facts, scope, unit);
1655
+ if (proof?.kind === "By") checkUseOrHide(proof, scope, unit);
1248
1656
  if (proof?.kind !== "Steps") return;
1249
1657
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
1250
1658
  };
@@ -1261,6 +1669,42 @@ const resolveLocalInstance = (instance: Instance, scope: LocalName | undefined,
1261
1669
  );
1262
1670
  };
1263
1671
 
1672
+ const getStepGoal = (body: StepBody, location: SourceLocation): Goal | undefined => {
1673
+ const createGoal = (keyword: string, statement: Expression) => ({
1674
+ statement,
1675
+ isSuffices: false,
1676
+ isInProof: false,
1677
+ keyword,
1678
+ });
1679
+ switch (body.kind) {
1680
+ case "Have":
1681
+ return createGoal("HAVE", { kind: "Tuple", elements: [body.expression], location });
1682
+ case "Case":
1683
+ return createGoal("CASE", { kind: "Tuple", elements: [body.expression], location });
1684
+ case "Witness":
1685
+ return createGoal("WITNESS", { kind: "Tuple", elements: body.expressions, location });
1686
+ case "Take":
1687
+ return createGoal("TAKE", { kind: "Tuple", elements: getBoundSets(body.bounds), location });
1688
+ case "Pick":
1689
+ return createGoal(
1690
+ "PICK",
1691
+ body.bounds.length > 0
1692
+ ? { kind: "Exists", bounds: body.bounds, body: body.body, location }
1693
+ : {
1694
+ kind: "UnboundedQuantifier",
1695
+ quantifier: "Exists",
1696
+ names: body.names,
1697
+ body: body.body,
1698
+ location,
1699
+ },
1700
+ );
1701
+ case "Qed":
1702
+ return createGoal("QED step", { kind: "Tuple", elements: [], location });
1703
+ default:
1704
+ return undefined;
1705
+ }
1706
+ };
1707
+
1264
1708
  const resolveStep = (
1265
1709
  step: ProofStep,
1266
1710
  scope: LocalName | undefined,
@@ -1271,8 +1715,9 @@ const resolveStep = (
1271
1715
  step.name === undefined
1272
1716
  ? unit
1273
1717
  : { ...unit, hasLabelScope: true, labelParams: [], labels: new Set<string>() };
1718
+ const goal = getStepGoal(body, step.location);
1274
1719
  const bindStep = (parent: LocalName | undefined): LocalName | undefined =>
1275
- step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent };
1720
+ step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent, goal };
1276
1721
  const bindNonFactStep = (parent: LocalName | undefined): LocalName | undefined =>
1277
1722
  step.name === undefined
1278
1723
  ? parent
@@ -1286,14 +1731,29 @@ const resolveStep = (
1286
1731
  resolveProof(step.proof, proofScope, unit);
1287
1732
  return body.isSuffices ? assumed : scope;
1288
1733
  }
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 };
1734
+ const assertion = {
1735
+ statement: body.statement,
1736
+ isSuffices: body.isSuffices,
1737
+ isInProof: true,
1738
+ keyword: body.isSuffices && body.statement.kind !== "AssumeProve" ? "SUFFICES" : undefined,
1739
+ };
1740
+ resolveProof(
1741
+ step.proof,
1742
+ { name, arity: 0, kind: "Theorem", parent: proofScope, goal: assertion },
1743
+ unit,
1744
+ );
1745
+ assertion.isInProof = false;
1746
+ return {
1747
+ name,
1748
+ arity: 0,
1749
+ kind: "Theorem",
1750
+ parent: body.isSuffices ? assumed : scope,
1751
+ goal: assertion,
1752
+ };
1293
1753
  }
1294
1754
  case "Use":
1295
1755
  case "Hide":
1296
- checkFacts(body.facts, scope, unit);
1756
+ checkUseOrHide(body, scope, unit);
1297
1757
  return bindNonFactStep(scope);
1298
1758
  case "Instance":
1299
1759
  return bindNonFactStep(resolveLocalInstance(body, scope, stepUnit));
@@ -1416,18 +1876,72 @@ const checkSubstitutions = (
1416
1876
  (parent, param) => ({ name: param.name, arity: param.arity, kind: "Parameter", parent }),
1417
1877
  outer,
1418
1878
  );
1879
+ const reportArity = (declaration: Declaration, location: string) =>
1880
+ unit.errors.push({
1881
+ location,
1882
+ message: `An operator must be substituted for symbol '${resolveSynonym(declaration.name)}', and it must have arity ${declaration.arity}.`,
1883
+ });
1419
1884
  const resolveSubstitute = (declaration: Declaration, expression: Expression) => {
1420
- if (declaration.arity === 0 || expression.kind !== "Identifier") {
1885
+ const range = expression.location.range;
1886
+ if (declaration.arity === 0) {
1421
1887
  resolveExpression(expression, scope, unit);
1422
1888
  return;
1423
1889
  }
1890
+ if (expression.kind === "Lambda") {
1891
+ resolveLambda(expression, scope, unit);
1892
+ if (expression.params.length !== declaration.arity && range) {
1893
+ reportArity(declaration, formatRange(range));
1894
+ }
1895
+ return;
1896
+ }
1897
+ if (expression.kind === "OperatorReference") {
1898
+ const arity = getSymbolArity(expression, expression.operator, scope, unit);
1899
+ if (arity === undefined) reportArity(declaration, BUILTIN_LOCATION);
1900
+ else if (arity !== declaration.arity && range) reportArity(declaration, formatRange(range));
1901
+ return;
1902
+ }
1903
+ if (expression.kind !== "Identifier") {
1904
+ if (range) {
1905
+ unit.errors.push({
1906
+ location: formatRange(range),
1907
+ message: `Arity ${declaration.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${resolveSynonym(declaration.name)}'.`,
1908
+ });
1909
+ }
1910
+ reportArity(declaration, BUILTIN_LOCATION);
1911
+ return;
1912
+ }
1424
1913
  const arity = getSymbolArity(expression, expression.name, scope, unit);
1425
1914
  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
- );
1915
+ unit.errors.push({
1916
+ location: formatRange(getSpelledNameRange(expression, expression.name)),
1917
+ message: `Expected arity ${declaration.arity} but found operator of arity ${arity}.`,
1918
+ });
1429
1919
  }
1920
+ if (arity !== declaration.arity) reportArity(declaration, BUILTIN_LOCATION);
1430
1921
  };
1922
+ const instanceRange = instance.location.range;
1923
+ const isFound = (declaration: Declaration) =>
1924
+ lookupLocal(scope, declaration.name) !== undefined ||
1925
+ findSymbol(declaration.name, unit) !== undefined;
1926
+ const implicit = declarations.filter(isFound).map((declaration) => {
1927
+ const expression: Expression & { kind: "Identifier" } = {
1928
+ kind: "Identifier",
1929
+ name: declaration.name,
1930
+ location: instance.location,
1931
+ };
1932
+ return { declaration, expression };
1933
+ });
1934
+ implicit
1935
+ .filter((item) => item.declaration.arity === 0)
1936
+ .forEach((item) => {
1937
+ const arity = getSymbolArity(item.expression, item.declaration.name, scope, unit);
1938
+ if (arity && instanceRange) {
1939
+ unit.errors.push({
1940
+ location: formatRange(instanceRange),
1941
+ message: `Wrong number of arguments (0) given to operator '${resolveSynonym(item.declaration.name)}', \nwhich requires ${arity} arguments.`,
1942
+ });
1943
+ }
1944
+ });
1431
1945
  const substitutions = new Map<string, Expression>();
1432
1946
  instance.substitutions.forEach((substitution) => {
1433
1947
  const name = substitution.name;
@@ -1450,30 +1964,29 @@ const checkSubstitutions = (
1450
1964
  });
1451
1965
  }
1452
1966
  });
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
1967
  implicit
1457
- .filter((declaration) => !isMissing(declaration))
1968
+ .filter((item) => !substitutions.has(item.declaration.name))
1969
+ .forEach((item) => {
1970
+ const arity =
1971
+ item.declaration.arity === 0
1972
+ ? 0
1973
+ : getSymbolArity(item.expression, item.declaration.name, scope, unit);
1974
+ if (arity !== item.declaration.arity && instanceRange) {
1975
+ reportArity(item.declaration, formatRange(instanceRange));
1976
+ }
1977
+ substitutions.set(item.declaration.name, item.expression);
1978
+ });
1979
+ declarations
1980
+ .filter((declaration) => !substitutions.has(declaration.name))
1458
1981
  .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);
1982
+ const declared = declaration.location.range;
1983
+ if (instanceRange && declared) {
1984
+ unit.errors.push({
1985
+ location: formatRange(instanceRange),
1986
+ message: `Substitution missing for symbol ${resolveSynonym(declaration.name)} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
1987
+ });
1988
+ }
1466
1989
  });
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
1990
  return substitutions;
1478
1991
  };
1479
1992
 
@@ -1481,7 +1994,7 @@ const resolveInstance = (instance: Instance, scope: LocalName | undefined, unit:
1481
1994
  const instanced = unit.getInstance(instance);
1482
1995
  checkSubstitutions(instance, instanced.declarations, instanced.instancer, scope, unit);
1483
1996
  return [...instanced.symbols].reduce(
1484
- (parent, [name, symbol]) => bindName(parent, name, symbol, unit),
1997
+ (parent, entry) => bindName(parent, entry[0], entry[1], unit),
1485
1998
  scope,
1486
1999
  );
1487
2000
  };
@@ -1493,6 +2006,12 @@ export const resolveSubstitutions = (
1493
2006
  unit: ModuleUnit,
1494
2007
  ) => {
1495
2008
  const imported = createSymbols(module, unit.imported);
2009
+ const positions = new Map(
2010
+ [...module.constants, ...module.variables].map((declaration) => [
2011
+ declaration.name,
2012
+ declaration.location,
2013
+ ]),
2014
+ );
1496
2015
  const report: ModuleReport = { location: instance.location, errors: [], warnings: [] };
1497
2016
  unit.reports.push(report);
1498
2017
  return checkSubstitutions(instance, declarations, module.name, undefined, {
@@ -1505,7 +2024,10 @@ export const resolveSubstitutions = (
1505
2024
  facts: new Set(),
1506
2025
  goals: new Map(),
1507
2026
  bindings: new Map(
1508
- [...imported].map(([name, symbol]) => [name, { ...symbol, position: MODULE_START }]),
2027
+ [...imported].map((entry) => [
2028
+ entry[0],
2029
+ { ...entry[1], position: positions.get(entry[0]) ?? MODULE_START },
2030
+ ]),
1509
2031
  ),
1510
2032
  errors: report.errors,
1511
2033
  warnings: report.warnings,
@@ -1535,13 +2057,7 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1535
2057
  }
1536
2058
  };
1537
2059
  units
1538
- .toSorted((left, right) =>
1539
- isBefore(left.location, right.location)
1540
- ? -1
1541
- : isBefore(right.location, left.location)
1542
- ? 1
1543
- : 0,
1544
- )
2060
+ .toSorted((left, right) => compareLocations(left.location, right.location))
1545
2061
  .forEach((unit) => {
1546
2062
  const reported: SanyError[] = [];
1547
2063
  const warned: SanyError[] = [];
@@ -1561,21 +2077,27 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1561
2077
 
1562
2078
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
1563
2079
  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
2080
  const goals = new Map(
1569
2081
  module.theorems.flatMap((theorem): [string, Goal][] =>
1570
2082
  theorem.name !== undefined && theorem.statement.kind === "AssumeProve"
1571
- ? [[theorem.name, { statement: theorem.statement, isSuffices: false, isInProof: false }]]
2083
+ ? [
2084
+ [
2085
+ theorem.name,
2086
+ {
2087
+ statement: theorem.statement,
2088
+ isSuffices: false,
2089
+ isInProof: false,
2090
+ keyword: undefined,
2091
+ },
2092
+ ],
2093
+ ]
1572
2094
  : [],
1573
2095
  ),
1574
2096
  );
1575
2097
  const bindings = new Map<string, ModuleBinding>(
1576
- [...CORE_SYMBOLS, ...unit.bound].map(([name, symbol]) => [
1577
- name,
1578
- { ...symbol, position: MODULE_START },
2098
+ [...CORE_SYMBOLS, ...unit.bound].map((entry) => [
2099
+ entry[0],
2100
+ { ...entry[1], position: MODULE_START },
1579
2101
  ]),
1580
2102
  );
1581
2103
  const recursive = new Set<Binding>();
@@ -1595,7 +2117,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1595
2117
  getKey: unit.getKey,
1596
2118
  location,
1597
2119
  self,
1598
- facts,
2120
+ facts: unit.facts,
1599
2121
  goals,
1600
2122
  bindings,
1601
2123
  errors,
@@ -1620,6 +2142,37 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1620
2142
  );
1621
2143
  return collectSemanticErrors(
1622
2144
  [
2145
+ ...module.units.flatMap((item): SemanticUnit[] => {
2146
+ const section =
2147
+ item.kind === "Variables"
2148
+ ? { type: "A VARIABLE declaration", location: item.location }
2149
+ : item.kind === "Constants"
2150
+ ? { type: "A declaration", location: item.location }
2151
+ : item.kind === "Module"
2152
+ ? { type: "A MODULE ", location: item.module.location }
2153
+ : item.kind === "Theorem"
2154
+ ? { type: "A THEOREM", location: item.theorem.location }
2155
+ : item.kind === "Assumption"
2156
+ ? { type: "An ASSUME", location: item.assumption.location }
2157
+ : item.kind === "Use"
2158
+ ? { type: "A USE or HIDE", location: item.use.location }
2159
+ : undefined;
2160
+ const range = section?.location.range;
2161
+ if (!section || !range) return [];
2162
+ return [
2163
+ {
2164
+ location: section.location,
2165
+ check: (errors) => {
2166
+ if (declarations.some((declared) => declared.binding?.isPending)) {
2167
+ errors.push({
2168
+ location: formatRange(range),
2169
+ message: `${section.type} may not appear within a recursive definition section.`,
2170
+ });
2171
+ }
2172
+ },
2173
+ },
2174
+ ];
2175
+ }),
1623
2176
  ...unit.reports.map((report) => ({
1624
2177
  location: report.location,
1625
2178
  check: (errors: SanyError[], warnings: SanyError[]) => {
@@ -1636,6 +2189,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1636
2189
  const binding: ModuleBinding = {
1637
2190
  kind: "Definition",
1638
2191
  arity: declaration.arity,
2192
+ params: Array(declaration.arity).fill(0),
1639
2193
  range: declaration.location.range,
1640
2194
  position: declaration.location,
1641
2195
  isPending: true,
@@ -1701,7 +2255,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1701
2255
  ),
1702
2256
  ...module.uses.map((use) =>
1703
2257
  createCheck(use.location, undefined, false, (inner) =>
1704
- checkFacts(use.facts, undefined, inner),
2258
+ checkUseOrHide(use, undefined, inner),
1705
2259
  ),
1706
2260
  ),
1707
2261
  {
@@ -1712,7 +2266,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1712
2266
  if (range && (!item.binding || item.binding.isPending)) {
1713
2267
  errors.push({
1714
2268
  location: formatRange(range),
1715
- message: `Symbol ${item.declaration.name} declared in RECURSIVE statement but not defined.`,
2269
+ message: `Symbol ${resolveSynonym(item.declaration.name)} declared in RECURSIVE statement but not defined.`,
1716
2270
  });
1717
2271
  }
1718
2272
  }),