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

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