tla-ts 0.0.10-dev.09e53c2a6 → 0.0.10-dev.1ebc153bd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/dist/compile.cjs +3 -3
  2. package/dist/compile.js +1 -1
  3. package/dist/deciders.cjs +36 -36
  4. package/dist/deciders.js +54 -54
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.cts +2 -1
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.js +1 -1
  9. package/dist/parallel-worker.cjs +1 -1
  10. package/dist/parallel-worker.js +1 -1
  11. package/dist/prove-worker.cjs +1 -1
  12. package/dist/prove-worker.js +1 -1
  13. package/dist/prove.cjs +43 -43
  14. package/dist/prove.js +78 -78
  15. package/dist/run.cjs +33 -35
  16. package/dist/run.js +44 -46
  17. package/dist/tlapm.cjs +1 -1
  18. package/dist/tlapm.js +2 -2
  19. package/dist/transfer.cjs +43 -43
  20. package/dist/transfer.js +38 -38
  21. package/dist/worker.cjs +6 -6
  22. package/dist/worker.js +6 -6
  23. package/package.json +1 -1
  24. package/src/ast.ts +1 -0
  25. package/src/bags.ts +46 -28
  26. package/src/check-trace.ts +2 -16
  27. package/src/check.ts +152 -64
  28. package/src/cli/runtime-invariants.ts +20 -56
  29. package/src/cli/tlc-arguments.ts +2 -2
  30. package/src/cli/tlc-output.ts +1 -2
  31. package/src/cli/tlc.ts +13 -8
  32. package/src/cli/xml-exporter.ts +1 -1
  33. package/src/codegen.ts +9 -5
  34. package/src/dependencies.ts +49 -9
  35. package/src/dfid.ts +9 -2
  36. package/src/environment.ts +57 -33
  37. package/src/errors.ts +7 -0
  38. package/src/evaluate.ts +92 -32
  39. package/src/exit-codes.ts +4 -2
  40. package/src/instances.ts +5 -5
  41. package/src/java-overrides.ts +2 -2
  42. package/src/levels.ts +138 -90
  43. package/src/liveness-checker.ts +43 -4
  44. package/src/liveness.ts +1 -1
  45. package/src/obligations/index.ts +1 -1
  46. package/src/obligations/normalize.ts +1 -4
  47. package/src/obligations/printer.ts +5 -5
  48. package/src/parallel-worker.ts +8 -2
  49. package/src/parallel.ts +5 -0
  50. package/src/parser.ts +106 -144
  51. package/src/prover/isabelle/isar/attrib.ts +4 -4
  52. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  53. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  54. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  55. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  56. package/src/prover/isabelle/pure/term.ts +3 -3
  57. package/src/prover/prep/md5.ts +26 -29
  58. package/src/prover/smt/rewrite.ts +2 -7
  59. package/src/prover/smt/simplify.ts +1 -1
  60. package/src/prover/smt/solver/asserted-formulas.ts +66 -1
  61. package/src/prover/smt/solver/ast-lt.ts +1 -1
  62. package/src/prover/smt/solver/ast.ts +58 -11
  63. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  64. package/src/prover/smt/solver/bound-simplifier.ts +2 -3
  65. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  66. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  67. package/src/prover/smt/solver/card2bv.ts +3 -5
  68. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +2 -3
  69. package/src/prover/smt/solver/context.ts +24 -3
  70. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  71. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  72. package/src/prover/smt/solver/dependent-expr-state.ts +9 -4
  73. package/src/prover/smt/solver/diff-neq.ts +1 -2
  74. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  75. package/src/prover/smt/solver/elim-uncnstr.ts +4 -7
  76. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  77. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  78. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  79. package/src/prover/smt/solver/euf/egraph.ts +4 -10
  80. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  81. package/src/prover/smt/solver/euf/mam.ts +1 -5
  82. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  83. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  84. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  85. package/src/prover/smt/solver/factor.ts +36 -14
  86. package/src/prover/smt/solver/fd-solver.ts +2 -0
  87. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  88. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  89. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  90. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  91. package/src/prover/smt/solver/goal.ts +6 -3
  92. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  93. package/src/prover/smt/solver/hashtable.ts +4 -0
  94. package/src/prover/smt/solver/logic-tactics.ts +9 -2
  95. package/src/prover/smt/solver/lp/containers.ts +7 -1
  96. package/src/prover/smt/solver/lp/cross-nested.ts +1 -3
  97. package/src/prover/smt/solver/lp/lp-settings.ts +1 -1
  98. package/src/prover/smt/solver/lp/nex-creator.ts +3 -2
  99. package/src/prover/smt/solver/lp/nex.ts +2 -1
  100. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  101. package/src/prover/smt/solver/lp/nla-grobner.ts +158 -80
  102. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  103. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -2
  104. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -20
  105. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -39
  106. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  107. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  108. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  109. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  110. package/src/prover/smt/solver/model-generator.ts +3 -1
  111. package/src/prover/smt/solver/mpf.ts +2 -4
  112. package/src/prover/smt/solver/mus.ts +2 -3
  113. package/src/prover/smt/solver/muz/dl-context.ts +10 -4
  114. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  115. package/src/prover/smt/solver/muz/dl-rule.ts +2 -2
  116. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  117. package/src/prover/smt/solver/muz/horn-tactic.ts +1 -1
  118. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  119. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  120. package/src/prover/smt/solver/nlqsat.ts +1 -1
  121. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  122. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  123. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  124. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  125. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  126. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  127. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  128. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  129. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  130. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  131. package/src/prover/smt/solver/nnf.ts +6 -2
  132. package/src/prover/smt/solver/opt-context.ts +9 -3
  133. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  134. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  135. package/src/prover/smt/solver/opt-solver.ts +6 -3
  136. package/src/prover/smt/solver/optsmt.ts +1 -1
  137. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  138. package/src/prover/smt/solver/poly-rewriter.ts +74 -18
  139. package/src/prover/smt/solver/probes.ts +88 -23
  140. package/src/prover/smt/solver/proto-model.ts +4 -6
  141. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  142. package/src/prover/smt/solver/qe-lite.ts +2 -2
  143. package/src/prover/smt/solver/qe.ts +3 -2
  144. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  145. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  146. package/src/prover/smt/solver/rlimit.ts +4 -0
  147. package/src/prover/smt/solver/sat/config.ts +1 -1
  148. package/src/prover/smt/solver/sat/inc-sat-solver.ts +26 -1
  149. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  150. package/src/prover/smt/solver/sat/pb-solver.ts +1 -1
  151. package/src/prover/smt/solver/sat/sat-tactic.ts +4 -3
  152. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  153. package/src/prover/smt/solver/sat/solver.ts +25 -47
  154. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  155. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  156. package/src/prover/smt/solver/seq-derive.ts +4 -7
  157. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  158. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  159. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  160. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  161. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  162. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  163. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  164. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  165. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  166. package/src/prover/smt/solver/smt-kernel.ts +9 -3
  167. package/src/prover/smt/solver/smt-setup.ts +68 -6
  168. package/src/prover/smt/solver/smtlib-parser.ts +558 -220
  169. package/src/prover/smt/solver/smtlib-script.ts +495 -153
  170. package/src/prover/smt/solver/solve-eqs.ts +13 -21
  171. package/src/prover/smt/solver/tactic.ts +219 -130
  172. package/src/prover/smt/solver/theory-bv.ts +2 -2
  173. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -1
  174. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -0
  175. package/src/prover/smt/solver/theory-lra-propagate.ts +6 -4
  176. package/src/prover/smt/solver/theory-lra.ts +0 -1
  177. package/src/prover/smt/solver/theory-pb.ts +24 -7
  178. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  179. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  180. package/src/prover/tlapm/cache.ts +8 -8
  181. package/src/prover/zenon/equality-rules.ts +24 -0
  182. package/src/prover/zenon/expr.ts +21 -0
  183. package/src/prover/zenon/index-table.ts +7 -2
  184. package/src/prover/zenon/isar-case.ts +1 -1
  185. package/src/prover/zenon/isar.ts +2 -2
  186. package/src/prover/zenon/phrase.ts +1 -1
  187. package/src/prover/zenon/rules.ts +2 -1
  188. package/src/resolve.ts +624 -187
  189. package/src/runtime.ts +3 -1
  190. package/src/sany/builtins.ts +10 -10
  191. package/src/sany/generation.ts +2 -13
  192. package/src/sany/generator-definitions.ts +3 -1
  193. package/src/sany/generator-expressions.ts +36 -30
  194. package/src/sany/generator-proofs.ts +5 -3
  195. package/src/sany/generator.ts +2 -1
  196. package/src/sany/lexer.ts +3 -3
  197. package/src/sany/modules.ts +4 -2
  198. package/src/sany/nodes.ts +1 -1
  199. package/src/sany/selectors.ts +11 -6
  200. package/src/sany/xml.ts +2 -3
  201. package/src/search.ts +51 -22
  202. package/src/spec-description.ts +2 -2
  203. package/src/subexpressions.ts +265 -94
  204. package/src/successors.ts +1 -0
  205. package/src/symmetry.ts +1 -1
  206. package/src/tlc/jar-data.ts +10 -0
  207. package/src/tlc/messages.ts +3 -3
  208. package/src/tlc/order.ts +14 -3
  209. package/src/tlc/tlc-operators.ts +3 -1
  210. package/src/tlc/tlcext-operators.ts +18 -5
  211. package/src/tlc/trace-spec.ts +5 -5
  212. package/src/typed-tier.ts +29 -23
  213. package/src/typescript/types.ts +2 -2
  214. package/src/values.ts +46 -27
package/src/resolve.ts CHANGED
@@ -19,8 +19,10 @@ import {
19
19
  type SourceLocation,
20
20
  type SourceRange,
21
21
  type Theorem,
22
+ type UseOrHide,
22
23
  } from "./ast";
23
24
  import { formatRange, TlaSyntaxError, type SanyError } from "./errors";
25
+ import { resolveSynonym } from "./tlc/jar-data";
24
26
 
25
27
  export type SymbolKind =
26
28
  | "Builtin"
@@ -84,8 +86,15 @@ interface Unit {
84
86
  isGenerated: boolean;
85
87
  }
86
88
 
87
- interface SelectionError {
89
+ export interface SelectionArguments {
90
+ operator: string;
91
+ range: SourceRange | undefined;
88
92
  args: Expression[];
93
+ params: number[];
94
+ }
95
+
96
+ interface SelectionError {
97
+ applications: SelectionArguments[];
89
98
  error: SanyError;
90
99
  }
91
100
 
@@ -99,8 +108,15 @@ type Reference = Expression & { kind: "Identifier" | "Apply" | "Subexpression" }
99
108
 
100
109
  export const LOCAL_RESOLUTION = { kind: "Local" } as const;
101
110
 
111
+ export interface NullSelection {
112
+ node: Expression;
113
+ error: SanyError;
114
+ }
115
+
102
116
  export const selections = new WeakSet<Expression>();
103
117
  export const selectionErrors = new WeakMap<Expression, SelectionError>();
118
+ export const nullSelections = new WeakMap<Expression, NullSelection[]>();
119
+ const unresolvedExpressions = new WeakSet<Expression>();
104
120
 
105
121
  const renamedArities = new WeakMap<Expression, number>();
106
122
 
@@ -111,13 +127,20 @@ const isKey = (name: string) => {
111
127
  return index > 0 && index < name.length - 1;
112
128
  };
113
129
 
114
- const CORE_SYMBOLS: Symbols = new Map(
115
- ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2, kind: "Builtin" }]),
116
- );
130
+ const CORE_SYMBOLS: Symbols = new Map([
131
+ ...["~>", "-+->", "\\cdot", "\\X"].map((name): [string, ModuleSymbol] => [
132
+ name,
133
+ { key: name, arity: 2, kind: "Builtin" },
134
+ ]),
135
+ ["'", { key: "'", arity: 1, kind: "Builtin" }],
136
+ ]);
117
137
 
118
138
  export const isBefore = (left: SourceLocation, right: SourceLocation) =>
119
139
  left.line < right.line || (left.line === right.line && left.column < right.column);
120
140
 
141
+ const compareLocations = (left: SourceLocation, right: SourceLocation) =>
142
+ isBefore(left, right) ? -1 : isBefore(right, left) ? 1 : 0;
143
+
121
144
  export const getArity = (definition: Definition) =>
122
145
  definition.kind === "Operator" ? definition.params.length : 0;
123
146
 
@@ -157,7 +180,7 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
157
180
  if (current.kind === "Builtin") {
158
181
  unit.errors.push({
159
182
  location,
160
- message: `Symbol ${name} is a built-in operator, and cannot be redefined.`,
183
+ message: `Symbol ${resolveSynonym(name)} is a built-in operator, and cannot be redefined.`,
161
184
  });
162
185
  } else if (
163
186
  added.kind === "Parameter" ||
@@ -166,12 +189,12 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
166
189
  ) {
167
190
  unit.errors.push({
168
191
  location,
169
- message: `Multiply-defined symbol '${name}': this definition or declaration conflicts \nwith the one at ${existing}.`,
192
+ message: `Multiply-defined symbol '${resolveSynonym(name)}': this definition or declaration conflicts \nwith the one at ${existing}.`,
170
193
  });
171
194
  } else {
172
195
  unit.warnings.push({
173
196
  location,
174
- message: `Multiple declarations or definitions for symbol ${name}. \nThis duplicates the one at ${existing}.`,
197
+ message: `Multiple declarations or definitions for symbol ${resolveSynonym(name)}. \nThis duplicates the one at ${existing}.`,
175
198
  });
176
199
  }
177
200
  return false;
@@ -233,23 +256,35 @@ const getVisibleDefinition = (name: string, unit: Unit) => {
233
256
  const isVisible =
234
257
  definition !== undefined &&
235
258
  (definition === unit.self
236
- ? definition.kind === "Function" || definition.isRecursive
237
- : definition.isRecursive || isBefore(definition.location, unit.location));
259
+ ? definition.isRecursive
260
+ : definition.isRecursive
261
+ ? getModuleBinding(name, unit, undefined) !== undefined
262
+ : isBefore(definition.location, unit.location));
238
263
  return isVisible ? definition : undefined;
239
264
  };
240
265
 
241
266
  const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
242
267
  const definition = getVisibleDefinition(name, unit);
243
- return definition
244
- ? {
245
- key: unit.getKey(definition),
246
- arity: getArity(definition),
247
- params: getParamArities(definition),
248
- kind: "Definition",
249
- }
250
- : unit.imported.get(name);
268
+ if (definition) {
269
+ const declared = definition.isRecursive ? unit.bindings.get(name) : undefined;
270
+ return {
271
+ key: unit.getKey(definition),
272
+ arity: declared?.arity ?? getArity(definition),
273
+ params: declared?.params ?? getParamArities(definition),
274
+ kind: "Definition",
275
+ };
276
+ }
277
+ const binding = getModuleBinding(name, unit, undefined);
278
+ if (binding?.isPending) return { key: name, arity: binding.arity, kind: binding.kind };
279
+ return binding ? unit.imported.get(name) : undefined;
251
280
  };
252
281
 
282
+ const isFact = (name: string, unit: Unit) =>
283
+ unit.facts.has(name) || unit.bindings.get(name)?.kind === "Theorem";
284
+
285
+ const getGoal = (name: string, unit: Unit) =>
286
+ unit.bindings.get(name)?.kind === "Theorem" ? unit.goals.get(name) : undefined;
287
+
253
288
  const findBinding = (name: string, scope: LocalName | undefined, unit: Unit): Binding | undefined =>
254
289
  lookupLocal(scope, name) ?? findSymbol(name, unit);
255
290
 
@@ -271,12 +306,22 @@ const getSpelledNameRange = (
271
306
  };
272
307
 
273
308
  const getFixity = (expression: Expression) => {
274
- if (expression.kind !== "Apply") return undefined;
309
+ if (expression.kind !== "Apply" || expression.argumentsRange) return undefined;
275
310
  if (expression.args.length === 2) return "infix";
276
311
  if (expression.args.length !== 1) return undefined;
277
312
  return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
278
313
  };
279
314
 
315
+ const BUILTIN_LOCATION = "In module --TLA+ BUILTINS--";
316
+
317
+ const SELECTABLE_KINDS = new Set<SymbolKind>(["Definition", "Instance", "Theorem"]);
318
+
319
+ const reportUnselectable = (name: string, range: SourceRange, unit: Unit) =>
320
+ unit.errors.push({
321
+ location: formatRange(range),
322
+ message: `Cannot take subexpression of \`${resolveSynonym(name)}'.`,
323
+ });
324
+
280
325
  const isOperatorSymbol = (name: string) => !/^[\p{L}\d_]/u.test(name);
281
326
 
282
327
  const isStepName = (name: string) =>
@@ -519,10 +564,17 @@ const checkSelection = (
519
564
  state.isSufficesOpen = false;
520
565
  continue;
521
566
  }
522
- if (selector.kind !== "Operand") return;
523
- const operand = getOperandName(selector.operand);
567
+ if (selector.kind === "Colon") return;
568
+ const operand =
569
+ selector.kind === "Operand"
570
+ ? getOperandName(selector.operand)
571
+ : selector.kind === "At"
572
+ ? "@"
573
+ : "!(...)";
574
+ const getPosition = (count: number) =>
575
+ selector.kind === "Operand" ? getOperandIndex(selector.operand, count) : -1;
524
576
  if (state.isSufficesOpen) {
525
- if (getOperandIndex(selector.operand, 1) !== 0) {
577
+ if (getPosition(1) !== 0) {
526
578
  return report(
527
579
  index,
528
580
  node.kind === "AssumeProve"
@@ -547,6 +599,7 @@ const checkSelection = (
547
599
  return report(index, `Choosing operand \`${operand}' of subexpression with no operands.`);
548
600
  }
549
601
  const sets = getBinder(expression)?.sets;
602
+ if (sets && selector.kind !== "Operand") return;
550
603
  const operands =
551
604
  expression.kind === "Identifier"
552
605
  ? []
@@ -558,14 +611,14 @@ const checkSelection = (
558
611
  ? undefined
559
612
  : getOperands(expression);
560
613
  if (!operands) return;
561
- const position = getOperandIndex(selector.operand, operands.length);
614
+ const position = getPosition(operands.length);
562
615
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
563
616
  state.node = operands[position];
564
617
  state.isGoal = false;
565
618
  continue;
566
619
  }
567
620
  const clauses = [...node.assumptions, node.conclusion];
568
- const position = getOperandIndex(selector.operand, clauses.length);
621
+ const position = getPosition(clauses.length);
569
622
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
570
623
  if (isInScopeOfDeclaration(node, position) && (!state.isGoal || isOutOfScope)) {
571
624
  return report(index, `Accessing ASSUME/PROVE clause ${SCOPE_MESSAGE}`);
@@ -659,7 +712,7 @@ const checkReference = (
659
712
  const first = selectors[0];
660
713
  const goal =
661
714
  selectors.length > 1 && first.kind === "Name"
662
- ? (lookupLocal(scope, first.name)?.goal ?? unit.goals.get(first.name))
715
+ ? (lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit))
663
716
  : undefined;
664
717
  if (goal) checkSelection(expression, selectors, goal, scope, unit, isFact);
665
718
  return goal !== undefined;
@@ -697,29 +750,39 @@ const getSymbolArity = (
697
750
  return symbol.arity;
698
751
  }
699
752
  const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
700
- const isSelected =
701
- prefix !== "" &&
702
- (lookupLocal(scope, prefix) !== undefined ||
703
- findSymbol(prefix, unit) !== undefined ||
704
- unit.facts.has(prefix));
705
- if (isSelected) {
753
+ const selected =
754
+ prefix === "" ? undefined : (lookupLocal(scope, prefix) ?? findSymbol(prefix, unit));
755
+ if (selected && !SELECTABLE_KINDS.has(selected.kind)) {
756
+ reportUnselectable(
757
+ prefix,
758
+ (expression.kind !== "OperatorReference" && expression.selectorRanges?.[0]) ||
759
+ getSpelledNameRange(expression, name),
760
+ unit,
761
+ );
762
+ return undefined;
763
+ }
764
+ if (selected || (prefix !== "" && isFact(prefix, unit))) {
706
765
  return expression.kind === "Apply" ? expression.args.length : 0;
707
766
  }
708
- const spelling = (expression.kind === "Identifier" ? undefined : expression.spelling) ?? name;
709
- const range = formatRange(
710
- expression.kind === "Apply" && spelling === "-."
711
- ? getNameRange(location, "-")
712
- : getSpelledNameRange(expression, name),
713
- );
714
- if (!isOperatorSymbol(name) || isStepName(name)) {
715
- unit.errors.push({ location: range, message: `Unknown operator: \`${name}'.` });
767
+ const fixity = getFixity(expression);
768
+ const isOperatorApplication = expression.kind === "OperatorReference" || fixity !== undefined;
769
+ if (!isOperatorSymbol(name) || isStepName(name) || !isOperatorApplication) {
770
+ unit.errors.push({
771
+ location: formatRange(getSpelledNameRange(expression, name)),
772
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
773
+ });
716
774
  return undefined;
717
775
  }
776
+ const spelling = expression.spelling ?? name;
718
777
  unit.errors.push({
719
- location: range,
778
+ location: formatRange(
779
+ fixity === "prefix" && spelling === "-."
780
+ ? getNameRange(location, "-")
781
+ : getSpelledNameRange(expression, name),
782
+ ),
720
783
  message: `Could not find declaration or definition of symbol '${spelling}'.`,
721
784
  });
722
- const fixity = getFixity(expression);
785
+ if (fixity) unresolvedExpressions.add(expression);
723
786
  if (fixity && location.range) {
724
787
  unit.errors.push({
725
788
  location: formatRange(location.range),
@@ -774,15 +837,30 @@ const resolveDefinition = (
774
837
  const isDeclared = current?.isPending === true && recursive.has(current);
775
838
  if (current?.isPending && !isDeclared) {
776
839
  report(
777
- `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${name} defined at wrong LET/IN level.`,
840
+ `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${resolveSynonym(name)} defined at wrong LET/IN level.`,
778
841
  );
779
842
  } else if (current && !isDeclared) {
780
843
  report(
781
844
  definition.kind === "Function"
782
845
  ? `Function name \`${name}' already defined or declared.`
783
- : `Operator ${name} already defined or declared.`,
846
+ : `Operator ${resolveSynonym(name)} already defined or declared.`,
847
+ );
848
+ } else if (current && definition.kind === "Function" && current.arity > 0) {
849
+ report(`Function ${resolveSynonym(name)} has operator arguments in its RECURSIVE declaration.`);
850
+ } else if (
851
+ current &&
852
+ definition.kind === "Operator" &&
853
+ // Deviation from SANY: Generator#processOperator compares only the last parameter's arity with the RECURSIVE declaration's.
854
+ (current.arity !== definition.params.length ||
855
+ definition.params.some((param) => param.arity > 0))
856
+ ) {
857
+ report(
858
+ `Definition of ${resolveSynonym(name)} has different arity than its RECURSIVE declaration.`,
784
859
  );
785
860
  }
861
+ if (current && isDeclared && definition.kind === "Operator") {
862
+ current.params = getParamArities(definition);
863
+ }
786
864
  if (definition.kind === "Function") {
787
865
  resolveExpression(
788
866
  definition.body,
@@ -793,8 +871,10 @@ const resolveDefinition = (
793
871
  definition.isSelfReferential = isReferenced(definition.body, name);
794
872
  } else resolveExpression(definition.body, inner, unit);
795
873
  if (current && isDeclared) {
796
- current.isPending = false;
797
- current.range = range;
874
+ if (definition.kind === "Operator" || current.arity === 0) {
875
+ current.isPending = false;
876
+ current.range = range;
877
+ }
798
878
  return false;
799
879
  }
800
880
  return definition.kind === "Function"
@@ -812,10 +892,15 @@ const resolveDefinitions = (
812
892
  scope: LocalName | undefined,
813
893
  unit: Unit,
814
894
  instances: Instance[] = [],
895
+ declarations: Declaration[] = [],
815
896
  ) => {
816
897
  const recursive = new Set<Binding>();
817
898
  const declared = definitions
818
- .filter((definition) => definition.isRecursive)
899
+ .filter(
900
+ (definition) =>
901
+ definition.isRecursive &&
902
+ declarations.every((declaration) => declaration.name !== definition.name),
903
+ )
819
904
  .reduce<LocalName | undefined>((parent, definition) => {
820
905
  if (lookupLocal(parent, definition.name)?.isPending) return parent;
821
906
  const local: LocalName = {
@@ -829,20 +914,47 @@ const resolveDefinitions = (
829
914
  recursive.add(local);
830
915
  return local;
831
916
  }, scope);
832
- const pending = unit.isGenerated ? [] : [...instances];
833
- const resolveInstances = (
917
+ const declaredLocals = new Map<Declaration, LocalName | undefined>();
918
+ const bindDeclaration = (parent: LocalName | undefined, declaration: Declaration) => {
919
+ const binding: Binding = {
920
+ kind: "Definition",
921
+ arity: declaration.arity,
922
+ params: Array(declaration.arity).fill(0),
923
+ range: declaration.location.range,
924
+ };
925
+ const local: LocalName | undefined = isBindable(
926
+ declaration.name,
927
+ lookupLocal(parent, declaration.name) ??
928
+ getModuleBinding(declaration.name, unit, binding.range),
929
+ binding,
930
+ unit,
931
+ )
932
+ ? { ...binding, name: declaration.name, parent, isPending: true }
933
+ : undefined;
934
+ if (local) recursive.add(local);
935
+ declaredLocals.set(declaration, local);
936
+ return local ?? parent;
937
+ };
938
+ const pending = [...(unit.isGenerated ? [] : instances), ...declarations].toSorted(
939
+ (left, right) => compareLocations(left.location, right.location),
940
+ );
941
+ const resolvePending = (
834
942
  current: LocalName | undefined,
835
- isDue: (instance: Instance) => boolean,
943
+ isDue: (item: Instance | Declaration) => boolean,
836
944
  ) => {
837
- const count = pending.findIndex((instance) => !isDue(instance));
945
+ const count = pending.findIndex((item) => !isDue(item));
838
946
  return pending
839
947
  .splice(0, count === -1 ? pending.length : count)
840
- .reduce((parent, instance) => resolveLocalInstance(instance, parent, unit), current);
948
+ .reduce(
949
+ (parent, item) =>
950
+ "kind" in item ? resolveLocalInstance(item, parent, unit) : bindDeclaration(parent, item),
951
+ current,
952
+ );
841
953
  };
842
954
  const resolved = definitions.reduce<LocalName | undefined>((previous, definition) => {
843
955
  const current = isKey(definition.name)
844
956
  ? previous
845
- : resolveInstances(previous, (instance) => !isBefore(definition.location, instance.location));
957
+ : resolvePending(previous, (item) => !isBefore(definition.location, item.location));
846
958
  const local: LocalName = {
847
959
  name: definition.name,
848
960
  arity: getArity(definition),
@@ -862,7 +974,17 @@ const resolveDefinitions = (
862
974
  ? { ...local, params: getParamArities(definition) }
863
975
  : current;
864
976
  }, declared);
865
- return resolveInstances(resolved, () => true);
977
+ const resolvedScope = resolvePending(resolved, () => true);
978
+ declaredLocals.forEach((local, declaration) => {
979
+ const range = declaration.location.range;
980
+ if (range && !unit.isGenerated && (!local || local.isPending)) {
981
+ unit.errors.push({
982
+ location: formatRange(range),
983
+ message: `Symbol ${resolveSynonym(declaration.name)} declared in RECURSIVE statement but not defined.`,
984
+ });
985
+ }
986
+ });
987
+ return resolvedScope;
866
988
  };
867
989
 
868
990
  const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) => {
@@ -899,6 +1021,100 @@ const isInstanceArityReported = (
899
1021
  return true;
900
1022
  };
901
1023
 
1024
+ const isArgumentCountReported = (
1025
+ callee: Binding | undefined,
1026
+ name: string,
1027
+ count: number,
1028
+ range: SourceRange | undefined,
1029
+ unit: Unit,
1030
+ ) => {
1031
+ const params = callee?.kind === "Definition" ? callee.params : undefined;
1032
+ if (!callee || !params || params.length === callee.arity) return false;
1033
+ if (range) {
1034
+ unit.errors.push({
1035
+ location: formatRange(range),
1036
+ message: `Wrong number of arguments (${count}) given to operator '${resolveSynonym(name)}', \nwhich requires ${params.length} arguments.`,
1037
+ });
1038
+ }
1039
+ return true;
1040
+ };
1041
+
1042
+ const matchArgument = (
1043
+ arg: Expression,
1044
+ expected: number,
1045
+ index: number,
1046
+ operator: string,
1047
+ operatorRange: SourceRange | undefined,
1048
+ scope: LocalName | undefined,
1049
+ unit: Unit,
1050
+ ) => {
1051
+ const report = (range: SourceRange | undefined, message: string) => {
1052
+ if (range) unit.errors.push({ location: formatRange(range), message });
1053
+ };
1054
+ const range = arg.location.range;
1055
+ if (expected === 0) {
1056
+ // Deviation from SANY: SANY names its internal node kind here, where tla-ts words it as for a name.
1057
+ if (arg.kind === "Lambda" && arg.operator !== undefined) {
1058
+ report(range, `The operator ${resolveSynonym(arg.operator)} requires 1 arguments.`);
1059
+ } else if (arg.kind === "Lambda" && range) {
1060
+ report(range, "LAMBDA expression used where an expression is required.");
1061
+ } else if (arg.kind === "OperatorReference") {
1062
+ const argArity = getSymbolArity(arg, arg.operator, scope, unit);
1063
+ if (argArity !== undefined) {
1064
+ report(
1065
+ range,
1066
+ `The operator ${resolveSynonym(arg.operator)} requires ${argArity} arguments.`,
1067
+ );
1068
+ }
1069
+ } else resolveExpression(arg, scope, unit);
1070
+ return true;
1071
+ }
1072
+ if (arg.kind === "Lambda") {
1073
+ if (selections.has(arg)) resolveExpression(arg, scope, unit);
1074
+ else resolveLambda(arg, scope, unit);
1075
+ const isMatched = arg.params.length === expected;
1076
+ if (!isMatched && selections.has(arg)) {
1077
+ report(range, `Expected arity ${expected} but found operator of arity ${arg.params.length}.`);
1078
+ } else if (!isMatched && range && arg.operator === undefined) {
1079
+ report(
1080
+ operatorRange,
1081
+ `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
1082
+ );
1083
+ }
1084
+ return isMatched;
1085
+ }
1086
+ if (arg.kind === "Subexpression") {
1087
+ resolveExpression(arg, scope, unit);
1088
+ return true;
1089
+ }
1090
+ if (arg.kind === "Apply" && arg.argumentCounts?.at(-1) === 0) {
1091
+ const selectorIndex = arg.argumentCounts.findIndex((count) => count > 0);
1092
+ report(
1093
+ arg.selectorRanges?.[selectorIndex],
1094
+ `Selector \`${arg.operator.split("!")[selectorIndex]}' should not have argument(s).`,
1095
+ );
1096
+ return false;
1097
+ }
1098
+ if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
1099
+ report(
1100
+ range,
1101
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
1102
+ );
1103
+ return false;
1104
+ }
1105
+ const name = arg.kind === "Identifier" ? arg.name : arg.operator;
1106
+ const argParams = findBinding(name, scope, unit)?.params ?? [];
1107
+ const argArity = getSymbolArity(arg, name, scope, unit);
1108
+ if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
1109
+ report(
1110
+ getSpelledNameRange(arg, name),
1111
+ `Expected arity ${expected} but found operator of arity ${argArity}.`,
1112
+ );
1113
+ }
1114
+ // Deviation from SANY: OpDefNode#matchingOpArgOperand reads as many parameters as a RECURSIVE declaration gives and crashes when the definition has fewer.
1115
+ return argArity === expected && argParams.every((param) => param === 0);
1116
+ };
1117
+
902
1118
  const resolveApply = (
903
1119
  expression: Expression & { kind: "Apply" },
904
1120
  scope: LocalName | undefined,
@@ -912,90 +1128,42 @@ const resolveApply = (
912
1128
  if (arity !== expression.args.length) {
913
1129
  unit.errors.push({
914
1130
  location: formatRange(expression.argumentsRange ?? getSpelledNameRange(expression, operator)),
915
- message: `The operator ${operator} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
1131
+ message: `The operator ${resolveSynonym(operator)} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
916
1132
  });
917
1133
  return;
918
1134
  }
919
- const params = callee && (callee.kind === "Definition" ? callee.params : []);
1135
+ const params =
1136
+ callee && (callee.kind === "Definition" ? callee.params : expression.args.map(() => 0));
920
1137
  if (params === undefined) {
921
1138
  expression.args.forEach((arg) => resolveArgument(arg, scope, unit));
922
1139
  return;
923
1140
  }
924
- const report = (range: SourceRange | undefined, message: string) => {
925
- if (range) unit.errors.push({ location: formatRange(range), message });
926
- };
927
- expression.args
928
- .map((arg, index) => {
929
- const expected = params[index] ?? 0;
930
- const range = arg.location.range;
931
- if (expected === 0) {
932
- // Deviation from SANY: SANY fails here with an internal error; tla-ts words it as for a name.
933
- if (arg.kind === "Lambda" && arg.operator !== undefined) {
934
- report(range, `The operator ${arg.operator} requires 1 arguments.`);
935
- } else if (arg.kind === "Lambda" && range) {
936
- report(range, "LAMBDA expression used where an expression is required.");
937
- } else if (arg.kind === "OperatorReference") {
938
- const argArity = getSymbolArity(arg, arg.operator, scope, unit);
939
- if (argArity !== undefined) {
940
- report(range, `The operator ${arg.operator} requires ${argArity} arguments.`);
941
- }
942
- } else resolveExpression(arg, scope, unit);
943
- return true;
944
- }
945
- if (arg.kind === "Lambda") {
946
- resolveExpression(arg, scope, unit);
947
- const isMatched = arg.params.length === expected;
948
- if (!isMatched && selections.has(arg)) {
949
- report(
950
- range,
951
- `Expected arity ${expected} but found operator of arity ${arg.params.length}.`,
952
- );
953
- } else if (!isMatched && range && arg.operator === undefined) {
954
- report(
955
- expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator),
956
- `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
957
- );
958
- }
959
- return isMatched;
960
- }
961
- if (arg.kind === "Subexpression") {
962
- resolveExpression(arg, scope, unit);
963
- return true;
964
- }
965
- if (arg.kind === "Apply" && arg.argumentCounts?.at(-1) === 0) {
966
- const selectorIndex = arg.argumentCounts.findIndex((count) => count > 0);
967
- report(
968
- arg.selectorRanges?.[selectorIndex],
969
- `Selector \`${arg.operator.split("!")[selectorIndex]}' should not have argument(s).`,
970
- );
971
- return false;
972
- }
973
- if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
974
- report(
975
- range,
976
- `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
977
- );
978
- return false;
979
- }
980
- const name = arg.kind === "Identifier" ? arg.name : arg.operator;
981
- const argParams = findBinding(name, scope, unit)?.params ?? [];
982
- const argArity = getSymbolArity(arg, name, scope, unit);
983
- if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
984
- report(
985
- getSpelledNameRange(arg, name),
986
- `Expected arity ${expected} but found operator of arity ${argArity}.`,
987
- );
988
- }
989
- return argArity === expected && argParams.every((param) => param === 0);
990
- })
991
- .forEach((isMatched, index) => {
992
- if (!isMatched) {
993
- report(
994
- expression.location.range,
995
- `Argument number ${index + 1} to operator '${operator}' \nshould be a ${params[index]}-parameter operator.`,
996
- );
997
- }
998
- });
1141
+ const operatorRange =
1142
+ expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator);
1143
+ const matches = expression.args
1144
+ .slice(0, params.length)
1145
+ .map((arg, index) =>
1146
+ matchArgument(arg, params[index], index, operator, operatorRange, scope, unit),
1147
+ );
1148
+ if (
1149
+ isArgumentCountReported(
1150
+ callee,
1151
+ operator,
1152
+ expression.args.length,
1153
+ expression.location.range,
1154
+ unit,
1155
+ )
1156
+ ) {
1157
+ return;
1158
+ }
1159
+ matches.forEach((isMatched, index) => {
1160
+ if (!isMatched && expression.location.range) {
1161
+ unit.errors.push({
1162
+ location: formatRange(expression.location.range),
1163
+ message: `Argument number ${index + 1} to operator '${operator}' \nshould be a ${params[index]}-parameter operator.`,
1164
+ });
1165
+ }
1166
+ });
999
1167
  };
1000
1168
 
1001
1169
  const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
@@ -1006,18 +1174,48 @@ const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Un
1006
1174
  const isSelectionReported = (expression: Expression, scope: LocalName | undefined, unit: Unit) => {
1007
1175
  const failed = selectionErrors.get(expression);
1008
1176
  if (!failed) return false;
1009
- failed.args.forEach((arg) => resolveArgument(arg, scope, unit));
1177
+ failed.applications.forEach((application) =>
1178
+ application.args.forEach((arg, index) =>
1179
+ matchArgument(
1180
+ arg,
1181
+ application.params[index],
1182
+ index,
1183
+ application.operator,
1184
+ application.range,
1185
+ scope,
1186
+ unit,
1187
+ ),
1188
+ ),
1189
+ );
1010
1190
  unit.errors.push(failed.error);
1011
1191
  return true;
1012
1192
  };
1013
1193
 
1194
+ const resolveLambda = (
1195
+ expression: Expression & { kind: "Lambda" },
1196
+ scope: LocalName | undefined,
1197
+ unit: Unit,
1198
+ ) =>
1199
+ resolveExpression(
1200
+ expression.body,
1201
+ bindNames(scope, expression.params, expression.paramRanges, unit),
1202
+ {
1203
+ ...unit,
1204
+ labelParams: [...unit.labelParams, ...expression.params],
1205
+ },
1206
+ );
1207
+
1014
1208
  const resolveExpression = (
1015
1209
  expression: Expression,
1016
1210
  scope: LocalName | undefined,
1017
1211
  unit: Unit,
1018
1212
  ): void => {
1019
1213
  if (selections.has(expression) && !unit.isGenerated) {
1020
- resolveExpression(expression, scope, { ...unit, isGenerated: true });
1214
+ const failed = nullSelections
1215
+ .get(expression)
1216
+ ?.find((selection) => unresolvedExpressions.has(selection.node));
1217
+ if (failed) unit.errors.push(failed.error);
1218
+ else resolveExpression(expression, scope, { ...unit, isGenerated: true });
1021
1219
  return;
1022
1220
  }
1023
1221
  const resolveAll = (expressions: Expression[]) =>
@@ -1030,16 +1228,31 @@ const resolveExpression = (
1030
1228
  case "Number":
1031
1229
  case "Decimal":
1032
1230
  case "String":
1231
+ return;
1033
1232
  case "ExceptAt":
1233
+ if (!unit.isInExcept && expression.location.range) {
1234
+ unit.errors.push({
1235
+ location: formatRange(expression.location.range),
1236
+ message: "@ used where its meaning is not defined.",
1237
+ });
1238
+ }
1034
1239
  return;
1035
1240
  case "Identifier": {
1036
1241
  if (isInstanceArityReported(expression, scope, unit)) return;
1037
1242
  const name = expression.name;
1038
1243
  const arity = getSymbolArity(expression, name, scope, unit);
1039
- if (arity !== undefined && arity > 0) {
1244
+ if (arity === 0) {
1245
+ isArgumentCountReported(
1246
+ findBinding(name, scope, unit),
1247
+ name,
1248
+ 0,
1249
+ getSpelledNameRange(expression, name),
1250
+ unit,
1251
+ );
1252
+ } else if (arity !== undefined) {
1040
1253
  unit.errors.push({
1041
1254
  location: formatRange(getSpelledNameRange(expression, name)),
1042
- message: `The operator ${name} requires ${arity} arguments.`,
1255
+ message: `The operator ${resolveSynonym(name)} requires ${arity} arguments.`,
1043
1256
  });
1044
1257
  }
1045
1258
  return;
@@ -1051,11 +1264,13 @@ const resolveExpression = (
1051
1264
  resolveApply(expression, scope, unit);
1052
1265
  return;
1053
1266
  case "Lambda":
1054
- resolveExpression(
1055
- expression.body,
1056
- bindNames(scope, expression.params, expression.paramRanges, unit),
1057
- bindLabelParams(expression.params),
1058
- );
1267
+ if (selections.has(expression)) resolveLambda(expression, scope, unit);
1268
+ else if (expression.location.range) {
1269
+ unit.errors.push({
1270
+ location: formatRange(expression.location.range),
1271
+ message: "LAMBDA expression used where an expression is required.",
1272
+ });
1273
+ }
1059
1274
  return;
1060
1275
  case "And":
1061
1276
  case "Or":
@@ -1078,7 +1293,13 @@ const resolveExpression = (
1078
1293
  case "Let":
1079
1294
  resolveExpression(
1080
1295
  expression.body,
1081
- resolveDefinitions(expression.definitions, scope, unit, expression.instances),
1296
+ resolveDefinitions(
1297
+ expression.definitions,
1298
+ scope,
1299
+ unit,
1300
+ expression.instances,
1301
+ expression.recursive,
1302
+ ),
1082
1303
  unit,
1083
1304
  );
1084
1305
  return;
@@ -1173,13 +1394,64 @@ const resolveExpression = (
1173
1394
  expression.selectors
1174
1395
  .flatMap((selector) => ("args" in selector ? selector.args : []))
1175
1396
  .forEach((arg) => resolveArgument(arg, scope, unit));
1176
- checkReference(expression, scope, unit, false);
1397
+ if (checkReference(expression, scope, unit, false)) return;
1398
+ const head = expression.selectors[0];
1399
+ const range = expression.selectorRanges?.[0];
1400
+ const nameCount = expression.selectors.findIndex((selector) => selector.kind !== "Name");
1401
+ const names = expression.selectors
1402
+ .slice(0, nameCount)
1403
+ .flatMap((selector) => (selector.kind === "Name" ? [selector.name] : []));
1404
+ const symbolIndex = names.findIndex(
1405
+ (_name, index) => index > 0 && findSymbol(names.slice(0, index + 1).join("!"), unit),
1406
+ );
1407
+ const isInstance =
1408
+ names.length > 1 &&
1409
+ (lookupLocal(scope, names[0]) ?? getModuleBinding(names[0], unit, undefined))?.kind ===
1410
+ "Instance";
1411
+ const lastRange = expression.selectorRanges?.[nameCount - 1];
1412
+ if (isInstance && symbolIndex === -1 && range && lastRange) {
1413
+ unit.errors.push({
1414
+ location: formatRange({ module: range.module, start: range.start, end: lastRange.end }),
1415
+ message: `Unknown operator: \`${resolveSynonym(names.join("!"))}'.`,
1416
+ });
1417
+ return;
1418
+ }
1419
+ const name = names.slice(0, symbolIndex + 1).join("!");
1420
+ const symbol = symbolIndex > 0 ? findSymbol(name, unit) : undefined;
1421
+ const argumentCount = expression.selectors
1422
+ .slice(0, symbolIndex + 1)
1423
+ .flatMap((selector) => ("args" in selector ? selector.args : [])).length;
1424
+ const argumentRange = expression.argumentRanges?.[symbolIndex] ?? expression.location.range;
1425
+ if (symbol && symbol.arity !== argumentCount && argumentRange) {
1426
+ unit.errors.push({
1427
+ location: formatRange(argumentRange),
1428
+ message: `The operator ${resolveSynonym(name)} requires ${symbol.arity} arguments.`,
1429
+ });
1430
+ return;
1431
+ }
1432
+ if (head.kind !== "Name" || expression.selectors[1].kind === "Name" || !range) return;
1433
+ const binding = lookupLocal(scope, head.name) ?? findSymbol(head.name, unit);
1434
+ if ((binding === undefined && !isFact(head.name, unit)) || binding?.kind === "Instance") {
1435
+ unit.errors.push({
1436
+ location: formatRange(range),
1437
+ message: `Unknown operator: \`${resolveSynonym(head.name)}'.`,
1438
+ });
1439
+ } else if (binding && !SELECTABLE_KINDS.has(binding.kind)) {
1440
+ reportUnselectable(head.name, range, unit);
1441
+ }
1177
1442
  }
1178
1443
  }
1179
1444
  };
1180
1445
 
1181
1446
  const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) =>
1182
1447
  facts.forEach((fact) => {
1448
+ if (fact.kind === "ExceptAt" && fact.location.range) {
1449
+ unit.errors.push({
1450
+ location: formatRange(fact.location.range),
1451
+ message: "Unknown operator: `@'.",
1452
+ });
1453
+ return;
1454
+ }
1183
1455
  if (
1184
1456
  fact.kind === "ModuleFact" ||
1185
1457
  isInstanceArityReported(fact, scope, unit) ||
@@ -1194,8 +1466,89 @@ const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) =>
1194
1466
  location: formatRange(getSpelledNameRange(fact, name)),
1195
1467
  message: "Step number of non-fact used as a fact",
1196
1468
  });
1197
- } else if (!unit.facts.has(name)) resolveExpression(fact, scope, unit);
1469
+ } else if (!isFact(name, unit)) resolveExpression(fact, scope, unit);
1470
+ });
1471
+
1472
+ const isDefinitionEntry = (def: Fact, scope: LocalName | undefined, unit: Unit) => {
1473
+ const range = def.location.range;
1474
+ const name =
1475
+ def.kind === "Identifier" ? def.name : def.kind === "OperatorReference" ? def.operator : "";
1476
+ if (name === "" || !range) return true;
1477
+ const binding =
1478
+ lookupLocal(scope, name) ?? findSymbol(name, unit) ?? getModuleBinding(name, unit, range);
1479
+ if (binding === undefined && (isFact(name, unit) || isStepName(name))) return true;
1480
+ if (binding === undefined) {
1481
+ unit.errors.push({
1482
+ location: formatRange(range),
1483
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
1484
+ });
1485
+ }
1486
+ if (binding && SELECTABLE_KINDS.has(binding.kind) && !isStepName(name)) return true;
1487
+ unit.errors.push({
1488
+ location: formatRange(range),
1489
+ message: "DEF clause entry should describe a defined operator.",
1490
+ });
1491
+ return false;
1492
+ };
1493
+
1494
+ const getHiddenExpressionLocation = (fact: Fact, scope: LocalName | undefined, unit: Unit) => {
1495
+ const range = fact.location.range && formatRange(fact.location.range);
1496
+ if (fact.kind === "ModuleFact" || selections.has(fact)) return undefined;
1497
+ if (selectionErrors.has(fact) || fact.kind === "ExceptAt") return BUILTIN_LOCATION;
1498
+ switch (fact.kind) {
1499
+ case "Number":
1500
+ case "String":
1501
+ case "Decimal":
1502
+ case "Let":
1503
+ case "Label":
1504
+ return undefined;
1505
+ case "Identifier":
1506
+ case "Apply":
1507
+ case "Subexpression": {
1508
+ const first = getSelectors(fact)[0];
1509
+ if (fact.kind === "Subexpression" || first.kind !== "Name") return undefined;
1510
+ const name = fact.kind === "Identifier" ? fact.name : fact.operator;
1511
+ const goal = lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit);
1512
+ if (isFact(name, unit) || goal || (isStepName(name) && lookupLocal(scope, name))) {
1513
+ return undefined;
1514
+ }
1515
+ const binding = findBinding(name, scope, unit);
1516
+ const count = fact.kind === "Apply" ? fact.args.length : 0;
1517
+ return binding?.arity === count ? range : BUILTIN_LOCATION;
1518
+ }
1519
+ default:
1520
+ return range;
1521
+ }
1522
+ };
1523
+
1524
+ const checkUseOrHide = (
1525
+ statement: UseOrHide | Extract<Proof, { kind: "By" }>,
1526
+ scope: LocalName | undefined,
1527
+ unit: Unit,
1528
+ ) => {
1529
+ const hidden =
1530
+ statement.kind === "Hide"
1531
+ ? statement.facts.map((fact) => getHiddenExpressionLocation(fact, scope, unit))
1532
+ : [];
1533
+ checkFacts(statement.facts, scope, unit);
1534
+ const defCount = statement.defs.filter((def) => isDefinitionEntry(def, scope, unit)).length;
1535
+ hidden.forEach((location) => {
1536
+ if (location) {
1537
+ unit.errors.push({
1538
+ location,
1539
+ message:
1540
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1541
+ });
1542
+ }
1198
1543
  });
1544
+ const range = statement.location.range;
1545
+ if (statement.facts.length + defCount === 0 && range) {
1546
+ unit.errors.push({
1547
+ location: formatRange(range),
1548
+ message: statement.kind === "By" ? "Empty BY" : "Empty USE or HIDE statement.",
1549
+ });
1550
+ }
1551
+ };
1199
1552
 
1200
1553
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
1201
1554
  if (symbol.set) resolveExpression(symbol.set, scope, unit);
@@ -1244,7 +1597,7 @@ const resolveStatement = (
1244
1597
 
1245
1598
  const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, outer: Unit) => {
1246
1599
  const unit = outer.hasLabelScope ? { ...outer, hasLabelScope: false } : outer;
1247
- if (proof?.kind === "By") checkFacts(proof.facts, scope, unit);
1600
+ if (proof?.kind === "By") checkUseOrHide(proof, scope, unit);
1248
1601
  if (proof?.kind !== "Steps") return;
1249
1602
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
1250
1603
  };
@@ -1293,7 +1646,7 @@ const resolveStep = (
1293
1646
  }
1294
1647
  case "Use":
1295
1648
  case "Hide":
1296
- checkFacts(body.facts, scope, unit);
1649
+ checkUseOrHide(body, scope, unit);
1297
1650
  return bindNonFactStep(scope);
1298
1651
  case "Instance":
1299
1652
  return bindNonFactStep(resolveLocalInstance(body, scope, stepUnit));
@@ -1416,18 +1769,72 @@ const checkSubstitutions = (
1416
1769
  (parent, param) => ({ name: param.name, arity: param.arity, kind: "Parameter", parent }),
1417
1770
  outer,
1418
1771
  );
1772
+ const reportArity = (declaration: Declaration, location: string) =>
1773
+ unit.errors.push({
1774
+ location,
1775
+ message: `An operator must be substituted for symbol '${resolveSynonym(declaration.name)}', and it must have arity ${declaration.arity}.`,
1776
+ });
1419
1777
  const resolveSubstitute = (declaration: Declaration, expression: Expression) => {
1420
- if (declaration.arity === 0 || expression.kind !== "Identifier") {
1778
+ const range = expression.location.range;
1779
+ if (declaration.arity === 0) {
1421
1780
  resolveExpression(expression, scope, unit);
1422
1781
  return;
1423
1782
  }
1783
+ if (expression.kind === "Lambda") {
1784
+ resolveLambda(expression, scope, unit);
1785
+ if (expression.params.length !== declaration.arity && range) {
1786
+ reportArity(declaration, formatRange(range));
1787
+ }
1788
+ return;
1789
+ }
1790
+ if (expression.kind === "OperatorReference") {
1791
+ const arity = getSymbolArity(expression, expression.operator, scope, unit);
1792
+ if (arity === undefined) reportArity(declaration, BUILTIN_LOCATION);
1793
+ else if (arity !== declaration.arity && range) reportArity(declaration, formatRange(range));
1794
+ return;
1795
+ }
1796
+ if (expression.kind !== "Identifier") {
1797
+ if (range) {
1798
+ unit.errors.push({
1799
+ location: formatRange(range),
1800
+ message: `Arity ${declaration.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${resolveSynonym(declaration.name)}'.`,
1801
+ });
1802
+ }
1803
+ reportArity(declaration, BUILTIN_LOCATION);
1804
+ return;
1805
+ }
1424
1806
  const arity = getSymbolArity(expression, expression.name, scope, unit);
1425
1807
  if (arity !== undefined && arity !== declaration.arity) {
1426
- throw new TlaSyntaxError(
1427
- `An operator must be substituted for symbol '${declaration.name}', and it must have arity ${declaration.arity} in the instance of ${instance.module} at line ${instance.location.line}, column ${instance.location.column}`,
1428
- );
1808
+ unit.errors.push({
1809
+ location: formatRange(getSpelledNameRange(expression, expression.name)),
1810
+ message: `Expected arity ${declaration.arity} but found operator of arity ${arity}.`,
1811
+ });
1429
1812
  }
1813
+ if (arity !== declaration.arity) reportArity(declaration, BUILTIN_LOCATION);
1430
1814
  };
1815
+ const instanceRange = instance.location.range;
1816
+ const isFound = (declaration: Declaration) =>
1817
+ lookupLocal(scope, declaration.name) !== undefined ||
1818
+ findSymbol(declaration.name, unit) !== undefined;
1819
+ const implicit = declarations.filter(isFound).map((declaration) => {
1820
+ const expression: Expression & { kind: "Identifier" } = {
1821
+ kind: "Identifier",
1822
+ name: declaration.name,
1823
+ location: instance.location,
1824
+ };
1825
+ return { declaration, expression };
1826
+ });
1827
+ implicit
1828
+ .filter((item) => item.declaration.arity === 0)
1829
+ .forEach((item) => {
1830
+ const arity = getSymbolArity(item.expression, item.declaration.name, scope, unit);
1831
+ if (arity && instanceRange) {
1832
+ unit.errors.push({
1833
+ location: formatRange(instanceRange),
1834
+ message: `Wrong number of arguments (0) given to operator '${resolveSynonym(item.declaration.name)}', \nwhich requires ${arity} arguments.`,
1835
+ });
1836
+ }
1837
+ });
1431
1838
  const substitutions = new Map<string, Expression>();
1432
1839
  instance.substitutions.forEach((substitution) => {
1433
1840
  const name = substitution.name;
@@ -1450,30 +1857,29 @@ const checkSubstitutions = (
1450
1857
  });
1451
1858
  }
1452
1859
  });
1453
- const implicit = declarations.filter((declaration) => !substitutions.has(declaration.name));
1454
- const isMissing = (declaration: Declaration) =>
1455
- !lookupLocal(scope, declaration.name) && !findSymbol(declaration.name, unit);
1456
1860
  implicit
1457
- .filter((declaration) => !isMissing(declaration))
1861
+ .filter((item) => !substitutions.has(item.declaration.name))
1862
+ .forEach((item) => {
1863
+ const arity =
1864
+ item.declaration.arity === 0
1865
+ ? 0
1866
+ : getSymbolArity(item.expression, item.declaration.name, scope, unit);
1867
+ if (arity !== item.declaration.arity && instanceRange) {
1868
+ reportArity(item.declaration, formatRange(instanceRange));
1869
+ }
1870
+ substitutions.set(item.declaration.name, item.expression);
1871
+ });
1872
+ declarations
1873
+ .filter((declaration) => !substitutions.has(declaration.name))
1458
1874
  .forEach((declaration) => {
1459
- const expression: Expression = {
1460
- kind: "Identifier",
1461
- name: declaration.name,
1462
- location: instance.location,
1463
- };
1464
- resolveSubstitute(declaration, expression);
1465
- substitutions.set(declaration.name, expression);
1875
+ const declared = declaration.location.range;
1876
+ if (instanceRange && declared) {
1877
+ unit.errors.push({
1878
+ location: formatRange(instanceRange),
1879
+ message: `Substitution missing for symbol ${resolveSynonym(declaration.name)} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
1880
+ });
1881
+ }
1466
1882
  });
1467
- implicit.filter(isMissing).forEach((declaration) => {
1468
- const range = instance.location.range;
1469
- const declared = declaration.location.range;
1470
- if (range && declared) {
1471
- unit.errors.push({
1472
- location: formatRange(range),
1473
- message: `Substitution missing for symbol ${declaration.name} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
1474
- });
1475
- }
1476
- });
1477
1883
  return substitutions;
1478
1884
  };
1479
1885
 
@@ -1481,7 +1887,7 @@ const resolveInstance = (instance: Instance, scope: LocalName | undefined, unit:
1481
1887
  const instanced = unit.getInstance(instance);
1482
1888
  checkSubstitutions(instance, instanced.declarations, instanced.instancer, scope, unit);
1483
1889
  return [...instanced.symbols].reduce(
1484
- (parent, [name, symbol]) => bindName(parent, name, symbol, unit),
1890
+ (parent, entry) => bindName(parent, entry[0], entry[1], unit),
1485
1891
  scope,
1486
1892
  );
1487
1893
  };
@@ -1493,6 +1899,12 @@ export const resolveSubstitutions = (
1493
1899
  unit: ModuleUnit,
1494
1900
  ) => {
1495
1901
  const imported = createSymbols(module, unit.imported);
1902
+ const positions = new Map(
1903
+ [...module.constants, ...module.variables].map((declaration) => [
1904
+ declaration.name,
1905
+ declaration.location,
1906
+ ]),
1907
+ );
1496
1908
  const report: ModuleReport = { location: instance.location, errors: [], warnings: [] };
1497
1909
  unit.reports.push(report);
1498
1910
  return checkSubstitutions(instance, declarations, module.name, undefined, {
@@ -1505,7 +1917,10 @@ export const resolveSubstitutions = (
1505
1917
  facts: new Set(),
1506
1918
  goals: new Map(),
1507
1919
  bindings: new Map(
1508
- [...imported].map(([name, symbol]) => [name, { ...symbol, position: MODULE_START }]),
1920
+ [...imported].map((entry) => [
1921
+ entry[0],
1922
+ { ...entry[1], position: positions.get(entry[0]) ?? MODULE_START },
1923
+ ]),
1509
1924
  ),
1510
1925
  errors: report.errors,
1511
1926
  warnings: report.warnings,
@@ -1535,13 +1950,7 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1535
1950
  }
1536
1951
  };
1537
1952
  units
1538
- .toSorted((left, right) =>
1539
- isBefore(left.location, right.location)
1540
- ? -1
1541
- : isBefore(right.location, left.location)
1542
- ? 1
1543
- : 0,
1544
- )
1953
+ .toSorted((left, right) => compareLocations(left.location, right.location))
1545
1954
  .forEach((unit) => {
1546
1955
  const reported: SanyError[] = [];
1547
1956
  const warned: SanyError[] = [];
@@ -1561,10 +1970,6 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1561
1970
 
1562
1971
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
1563
1972
  const symbols = createSymbols(module, unit.imported);
1564
- const facts = new Set([
1565
- ...unit.facts,
1566
- ...[...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
1567
- ]);
1568
1973
  const goals = new Map(
1569
1974
  module.theorems.flatMap((theorem): [string, Goal][] =>
1570
1975
  theorem.name !== undefined && theorem.statement.kind === "AssumeProve"
@@ -1573,9 +1978,9 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1573
1978
  ),
1574
1979
  );
1575
1980
  const bindings = new Map<string, ModuleBinding>(
1576
- [...CORE_SYMBOLS, ...unit.bound].map(([name, symbol]) => [
1577
- name,
1578
- { ...symbol, position: MODULE_START },
1981
+ [...CORE_SYMBOLS, ...unit.bound].map((entry) => [
1982
+ entry[0],
1983
+ { ...entry[1], position: MODULE_START },
1579
1984
  ]),
1580
1985
  );
1581
1986
  const recursive = new Set<Binding>();
@@ -1595,7 +2000,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1595
2000
  getKey: unit.getKey,
1596
2001
  location,
1597
2002
  self,
1598
- facts,
2003
+ facts: unit.facts,
1599
2004
  goals,
1600
2005
  bindings,
1601
2006
  errors,
@@ -1620,6 +2025,37 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1620
2025
  );
1621
2026
  return collectSemanticErrors(
1622
2027
  [
2028
+ ...module.units.flatMap((item): SemanticUnit[] => {
2029
+ const section =
2030
+ item.kind === "Variables"
2031
+ ? { type: "A VARIABLE declaration", location: item.location }
2032
+ : item.kind === "Constants"
2033
+ ? { type: "A declaration", location: item.location }
2034
+ : item.kind === "Module"
2035
+ ? { type: "A MODULE ", location: item.module.location }
2036
+ : item.kind === "Theorem"
2037
+ ? { type: "A THEOREM", location: item.theorem.location }
2038
+ : item.kind === "Assumption"
2039
+ ? { type: "An ASSUME", location: item.assumption.location }
2040
+ : item.kind === "Use"
2041
+ ? { type: "A USE or HIDE", location: item.use.location }
2042
+ : undefined;
2043
+ const range = section?.location.range;
2044
+ if (!section || !range) return [];
2045
+ return [
2046
+ {
2047
+ location: section.location,
2048
+ check: (errors) => {
2049
+ if (declarations.some((declared) => declared.binding?.isPending)) {
2050
+ errors.push({
2051
+ location: formatRange(range),
2052
+ message: `${section.type} may not appear within a recursive definition section.`,
2053
+ });
2054
+ }
2055
+ },
2056
+ },
2057
+ ];
2058
+ }),
1623
2059
  ...unit.reports.map((report) => ({
1624
2060
  location: report.location,
1625
2061
  check: (errors: SanyError[], warnings: SanyError[]) => {
@@ -1636,6 +2072,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1636
2072
  const binding: ModuleBinding = {
1637
2073
  kind: "Definition",
1638
2074
  arity: declaration.arity,
2075
+ params: Array(declaration.arity).fill(0),
1639
2076
  range: declaration.location.range,
1640
2077
  position: declaration.location,
1641
2078
  isPending: true,
@@ -1701,7 +2138,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1701
2138
  ),
1702
2139
  ...module.uses.map((use) =>
1703
2140
  createCheck(use.location, undefined, false, (inner) =>
1704
- checkFacts(use.facts, undefined, inner),
2141
+ checkUseOrHide(use, undefined, inner),
1705
2142
  ),
1706
2143
  ),
1707
2144
  {
@@ -1712,7 +2149,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1712
2149
  if (range && (!item.binding || item.binding.isPending)) {
1713
2150
  errors.push({
1714
2151
  location: formatRange(range),
1715
- message: `Symbol ${item.declaration.name} declared in RECURSIVE statement but not defined.`,
2152
+ message: `Symbol ${resolveSynonym(item.declaration.name)} declared in RECURSIVE statement but not defined.`,
1716
2153
  });
1717
2154
  }
1718
2155
  }),