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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/dist/compile.cjs +3 -3
  2. package/dist/compile.js +1 -1
  3. package/dist/deciders.cjs +36 -36
  4. package/dist/deciders.js +53 -53
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.cts +18 -4
  7. package/dist/index.d.ts +18 -4
  8. package/dist/index.js +1 -1
  9. package/dist/parallel-worker.cjs +1 -1
  10. package/dist/parallel-worker.js +1 -1
  11. package/dist/prove-worker.cjs +1 -1
  12. package/dist/prove-worker.js +1 -1
  13. package/dist/prove.cjs +56 -56
  14. package/dist/prove.js +78 -78
  15. package/dist/run.cjs +40 -44
  16. package/dist/run.js +42 -46
  17. package/dist/tlapm.cjs +1 -1
  18. package/dist/tlapm.js +2 -2
  19. package/dist/transfer.cjs +49 -44
  20. package/dist/transfer.js +48 -43
  21. package/dist/worker.cjs +7 -7
  22. package/dist/worker.js +7 -7
  23. package/package.json +1 -1
  24. package/src/ast.ts +14 -2
  25. package/src/bags.ts +50 -29
  26. package/src/builtins.ts +4 -3
  27. package/src/check-failure.ts +13 -11
  28. package/src/check-trace.ts +116 -64
  29. package/src/check.ts +516 -280
  30. package/src/cli/runtime-invariants.ts +20 -56
  31. package/src/cli/tlc-arguments.ts +2 -2
  32. package/src/cli/tlc-output.ts +18 -4
  33. package/src/cli/tlc.ts +18 -12
  34. package/src/cli/xml-exporter.ts +1 -1
  35. package/src/codegen.ts +23 -10
  36. package/src/coverage.ts +190 -1
  37. package/src/dependencies.ts +68 -15
  38. package/src/dfid.ts +101 -36
  39. package/src/environment.ts +123 -38
  40. package/src/errors.ts +7 -0
  41. package/src/evaluate.ts +370 -99
  42. package/src/exit-codes.ts +28 -14
  43. package/src/instances.ts +135 -11
  44. package/src/java-hash.ts +14 -0
  45. package/src/java-overrides.ts +2 -2
  46. package/src/levels.ts +675 -236
  47. package/src/lexer.ts +12 -2
  48. package/src/liveness-checker.ts +179 -60
  49. package/src/liveness.ts +51 -10
  50. package/src/obligations/index.ts +1 -1
  51. package/src/obligations/normalize.ts +1 -4
  52. package/src/obligations/printer.ts +5 -5
  53. package/src/obligations/source.ts +2 -0
  54. package/src/parallel-worker.ts +8 -2
  55. package/src/parallel.ts +5 -0
  56. package/src/parser.ts +180 -149
  57. package/src/prover/isabelle/isar/attrib.ts +4 -4
  58. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  59. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  60. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  61. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  62. package/src/prover/isabelle/pure/term.ts +3 -3
  63. package/src/prover/prep/md5.ts +26 -29
  64. package/src/prover/smt/rewrite.ts +2 -7
  65. package/src/prover/smt/simplify.ts +1 -1
  66. package/src/prover/smt/solver/arith-rewriter.ts +11 -3
  67. package/src/prover/smt/solver/array-rewriter.ts +12 -2
  68. package/src/prover/smt/solver/asserted-formulas.ts +171 -58
  69. package/src/prover/smt/solver/ast-lt.ts +1 -1
  70. package/src/prover/smt/solver/ast.ts +66 -14
  71. package/src/prover/smt/solver/auf-solver.ts +23 -12
  72. package/src/prover/smt/solver/bit-blast-tactic.ts +27 -1
  73. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  74. package/src/prover/smt/solver/bound-simplifier.ts +11 -13
  75. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  76. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  77. package/src/prover/smt/solver/card2bv.ts +35 -18
  78. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +39 -24
  79. package/src/prover/smt/solver/context.ts +84 -15
  80. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  81. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  82. package/src/prover/smt/solver/dependent-expr-state.ts +28 -16
  83. package/src/prover/smt/solver/diff-neq.ts +1 -2
  84. package/src/prover/smt/solver/dt2bv-tactic.ts +57 -21
  85. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  86. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  87. package/src/prover/smt/solver/elim-uncnstr.ts +5 -8
  88. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  89. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  90. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  91. package/src/prover/smt/solver/euf/egraph.ts +4 -11
  92. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  93. package/src/prover/smt/solver/euf/mam.ts +1 -5
  94. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  95. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  96. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  97. package/src/prover/smt/solver/factor.ts +36 -14
  98. package/src/prover/smt/solver/fd-solver.ts +608 -139
  99. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  100. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  101. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  102. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  103. package/src/prover/smt/solver/goal.ts +6 -3
  104. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  105. package/src/prover/smt/solver/hashtable.ts +4 -0
  106. package/src/prover/smt/solver/internalizer.ts +1 -1
  107. package/src/prover/smt/solver/logic-tactics.ts +15 -5
  108. package/src/prover/smt/solver/lp/core-solver.ts +12 -8
  109. package/src/prover/smt/solver/lp/lar-solver.ts +1 -1
  110. package/src/prover/smt/solver/lp/lp-settings.ts +6 -2
  111. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  112. package/src/prover/smt/solver/lp/nla-grobner.ts +158 -80
  113. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  114. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -2
  115. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -20
  116. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -39
  117. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  118. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  119. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  120. package/src/prover/smt/solver/maxcore.ts +2 -1
  121. package/src/prover/smt/solver/maxsmt-base.ts +1 -0
  122. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  123. package/src/prover/smt/solver/model-checker.ts +1 -1
  124. package/src/prover/smt/solver/model-evaluator.ts +2 -0
  125. package/src/prover/smt/solver/model-generator.ts +85 -43
  126. package/src/prover/smt/solver/mpf.ts +2 -4
  127. package/src/prover/smt/solver/mus.ts +2 -3
  128. package/src/prover/smt/solver/muz/dl-context.ts +22 -44
  129. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +1 -1
  130. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  131. package/src/prover/smt/solver/muz/dl-rule.ts +8 -9
  132. package/src/prover/smt/solver/muz/hnf.ts +2 -2
  133. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  134. package/src/prover/smt/solver/muz/horn-tactic.ts +15 -2
  135. package/src/prover/smt/solver/muz/rule-properties.ts +22 -0
  136. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  137. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  138. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +1 -1
  139. package/src/prover/smt/solver/nlqsat.ts +1 -1
  140. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  141. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  142. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  143. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  144. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  145. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  146. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  147. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  148. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  149. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  150. package/src/prover/smt/solver/nnf.ts +6 -2
  151. package/src/prover/smt/solver/opt-context.ts +21 -7
  152. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  153. package/src/prover/smt/solver/opt-pareto.ts +19 -0
  154. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  155. package/src/prover/smt/solver/opt-solver.ts +10 -6
  156. package/src/prover/smt/solver/optsmt.ts +1 -1
  157. package/src/prover/smt/solver/parallel-tactic.ts +1 -1
  158. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  159. package/src/prover/smt/solver/poly-rewriter.ts +75 -18
  160. package/src/prover/smt/solver/probes.ts +88 -23
  161. package/src/prover/smt/solver/proto-model.ts +8 -8
  162. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  163. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  164. package/src/prover/smt/solver/qe-lite.ts +2 -2
  165. package/src/prover/smt/solver/qe.ts +3 -2
  166. package/src/prover/smt/solver/qsat.ts +23 -8
  167. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  168. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  169. package/src/prover/smt/solver/rewriter-tpl.ts +7 -6
  170. package/src/prover/smt/solver/rewriter.ts +31 -25
  171. package/src/prover/smt/solver/rlimit.ts +7 -3
  172. package/src/prover/smt/solver/sat/config.ts +1 -1
  173. package/src/prover/smt/solver/sat/goal2sat.ts +65 -12
  174. package/src/prover/smt/solver/sat/inc-sat-solver.ts +129 -43
  175. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  176. package/src/prover/smt/solver/sat/pb-constraint.ts +7 -0
  177. package/src/prover/smt/solver/sat/pb-solver.ts +26 -7
  178. package/src/prover/smt/solver/sat/sat-tactic.ts +17 -7
  179. package/src/prover/smt/solver/sat/sat2goal.ts +72 -48
  180. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  181. package/src/prover/smt/solver/sat/solver.ts +27 -47
  182. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  183. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  184. package/src/prover/smt/solver/seq-derive.ts +2 -2
  185. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  186. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  187. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  188. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  189. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  190. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  191. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  192. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  193. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  194. package/src/prover/smt/solver/smt-consequences.ts +1 -1
  195. package/src/prover/smt/solver/smt-kernel.ts +48 -7
  196. package/src/prover/smt/solver/smt-setup.ts +106 -13
  197. package/src/prover/smt/solver/smtlib-parser.ts +589 -224
  198. package/src/prover/smt/solver/smtlib-script.ts +713 -210
  199. package/src/prover/smt/solver/solve-eqs.ts +36 -37
  200. package/src/prover/smt/solver/solver.ts +18 -3
  201. package/src/prover/smt/solver/tactic.ts +350 -195
  202. package/src/prover/smt/solver/theory-bv.ts +13 -3
  203. package/src/prover/smt/solver/theory-fpa.ts +1 -1
  204. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -0
  205. package/src/prover/smt/solver/theory-lra-internalize.ts +2 -0
  206. package/src/prover/smt/solver/theory-lra-propagate.ts +11 -3
  207. package/src/prover/smt/solver/theory-lra-state.ts +1 -1
  208. package/src/prover/smt/solver/theory-lra.ts +1 -1
  209. package/src/prover/smt/solver/theory-pb.ts +24 -7
  210. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  211. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  212. package/src/prover/smt/solver/theory-without-terms.ts +24 -0
  213. package/src/prover/smt/solver/tseitin-cnf.ts +1 -0
  214. package/src/prover/tlapm/cache.ts +8 -8
  215. package/src/prover/zenon/index-table.ts +5 -2
  216. package/src/prover/zenon/isar-case.ts +1 -1
  217. package/src/prover/zenon/isar.ts +2 -2
  218. package/src/prover/zenon/phrase.ts +1 -1
  219. package/src/resolve.ts +1274 -257
  220. package/src/runtime.ts +7 -1
  221. package/src/sany/builtins.ts +10 -10
  222. package/src/sany/generation.ts +5 -15
  223. package/src/sany/generator-def-entries.ts +123 -36
  224. package/src/sany/generator-definitions.ts +5 -3
  225. package/src/sany/generator-expressions.ts +60 -37
  226. package/src/sany/generator-proofs.ts +18 -12
  227. package/src/sany/generator.ts +12 -6
  228. package/src/sany/lexer.ts +15 -7
  229. package/src/sany/modules.ts +4 -2
  230. package/src/sany/nodes.ts +1 -1
  231. package/src/sany/selectors.ts +11 -6
  232. package/src/sany/xml.ts +2 -3
  233. package/src/search.ts +319 -135
  234. package/src/simulate.ts +235 -182
  235. package/src/spec-description.ts +8 -6
  236. package/src/standard-definitions.ts +1 -0
  237. package/src/standard-modules.ts +56 -22
  238. package/src/subexpressions.ts +564 -138
  239. package/src/successors.ts +37 -13
  240. package/src/symmetry.ts +2 -1
  241. package/src/tlc/jar-data.ts +10 -0
  242. package/src/tlc/messages.ts +3 -3
  243. package/src/tlc/order.ts +14 -3
  244. package/src/tlc/random.ts +2 -1
  245. package/src/tlc/replay.ts +67 -43
  246. package/src/tlc/tlc-operators.ts +10 -8
  247. package/src/tlc/tlcext-operators.ts +44 -15
  248. package/src/tlc/trace-spec.ts +9 -22
  249. package/src/trace-liveness.ts +529 -0
  250. package/src/typed-tier.ts +52 -31
  251. package/src/typescript/types.ts +2 -2
  252. package/src/values.ts +150 -79
package/src/levels.ts CHANGED
@@ -1,27 +1,30 @@
1
1
  import {
2
2
  getChildren,
3
3
  type AssumeProve,
4
+ type Bound,
4
5
  type Definition,
5
6
  type Expression,
7
+ type Fact,
8
+ type LetExpression,
6
9
  type Module,
10
+ type ModuleUnit,
11
+ type NewSymbol,
7
12
  type OperatorParam,
8
13
  type Proof,
9
14
  type ProofStep,
10
15
  type SourceLocation,
16
+ type SourceRange,
11
17
  } from "./ast";
12
- import {
13
- createSanyError,
14
- createSemanticError,
15
- formatRange,
16
- TlaSyntaxError,
17
- type SanyError,
18
- } from "./errors";
18
+ import { formatRange, type SanyError } from "./errors";
19
19
  import { forEachChild } from "./instances";
20
- import { collectSemanticErrors, getBoundNames, getPatternNames } from "./resolve";
20
+ import { parenthesizedRanges } from "./parser";
21
+ import { collectSemanticErrors, getBoundNames, getPatternNames, isBefore } from "./resolve";
22
+ import { resolveSynonym } from "./tlc/jar-data";
21
23
  import { STANDARD_LEVELS } from "./standard-definitions";
22
24
 
23
25
  interface LevelData {
24
26
  level: number;
27
+ isCorrect: boolean;
25
28
  params: Set<string>;
26
29
  constraints: Map<string, number>;
27
30
  argConstraints: Map<string, number>;
@@ -46,7 +49,7 @@ interface LevelContext {
46
49
  }
47
50
 
48
51
  type ScopeEntry =
49
- | { kind: "Formal"; arity: number }
52
+ | { kind: "Formal"; arity: number; level: number }
50
53
  | { kind: "Let"; definition: Definition; scope: Scope };
51
54
 
52
55
  export type Scope = Map<string, ScopeEntry>;
@@ -55,6 +58,19 @@ type Resolved =
55
58
  | { kind: "Declared"; name: string; level: number; arity: number }
56
59
  | { kind: "Defined"; levels: OperatorLevels };
57
60
 
61
+ interface SectionMember {
62
+ definition: Definition;
63
+ scope: Scope;
64
+ isRechecked: boolean;
65
+ }
66
+
67
+ interface RecursiveSection {
68
+ location: SourceLocation;
69
+ members: SectionMember[];
70
+ }
71
+
72
+ type ScopeFrame = Definition | LetExpression | string[];
73
+
58
74
  type Operand =
59
75
  | { kind: "Value"; data: LevelData }
60
76
  | { kind: "Operator"; data: OperatorLevels }
@@ -65,6 +81,14 @@ export const VARIABLE_LEVEL = 1;
65
81
  export const ACTION_LEVEL = 2;
66
82
  export const TEMPORAL_LEVEL = 3;
67
83
 
84
+ const NEW_SYMBOL_LEVELS = {
85
+ Constant: CONSTANT_LEVEL,
86
+ Variable: VARIABLE_LEVEL,
87
+ State: VARIABLE_LEVEL,
88
+ Action: ACTION_LEVEL,
89
+ Temporal: TEMPORAL_LEVEL,
90
+ } satisfies Record<NewSymbol["level"], number>;
91
+
68
92
  const SEPARATOR = "\u0000";
69
93
 
70
94
  export const getArgumentKey = (operator: string, index: number) =>
@@ -83,6 +107,7 @@ const getConditionKey = (operator: number, operand: number, argument: number) =>
83
107
 
84
108
  const createData = (level = 0): LevelData => ({
85
109
  level,
110
+ isCorrect: true,
86
111
  params: new Set(),
87
112
  constraints: new Map(),
88
113
  argConstraints: new Map(),
@@ -154,27 +179,50 @@ const CORE_SIGNATURES = new Map(
154
179
  ["BOOLEAN", 0, [], []],
155
180
  ["STRING", 0, [], []],
156
181
  ] as const
157
- ).map(([name, level, maxLevels, weights]): [string, OperatorLevels] => [
158
- name,
182
+ ).map((signature): [string, OperatorLevels] => [
183
+ signature[0],
159
184
  {
160
- ...createSignature(name, level, [...maxLevels], [...weights]),
161
- nonLeibniz: new Set(level > 1 ? [0, 1] : []),
185
+ ...createSignature(signature[0], signature[1], [...signature[2]], [...signature[3]]),
186
+ nonLeibniz: new Set(signature[1] > 1 ? [0, 1] : []),
162
187
  },
163
188
  ]),
164
189
  );
165
190
 
166
- const SET_LEVELS = createSignature("$Set", 0, [2], [1]);
167
- const JUNCTION_LEVELS = createSignature("$Junction", 0, [3], [1]);
168
- const CHOOSE_LEVELS = createSignature("$Choose", 0, [2], [1]);
169
- const FUNCTION_LEVELS = createSignature("$Function", 0, [3], [1]);
170
- const APPLY_LEVELS = createSignature("$FcnApply", 0, [2, 2], [1, 1]);
171
- const SELECT_LEVELS = createSignature("$RcdSelect", 0, [2, 0], [1, 1]);
172
191
  const PRIME_LEVELS = createSignature("'", 2, [1], [0]);
192
+ const UNCHANGED_LEVELS = createSignature("UNCHANGED", 2, [1], [0]);
173
193
  const ENABLED_LEVELS = createSignature("ENABLED", 1, [2], [0]);
174
- const TEMPORAL_LEVELS = createSignature("[]", 3, [3], [0]);
175
- const ACTION_LEVELS = createSignature("$SquareAct", 2, [2, 1], [0, 0]);
176
- const FAIRNESS_LEVELS = createSignature("$WF", 3, [1, 2], [0, 0]);
177
- const TEMPORAL_QUANTIFIER_LEVELS = createSignature("$TemporalExists", 3, [3], [0]);
194
+ const ALWAYS_LEVELS = createSignature("[]", 3, [3], [0]);
195
+ const EVENTUALLY_LEVELS = createSignature("<>", 3, [3], [0]);
196
+ const AND_LEVELS = createSignature("$ConjList", 0, [3], [1]);
197
+ const OR_LEVELS = createSignature("$DisjList", 0, [3], [1]);
198
+ const IF_LEVELS = createSignature("$IfThenElse", 0, [3], [1]);
199
+ const CASE_LEVELS = createSignature("$Case", 0, [3], [1]);
200
+ const FORALL_LEVELS = createSignature("$BoundedForall", 0, [3], [1]);
201
+ const EXISTS_LEVELS = createSignature("$BoundedExists", 0, [3], [1]);
202
+ const UNBOUNDED_FORALL_LEVELS = createSignature("$UnboundedForall", 0, [3], [1]);
203
+ const UNBOUNDED_EXISTS_LEVELS = createSignature("$UnboundedExists", 0, [3], [1]);
204
+ const TEMPORAL_FORALL_LEVELS = createSignature("$TemporalForall", 3, [3], [0]);
205
+ const TEMPORAL_EXISTS_LEVELS = createSignature("$TemporalExists", 3, [3], [0]);
206
+ const BOUNDED_CHOOSE_LEVELS = createSignature("$BoundedChoose", 0, [2], [1]);
207
+ const UNBOUNDED_CHOOSE_LEVELS = createSignature("$UnboundedChoose", 0, [2], [1]);
208
+ const SET_ENUMERATE_LEVELS = createSignature("$SetEnumerate", 0, [2], [1]);
209
+ const TUPLE_LEVELS = createSignature("$Tuple", 0, [2], [1]);
210
+ const SET_OF_FCNS_LEVELS = createSignature("$SetOfFcns", 0, [2], [1]);
211
+ const CARTESIAN_PROD_LEVELS = createSignature("$CartesianProd", 0, [2], [1]);
212
+ const SUBSET_OF_LEVELS = createSignature("$SubsetOf", 0, [2], [1]);
213
+ const SET_OF_ALL_LEVELS = createSignature("$SetOfAll", 0, [2], [1]);
214
+ const FCN_CONSTRUCTOR_LEVELS = createSignature("$FcnConstructor", 0, [3], [1]);
215
+ const RCD_CONSTRUCTOR_LEVELS = createSignature("$RcdConstructor", 0, [3], [1]);
216
+ const SET_OF_RCDS_LEVELS = createSignature("$SetOfRcds", 0, [2], [1]);
217
+ const EXCEPT_LEVELS = createSignature("$Except", 0, [2], [1]);
218
+ const PAIR_LEVELS = createSignature("$Pair", 0, [3], [1]);
219
+ const SEQ_LEVELS = createSignature("$Seq", 0, [2], [1]);
220
+ const APPLY_LEVELS = createSignature("$FcnApply", 0, [2, 2], [1, 1]);
221
+ const SELECT_LEVELS = createSignature("$RcdSelect", 0, [2, 0], [1, 1]);
222
+ const SQUARE_ACT_LEVELS = createSignature("$SquareAct", 2, [2, 1], [0, 0]);
223
+ const ANGLE_ACT_LEVELS = createSignature("$AngleAct", 2, [2, 1], [0, 0]);
224
+ const WF_LEVELS = createSignature("$WF", 3, [1, 2], [0, 0]);
225
+ const SF_LEVELS = createSignature("$SF", 3, [1, 2], [0, 0]);
178
226
 
179
227
  const bindFormals = (scope: Scope, formals: OperatorParam[]) =>
180
228
  formals.length === 0
@@ -183,31 +231,204 @@ const bindFormals = (scope: Scope, formals: OperatorParam[]) =>
183
231
  ...scope,
184
232
  ...formals.map((formal): [string, ScopeEntry] => [
185
233
  formal.name,
186
- { kind: "Formal", arity: formal.arity },
234
+ { kind: "Formal", arity: formal.arity, level: CONSTANT_LEVEL },
187
235
  ]),
188
236
  ]);
189
237
 
190
238
  const toFormals = (names: string[]) => names.map((name) => ({ name, arity: 0 }));
191
239
 
192
- const createLevelError = (message: string, expression: Expression) =>
193
- expression.location.range
194
- ? createSemanticError(`${message}.`, expression.location.range)
195
- : new TlaSyntaxError(
196
- `${message} at line ${expression.location.line}, column ${expression.location.column}`,
197
- );
240
+ const getFormals = (definition: Definition) =>
241
+ definition.kind === "Operator" ? definition.params : [];
242
+
243
+ const getDefinitionBody = (definition: Definition): Expression =>
244
+ definition.kind === "Function"
245
+ ? {
246
+ kind: "FunctionConstruction",
247
+ bounds: definition.bounds,
248
+ body: definition.body,
249
+ location: definition.location,
250
+ }
251
+ : definition.body;
252
+
253
+ const createLetScope = (expression: LetExpression, scope: Scope) => {
254
+ const inner: Scope = new Map(scope);
255
+ expression.definitions.forEach((definition) =>
256
+ inner.set(definition.name, { kind: "Let", definition, scope: inner }),
257
+ );
258
+ return inner;
259
+ };
260
+
261
+ const createPlaceholder = (definition: Definition, maxLevel: number, weight: number) => {
262
+ const formals = getFormals(definition);
263
+ return {
264
+ ...createData(),
265
+ name: definition.name,
266
+ formals,
267
+ maxLevels: formals.map(() => maxLevel),
268
+ weights: formals.map(() => weight),
269
+ minMaxLevels: formals.map(() => []),
270
+ conditions: new Set<string>(),
271
+ nonLeibniz: new Set<number>(),
272
+ };
273
+ };
274
+
275
+ const getRecursiveSections = (
276
+ base: Scope,
277
+ root: ModuleUnit[] | LetExpression,
278
+ hasRecursiveLet = true,
279
+ ) => {
280
+ const sections: RecursiveSection[] = [];
281
+ const pending: Set<string>[] = [];
282
+ const frames: ScopeFrame[] = [];
283
+ const scopes: (Scope | undefined)[] = [];
284
+ let pendingCount = 0;
285
+ let depth = 0;
286
+
287
+ const getScope = () => {
288
+ let start = frames.length;
289
+ while (start > 0 && scopes[start - 1] === undefined) start--;
290
+ let scope = scopes[start - 1] ?? base;
291
+ for (let index = start; index < frames.length; index++) {
292
+ const frame = frames[index];
293
+ scope = Array.isArray(frame)
294
+ ? bindFormals(scope, toFormals(frame))
295
+ : frame.kind === "Let"
296
+ ? createLetScope(frame, scope)
297
+ : frame.kind === "Function"
298
+ ? bindFormals(scope, toFormals(getBoundNames(frame.bounds)))
299
+ : bindFormals(scope, frame.params);
300
+ scopes[index] = scope;
301
+ }
302
+ return scope;
303
+ };
304
+
305
+ const walkInFrame = (frame: ScopeFrame, expression: Expression) => {
306
+ frames.push(frame);
307
+ scopes.push(undefined);
308
+ walkExpression(expression);
309
+ frames.pop();
310
+ scopes.pop();
311
+ };
312
+
313
+ const visitChild = (child: Expression, bound: string[]) =>
314
+ bound.length === 0 ? walkExpression(child) : walkInFrame(bound, child);
315
+
316
+ const walkExpression = (expression: Expression): void => {
317
+ if (expression.kind !== "Let") return forEachChild(expression, visitChild);
318
+ frames.push(expression);
319
+ scopes.push(undefined);
320
+ depth++;
321
+ if (expression.recursive) walkUnits(getLetUnits(expression));
322
+ else {
323
+ for (let index = 0; index < expression.definitions.length; index++) {
324
+ walkDefinition(expression.definitions[index]);
325
+ }
326
+ }
327
+ depth--;
328
+ walkExpression(expression.body);
329
+ frames.pop();
330
+ scopes.pop();
331
+ };
332
+
333
+ const walkDefinition = (definition: Definition) => {
334
+ if (definition.kind === "Function") {
335
+ for (let index = 0; index < definition.bounds.length; index++) {
336
+ walkExpression(definition.bounds[index].set);
337
+ }
338
+ }
339
+ walkInFrame(definition, definition.body);
340
+ if (pendingCount === 0) return;
341
+ const names = (pending[depth] ??= new Set());
342
+ if (definition.isRecursive && names.delete(definition.name)) {
343
+ pendingCount--;
344
+ return;
345
+ }
346
+ sections.at(-1)?.members.push({ definition, scope: getScope(), isRechecked: names.size > 0 });
347
+ };
348
+
349
+ const declareRecursive = (definitions: Definition[], location: SourceLocation) => {
350
+ if (pendingCount === 0) sections.push({ location, members: [] });
351
+ const names = (pending[depth] ??= new Set());
352
+ definitions.forEach((definition) => {
353
+ if (names.has(definition.name)) return;
354
+ names.add(definition.name);
355
+ pendingCount++;
356
+ });
357
+ definitions.forEach((definition) =>
358
+ sections.at(-1)?.members.push({ definition, scope: getScope(), isRechecked: true }),
359
+ );
360
+ };
361
+
362
+ const walkUnits = (units: ModuleUnit[]) => {
363
+ const recursiveDefinitions = new Map<string, Definition[]>();
364
+ units.forEach((unit) => {
365
+ if (unit.kind !== "Definition" || !unit.definition.isRecursive) return;
366
+ const named = recursiveDefinitions.get(unit.definition.name);
367
+ if (named) named.push(unit.definition);
368
+ else recursiveDefinitions.set(unit.definition.name, [unit.definition]);
369
+ });
370
+ units.forEach((unit) => {
371
+ if (unit.kind === "Recursive") {
372
+ declareRecursive(
373
+ unit.declarations.flatMap(
374
+ (declaration) => recursiveDefinitions.get(declaration.name) ?? [],
375
+ ),
376
+ unit.location,
377
+ );
378
+ return;
379
+ }
380
+ if (pendingCount === 0 && !hasRecursiveLet) return;
381
+ if (unit.kind === "Assumption") walkExpression(unit.assumption.expression);
382
+ else if (unit.kind === "Theorem" && unit.theorem.statement.kind !== "AssumeProve") {
383
+ walkExpression(unit.theorem.statement);
384
+ } else if (unit.kind === "Definition") walkDefinition(unit.definition);
385
+ });
386
+ };
387
+
388
+ if (Array.isArray(root)) walkUnits(root);
389
+ else walkExpression(root);
390
+ return sections;
391
+ };
392
+
393
+ const getLetUnits = (expression: LetExpression) =>
394
+ [
395
+ ...(expression.recursive ?? []).map((declaration) => ({
396
+ location: declaration.location,
397
+ unit: {
398
+ kind: "Recursive",
399
+ declarations: [declaration],
400
+ location: declaration.location,
401
+ } satisfies ModuleUnit,
402
+ })),
403
+ ...expression.definitions.map((definition) => ({
404
+ location: definition.location,
405
+ unit: { kind: "Definition", definition } satisfies ModuleUnit,
406
+ })),
407
+ ]
408
+ .toSorted((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
409
+ .map((entry) => entry.unit);
198
410
 
199
411
  const LOGICAL_OPERATORS = new Set(["/\\", "\\/", "=>", "<=>"]);
200
412
 
413
+ const isMixed = (levels: number[]) =>
414
+ levels.includes(ACTION_LEVEL) && levels.includes(TEMPORAL_LEVEL);
415
+
416
+ const getWrittenRange = (expression: Expression) =>
417
+ parenthesizedRanges.get(expression) ?? expression.location.range;
418
+
201
419
  const isOperatorApplication = (expression: Expression) =>
202
420
  expression.kind !== "Let" && expression.kind !== "Label";
203
421
 
204
422
  export const createLevelAnalyzer = (context: LevelContext) => {
205
423
  const definitionLevels = new Map<Definition, OperatorLevels>();
424
+ const selectionLevels = new Map<Expression, LevelData>();
425
+ const errors: SanyError[] = [];
426
+ const messages: string[] = [];
206
427
 
207
428
  const resolve = (name: string, scope: Scope): Resolved => {
208
429
  const entry = scope.get(name);
209
430
  if (entry?.kind === "Formal") {
210
- return { kind: "Declared", name, level: 0, arity: entry.arity };
431
+ return { kind: "Declared", name, level: entry.level, arity: entry.arity };
211
432
  }
212
433
  if (entry?.kind === "Let") {
213
434
  return { kind: "Defined", levels: analyzeDefinition(entry.definition, entry.scope) };
@@ -230,6 +451,7 @@ export const createLevelAnalyzer = (context: LevelContext) => {
230
451
 
231
452
  const applyDeclared = (name: string, level: number, operands: Operand[]) => {
232
453
  const data = createData(Math.max(level, ...operands.map((operand) => operand.data.level)));
454
+ data.isCorrect = operands.every((operand) => operand.data.isCorrect);
233
455
  data.params.add(name);
234
456
  operands.forEach((operand, index) => {
235
457
  operand.data.params.forEach((param) => {
@@ -249,19 +471,18 @@ export const createLevelAnalyzer = (context: LevelContext) => {
249
471
  bound: string[] = [],
250
472
  ) => {
251
473
  const isBound = (name: string) => bound.includes(name);
252
- operands.forEach((operand, index) => {
253
- if (operand.kind !== "Value") return;
254
- if (operand.data.level > getMaxLevel(operator, index)) {
255
- throw new TlaSyntaxError(
256
- `Level error in applying operator ${operator.name}:\nThe level of argument ${index + 1} exceeds the maximum level allowed by the operator`,
257
- );
258
- }
259
- });
260
- if (ranges.some((range) => range.level > ACTION_LEVEL)) {
261
- throw new TlaSyntaxError(
262
- `Level error in applying operator ${operator.name}:\nThe level of the range for a bounded variable exceeds the maximum level allowed by the operator`,
474
+ const exceeding = operands.flatMap((operand, index) =>
475
+ operand.kind === "Value" && operand.data.level > getMaxLevel(operator, index)
476
+ ? [{ operand, index }]
477
+ : [],
478
+ );
479
+ exceeding
480
+ .filter((entry) => operator.isCorrect && entry.operand.data.isCorrect)
481
+ .forEach((entry) =>
482
+ messages.push(
483
+ `Level error in applying operator ${resolveSynonym(operator.name)}:\nThe level of argument ${entry.index + 1} exceeds the maximum level allowed by the operator`,
484
+ ),
263
485
  );
264
- }
265
486
  const getOperand = (formal: string) => {
266
487
  const index = operator.formals.findIndex((param) => param.name === formal);
267
488
  return index === -1 ? undefined : operands[index];
@@ -277,6 +498,10 @@ export const createLevelAnalyzer = (context: LevelContext) => {
277
498
  ...ranges.map((range) => range.level),
278
499
  ),
279
500
  );
501
+ data.isCorrect =
502
+ exceeding.length === 0 &&
503
+ operands.every((operand) => operand.data.isCorrect) &&
504
+ ranges.every((range) => range.isCorrect);
280
505
  operator.params.forEach((param) => data.params.add(param));
281
506
  operands.forEach((operand, index) => {
282
507
  if (getWeight(operator, index) === 1) {
@@ -448,16 +673,23 @@ export const createLevelAnalyzer = (context: LevelContext) => {
448
673
  operator: OperatorLevels,
449
674
  expressions: Expression[],
450
675
  scope: Scope,
451
- ranges: Expression[] = [],
452
- bound: string[] = [],
676
+ bounds: Bound[] = [],
677
+ bound = getBoundNames(bounds),
453
678
  ) => {
454
- const inner = bindFormals(scope, toFormals(bound));
455
- return applyDefined(
456
- operator,
457
- toOperands(expressions, inner),
458
- ranges.map((range) => analyze(range, scope)),
459
- bound,
460
- );
679
+ const operands = toOperands(expressions, bindFormals(scope, toFormals(bound)));
680
+ const ranges = bounds.map((range) => analyze(range.set, scope));
681
+ const data = applyDefined(operator, operands, ranges, bound);
682
+ ranges.forEach((range, index) => {
683
+ if (range.level <= ACTION_LEVEL) return;
684
+ data.isCorrect = false;
685
+ if (!range.isCorrect) return;
686
+ const pattern = bounds[index].pattern;
687
+ const symbol = pattern.ranges?.[0];
688
+ messages.push(
689
+ `Level error in applying operator ${operator.name}:\nThe level of the range for the bounded variable ${symbol ? formatRange(symbol) : getPatternNames(pattern)[0]} \nexceeds the maximum level allowed by the operator`,
690
+ );
691
+ });
692
+ return data;
461
693
  };
462
694
 
463
695
  const applyResolved = (resolved: Resolved, operands: Operand[]) =>
@@ -465,25 +697,21 @@ export const createLevelAnalyzer = (context: LevelContext) => {
465
697
  ? applyDeclared(resolved.name, resolved.level, operands)
466
698
  : applyDefined(resolved.levels, operands);
467
699
 
468
- const checkJunction = (operands: Operand[], expression: Expression) => {
469
- const levels = operands.map((operand) => operand.data.level);
470
- if (levels.includes(ACTION_LEVEL) && levels.includes(TEMPORAL_LEVEL)) {
471
- throw createLevelError(
472
- "Formula has both temporal formula and action as arguments",
473
- expression,
474
- );
475
- }
700
+ const checkJunction = (levels: number[], name: string) => {
701
+ if (isMixed(levels)) messages.push(`${name} has both temporal formula and action as arguments`);
476
702
  };
477
703
 
478
704
  const checkApply = (expression: Expression & { kind: "Apply" }, operands: Operand[]) => {
479
705
  const isLeadsTo = expression.operator === "~>" || expression.operator === "-+->";
480
706
  if (isLeadsTo && operands.some((operand) => operand.data.level === ACTION_LEVEL)) {
481
- throw createLevelError(
482
- "Action used where only temporal formula or state predicate allowed",
483
- expression,
707
+ messages.push("Action used where only temporal formula or state predicate allowed");
708
+ }
709
+ if (LOGICAL_OPERATORS.has(expression.operator)) {
710
+ checkJunction(
711
+ operands.map((operand) => operand.data.level),
712
+ resolveSynonym(expression.operator),
484
713
  );
485
714
  }
486
- if (LOGICAL_OPERATORS.has(expression.operator)) checkJunction(operands, expression);
487
715
  };
488
716
 
489
717
  const checkTemporal = (
@@ -493,40 +721,56 @@ export const createLevelAnalyzer = (context: LevelContext) => {
493
721
  const operand = expression.expression;
494
722
  const form = expression.kind === "Always" ? "BoxAction" : "AngleAction";
495
723
  if (level !== ACTION_LEVEL || !isOperatorApplication(operand) || operand.kind === form) return;
496
- throw createLevelError(
724
+ messages.push(
497
725
  expression.kind === "Always"
498
726
  ? "[] followed by action not of form [A]_v"
499
727
  : "<> followed by action not of form <<A>>_v",
500
- expression,
501
728
  );
502
729
  };
503
730
 
504
- const analyzeLet = (expression: Expression & { kind: "Let" }, scope: Scope) => {
505
- const inner = new Map(scope);
506
- expression.definitions.forEach((definition) =>
507
- inner.set(definition.name, { kind: "Let", definition, scope: inner }),
731
+ const analyzeLet = (expression: LetExpression, scope: Scope) => {
732
+ const inner = createLetScope(expression, scope);
733
+ if (expression.recursive) {
734
+ getRecursiveSections(scope, expression).forEach((section) =>
735
+ checkRecursiveSection(section.members),
736
+ );
737
+ }
738
+ const definitions = expression.definitions.map((definition) =>
739
+ analyzeDefinition(definition, inner),
508
740
  );
509
741
  const body = analyze(expression.body, inner);
510
742
  const data = {
511
743
  level: body.level,
744
+ isCorrect: body.isCorrect && definitions.every((levels) => levels.isCorrect),
512
745
  params: new Set(body.params),
513
746
  constraints: new Map(body.constraints),
514
747
  argConstraints: new Map(body.argConstraints),
515
748
  argParams: new Set(body.argParams),
516
749
  };
517
- expression.definitions.forEach((definition) =>
518
- mergeConstraints(data, analyzeDefinition(definition, inner)),
519
- );
750
+ definitions.forEach((levels) => mergeConstraints(data, levels));
520
751
  return data;
521
752
  };
522
753
 
523
- const analyze = (expression: Expression, scope: Scope): LevelData => {
524
- try {
525
- return analyzeNode(expression, scope);
526
- } catch (error) {
527
- if (!(error instanceof TlaSyntaxError) || error.sany) throw error;
528
- throw createLevelError(error.message, expression);
754
+ const reportSince = (start: number, range: SourceRange | undefined, data: LevelData) => {
755
+ if (messages.length === start) return data;
756
+ if (range) {
757
+ messages
758
+ .splice(start)
759
+ .forEach((message) =>
760
+ errors.push({ location: formatRange(range), message: `${message}.` }),
761
+ );
529
762
  }
763
+ return { ...data, isCorrect: false };
764
+ };
765
+
766
+ const reportAt = (range: SourceRange | undefined, getData: () => LevelData) => {
767
+ const start = messages.length;
768
+ return reportSince(start, range, getData());
769
+ };
770
+
771
+ const analyze = (expression: Expression, scope: Scope) => {
772
+ const start = messages.length;
773
+ return reportSince(start, expression.location.range, analyzeNode(expression, scope));
530
774
  };
531
775
 
532
776
  const analyzeNode = (expression: Expression, scope: Scope): LevelData => {
@@ -548,30 +792,65 @@ export const createLevelAnalyzer = (context: LevelContext) => {
548
792
  return toOperand(expression, scope).data;
549
793
  case "And":
550
794
  case "Or": {
551
- const operands = toOperands(expression.operands, scope);
552
- checkJunction(operands, expression);
553
- return applyDefined(JUNCTION_LEVELS, operands);
795
+ const isAnd = expression.kind === "And";
796
+ if (expression.isBulleted) {
797
+ const operands = toOperands(expression.operands, scope);
798
+ checkJunction(
799
+ operands.map((operand) => operand.data.level),
800
+ `${isAnd ? "Conjunction" : "Disjunction"} list`,
801
+ );
802
+ return applyDefined(isAnd ? AND_LEVELS : OR_LEVELS, operands);
803
+ }
804
+ // SANY nests a chain of infix /\ or \/ to the left, so it checks each prefix of the chain.
805
+ const name = isAnd ? "\\land" : "\\lor";
806
+ const start = getWrittenRange(expression.operands[0]);
807
+ const operands: Operand[] = [];
808
+ let prefixLevel = CONSTANT_LEVEL;
809
+ let isPrefixMixed = false;
810
+ expression.operands.forEach((operand, index) => {
811
+ const analyzed = toOperand(operand, scope);
812
+ operands.push(analyzed);
813
+ const levels = [prefixLevel, analyzed.data.level];
814
+ prefixLevel = Math.max(prefixLevel, analyzed.data.level);
815
+ if (index === 0) return;
816
+ const end = getWrittenRange(operand);
817
+ if (index === expression.operands.length - 1 || !start || !end) {
818
+ checkJunction(levels, name);
819
+ return;
820
+ }
821
+ if (!isMixed(levels)) return;
822
+ errors.push({
823
+ location: formatRange({ ...start, end: end.end }),
824
+ message: `${name} has both temporal formula and action as arguments.`,
825
+ });
826
+ isPrefixMixed = true;
827
+ });
828
+ const data = applyDefined(isAnd ? AND_LEVELS : OR_LEVELS, operands);
829
+ return isPrefixMixed ? { ...data, isCorrect: false } : data;
554
830
  }
555
831
  case "Prime":
556
- case "Unchanged":
557
832
  return applyBuiltin(PRIME_LEVELS, [expression.expression], scope);
833
+ case "Unchanged":
834
+ return applyBuiltin(UNCHANGED_LEVELS, [expression.expression], scope);
558
835
  case "Enabled":
559
836
  return applyBuiltin(ENABLED_LEVELS, [expression.expression], scope);
560
837
  case "Always":
561
838
  case "Eventually": {
562
839
  const operand = toOperand(expression.expression, scope);
563
840
  checkTemporal(expression, operand.data.level);
564
- return applyDefined(TEMPORAL_LEVELS, [operand]);
841
+ return applyDefined(expression.kind === "Always" ? ALWAYS_LEVELS : EVENTUALLY_LEVELS, [
842
+ operand,
843
+ ]);
565
844
  }
566
845
  case "If":
567
846
  return applyBuiltin(
568
- JUNCTION_LEVELS,
847
+ IF_LEVELS,
569
848
  [expression.condition, expression.consequent, expression.alternative],
570
849
  scope,
571
850
  );
572
851
  case "Case":
573
852
  return applyBuiltin(
574
- JUNCTION_LEVELS,
853
+ CASE_LEVELS,
575
854
  [
576
855
  ...expression.arms.flatMap((arm) => [arm.condition, arm.body]),
577
856
  ...(expression.other ? [expression.other] : []),
@@ -583,27 +862,33 @@ export const createLevelAnalyzer = (context: LevelContext) => {
583
862
  case "Forall":
584
863
  case "Exists": {
585
864
  const data = applyBuiltin(
586
- JUNCTION_LEVELS,
865
+ expression.kind === "Forall" ? FORALL_LEVELS : EXISTS_LEVELS,
587
866
  [expression.body],
588
867
  scope,
589
- expression.bounds.map((bound) => bound.set),
590
- getBoundNames(expression.bounds),
868
+ expression.bounds,
591
869
  );
592
870
  const actionBound =
593
871
  data.level === TEMPORAL_LEVEL
594
872
  ? expression.bounds.find((bound) => analyze(bound.set, scope).level === ACTION_LEVEL)
595
873
  : undefined;
596
- if (actionBound) {
597
- throw createLevelError(
598
- "Action-level bound of quantified temporal formula",
599
- actionBound.set,
600
- );
874
+ const range = actionBound?.set.location.range;
875
+ if (range) {
876
+ errors.push({
877
+ location: formatRange(range),
878
+ message: "Action-level bound of quantified temporal formula.",
879
+ });
601
880
  }
602
- return data;
881
+ return actionBound ? { ...data, isCorrect: false } : data;
603
882
  }
604
883
  case "UnboundedQuantifier":
605
884
  return applyBuiltin(
606
- expression.isTemporal ? TEMPORAL_QUANTIFIER_LEVELS : JUNCTION_LEVELS,
885
+ expression.isTemporal
886
+ ? expression.quantifier === "Forall"
887
+ ? TEMPORAL_FORALL_LEVELS
888
+ : TEMPORAL_EXISTS_LEVELS
889
+ : expression.quantifier === "Forall"
890
+ ? UNBOUNDED_FORALL_LEVELS
891
+ : UNBOUNDED_EXISTS_LEVELS,
607
892
  [expression.body],
608
893
  scope,
609
894
  [],
@@ -611,79 +896,74 @@ export const createLevelAnalyzer = (context: LevelContext) => {
611
896
  );
612
897
  case "Choose":
613
898
  return applyBuiltin(
614
- CHOOSE_LEVELS,
899
+ expression.set ? BOUNDED_CHOOSE_LEVELS : UNBOUNDED_CHOOSE_LEVELS,
615
900
  [expression.body],
616
901
  scope,
617
- expression.set ? [expression.set] : [],
902
+ expression.set ? [{ pattern: expression.pattern, set: expression.set }] : [],
618
903
  getPatternNames(expression.pattern),
619
904
  );
620
905
  case "SetEnumeration":
906
+ return applyBuiltin(SET_ENUMERATE_LEVELS, expression.elements, scope);
621
907
  case "Tuple":
908
+ return applyBuiltin(TUPLE_LEVELS, expression.elements, scope);
622
909
  case "FunctionSet":
910
+ return applyBuiltin(SET_OF_FCNS_LEVELS, [expression.domain, expression.range], scope);
623
911
  case "Product":
624
- return applyBuiltin(
625
- SET_LEVELS,
626
- expression.kind === "FunctionSet"
627
- ? [expression.domain, expression.range]
628
- : expression.kind === "Product"
629
- ? expression.factors
630
- : expression.elements,
631
- scope,
632
- );
912
+ return applyBuiltin(CARTESIAN_PROD_LEVELS, expression.factors, scope);
633
913
  case "SetFilter":
634
- return applyBuiltin(
635
- SET_LEVELS,
636
- [expression.predicate],
637
- scope,
638
- [expression.bound.set],
639
- getPatternNames(expression.bound.pattern),
640
- );
914
+ return applyBuiltin(SUBSET_OF_LEVELS, [expression.predicate], scope, [expression.bound]);
641
915
  case "SetMap":
642
- return applyBuiltin(
643
- SET_LEVELS,
644
- [expression.expression],
645
- scope,
646
- expression.bounds.map((bound) => bound.set),
647
- getBoundNames(expression.bounds),
648
- );
916
+ return applyBuiltin(SET_OF_ALL_LEVELS, [expression.expression], scope, expression.bounds);
649
917
  case "FunctionConstruction":
650
- return applyBuiltin(
651
- FUNCTION_LEVELS,
652
- [expression.body],
653
- scope,
654
- expression.bounds.map((bound) => bound.set),
655
- getBoundNames(expression.bounds),
656
- );
918
+ return applyBuiltin(FCN_CONSTRUCTOR_LEVELS, [expression.body], scope, expression.bounds);
657
919
  case "Record":
658
920
  return applyBuiltin(
659
- FUNCTION_LEVELS,
921
+ RCD_CONSTRUCTOR_LEVELS,
660
922
  expression.fields.map((field) => field.value),
661
923
  scope,
662
924
  );
663
925
  case "RecordSet":
664
926
  return applyBuiltin(
665
- SET_LEVELS,
927
+ SET_OF_RCDS_LEVELS,
666
928
  expression.fields.map((field) => field.value),
667
929
  scope,
668
930
  );
669
931
  case "Except":
670
- return applyBuiltin(
671
- SET_LEVELS,
672
- [
673
- expression.function,
674
- ...expression.updates.flatMap((update) => [
675
- ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
676
- update.value,
932
+ return applyDefined(EXCEPT_LEVELS, [
933
+ toOperand(expression.function, scope),
934
+ ...expression.updates.map((update): Operand => ({
935
+ kind: "Value",
936
+ data: applyDefined(PAIR_LEVELS, [
937
+ {
938
+ kind: "Value",
939
+ data: reportAt(update.range, () =>
940
+ applyDefined(
941
+ SEQ_LEVELS,
942
+ update.path.map((step): Operand =>
943
+ step.kind === "Field"
944
+ ? { kind: "Value", data: createData() }
945
+ : step.args.length === 1
946
+ ? toOperand(step.args[0], scope)
947
+ : {
948
+ kind: "Value",
949
+ data: reportAt(step.tupleRange, () =>
950
+ applyBuiltin(TUPLE_LEVELS, step.args, scope),
951
+ ),
952
+ },
953
+ ),
954
+ ),
955
+ ),
956
+ },
957
+ toOperand(update.value, scope),
677
958
  ]),
678
- ],
679
- scope,
680
- );
959
+ })),
960
+ ]);
681
961
  case "FunctionApplication":
682
962
  return applyDefined(APPLY_LEVELS, [
683
963
  toOperand(expression.function, scope),
684
964
  expression.args.length === 1
685
965
  ? toOperand(expression.args[0], scope)
686
- : { kind: "Value", data: applyBuiltin(SET_LEVELS, expression.args, scope) },
966
+ : { kind: "Value", data: applyBuiltin(TUPLE_LEVELS, expression.args, scope) },
687
967
  ]);
688
968
  case "Bracket":
689
969
  return createData();
@@ -694,12 +974,28 @@ export const createLevelAnalyzer = (context: LevelContext) => {
694
974
  ]);
695
975
  case "BoxAction":
696
976
  case "AngleAction":
697
- return applyBuiltin(ACTION_LEVELS, [expression.action, expression.subscript], scope);
977
+ return applyBuiltin(
978
+ expression.kind === "BoxAction" ? SQUARE_ACT_LEVELS : ANGLE_ACT_LEVELS,
979
+ [expression.action, expression.subscript],
980
+ scope,
981
+ );
698
982
  case "WeakFairness":
699
983
  case "StrongFairness":
700
- return applyBuiltin(FAIRNESS_LEVELS, [expression.subscript, expression.action], scope);
984
+ return applyBuiltin(
985
+ expression.kind === "WeakFairness" ? WF_LEVELS : SF_LEVELS,
986
+ [expression.subscript, expression.action],
987
+ scope,
988
+ );
701
989
  case "Label":
702
990
  return analyze(expression.body, scope);
991
+ case "Selection": {
992
+ const selected = expression.expression;
993
+ const known = selectionLevels.get(selected);
994
+ if (known) return known;
995
+ const data = analyze(selected, scope);
996
+ selectionLevels.set(selected, data);
997
+ return data;
998
+ }
703
999
  case "Subexpression":
704
1000
  return createData();
705
1001
  }
@@ -733,6 +1029,7 @@ export const createLevelAnalyzer = (context: LevelContext) => {
733
1029
  return names;
734
1030
  case "Lambda":
735
1031
  case "Let":
1032
+ case "Selection":
736
1033
  return names;
737
1034
  case "Prime":
738
1035
  case "Unchanged":
@@ -769,9 +1066,13 @@ export const createLevelAnalyzer = (context: LevelContext) => {
769
1066
  const inner = bindFormals(scope, formals);
770
1067
  const data = analyze(body, inner);
771
1068
  const isFormal = (param: string) => formals.some((formal) => formal.name === param);
772
- const nonLeibnizNames = getNonLeibnizNames(body, inner);
1069
+ const nonLeibnizNames = getNonLeibnizNames(
1070
+ body.kind === "Selection" ? body.expression : body,
1071
+ inner,
1072
+ );
773
1073
  const levels: OperatorLevels = {
774
1074
  ...createData(data.level),
1075
+ isCorrect: data.isCorrect,
775
1076
  name,
776
1077
  formals,
777
1078
  nonLeibniz: new Set(
@@ -815,35 +1116,87 @@ export const createLevelAnalyzer = (context: LevelContext) => {
815
1116
  return levels;
816
1117
  };
817
1118
 
1119
+ const staleDefinitions = new Set<Definition>();
1120
+
818
1121
  const analyzeDefinition = (definition: Definition, scope: Scope): OperatorLevels => {
819
1122
  const cached = definitionLevels.get(definition);
820
- if (cached) return cached;
821
- const formals = definition.kind === "Operator" ? definition.params : [];
822
- definitionLevels.set(definition, {
823
- ...createData(),
824
- name: definition.name,
825
- formals,
826
- maxLevels: formals.map(() => TEMPORAL_LEVEL),
827
- weights: formals.map(() => 0),
828
- minMaxLevels: formals.map(() => []),
829
- conditions: new Set(),
830
- nonLeibniz: new Set(),
1123
+ if (cached && !staleDefinitions.delete(definition)) return cached;
1124
+ const prior = cached ?? createPlaceholder(definition, TEMPORAL_LEVEL, 0);
1125
+ definitionLevels.set(definition, prior);
1126
+ const levels = analyzeOperator(
1127
+ definition.name,
1128
+ getFormals(definition),
1129
+ getDefinitionBody(definition),
1130
+ scope,
1131
+ );
1132
+ const merged = {
1133
+ ...levels,
1134
+ level: Math.max(prior.level, levels.level),
1135
+ params: new Set([...prior.params, ...levels.params]),
1136
+ argParams: new Set([...prior.argParams, ...levels.argParams]),
1137
+ maxLevels: levels.maxLevels.map((level, index) => Math.min(level, prior.maxLevels[index])),
1138
+ weights: levels.weights.map((weight, index) => Math.max(weight, prior.weights[index])),
1139
+ nonLeibniz: new Set([...prior.nonLeibniz, ...levels.nonLeibniz]),
1140
+ };
1141
+ definitionLevels.set(definition, merged);
1142
+ return merged;
1143
+ };
1144
+
1145
+ const checkPrimedArguments = (members: SectionMember[]) =>
1146
+ members.forEach((member) => {
1147
+ const range = member.definition.location.range;
1148
+ if (!member.definition.isRecursive || !range) return;
1149
+ analyzeDefinition(member.definition, member.scope).maxLevels.forEach((level, index) => {
1150
+ if (level >= ACTION_LEVEL) return;
1151
+ errors.push({
1152
+ location: formatRange(range),
1153
+ message: `Argument ${index + 1} of recursive operator ${resolveSynonym(member.definition.name)} is primed`,
1154
+ });
1155
+ });
831
1156
  });
832
- const body: Expression =
833
- definition.kind === "Function"
834
- ? {
835
- kind: "FunctionConstruction",
836
- bounds: definition.bounds,
837
- body: definition.body,
838
- location: definition.location,
839
- }
840
- : definition.body;
841
- const levels = analyzeOperator(definition.name, formals, body, scope);
842
- definitionLevels.set(definition, levels);
843
- return levels;
1157
+
1158
+ const checkRecursiveSection = (members: SectionMember[]) => {
1159
+ if (members.length === 0 || definitionLevels.has(members[0].definition)) return;
1160
+ const recursive = members.filter((member) => member.definition.isRecursive);
1161
+ recursive.forEach((member) =>
1162
+ definitionLevels.set(
1163
+ member.definition,
1164
+ createPlaceholder(member.definition, ACTION_LEVEL, 1),
1165
+ ),
1166
+ );
1167
+ const recheck = (member: SectionMember) => {
1168
+ if (member.definition.isRecursive) staleDefinitions.add(member.definition);
1169
+ return analyzeDefinition(member.definition, member.scope);
1170
+ };
1171
+ members.forEach((member) => {
1172
+ recheck(member);
1173
+ checkPrimedArguments([member]);
1174
+ });
1175
+ const firstPass = recursive.map((member) => analyzeDefinition(member.definition, member.scope));
1176
+ const level = Math.max(CONSTANT_LEVEL, ...firstPass.map((levels) => levels.level));
1177
+ const params = firstPass.flatMap((levels) => [...levels.params]);
1178
+ members.forEach((member) => {
1179
+ const levels = analyzeDefinition(member.definition, member.scope);
1180
+ definitionLevels.set(member.definition, {
1181
+ ...levels,
1182
+ level: Math.max(levels.level, level),
1183
+ params: new Set([...levels.params, ...params]),
1184
+ });
1185
+ if (member.isRechecked && !member.definition.isRecursive) {
1186
+ staleDefinitions.add(member.definition);
1187
+ }
1188
+ });
1189
+ members.forEach(recheck);
844
1190
  };
845
1191
 
846
- return { analyze, analyzeDefinition, toOperand };
1192
+ return {
1193
+ analyze,
1194
+ analyzeDefinition,
1195
+ checkPrimedArguments,
1196
+ checkRecursiveSection,
1197
+ toOperand,
1198
+ errors,
1199
+ };
847
1200
  };
848
1201
 
849
1202
  export const analyzeAssumeProve = (
@@ -855,7 +1208,18 @@ export const analyzeAssumeProve = (
855
1208
  const parts = assumeProve.assumptions.flatMap((assumption) => {
856
1209
  if (assumption.kind === "NewSymbol") {
857
1210
  const set = assumption.set && analyzer.analyze(assumption.set, inner);
858
- inner.set(assumption.name, { kind: "Formal", arity: assumption.arity });
1211
+ const range = assumption.location.range;
1212
+ if (set?.level === TEMPORAL_LEVEL && range) {
1213
+ analyzer.errors.push({
1214
+ location: formatRange(range),
1215
+ message: "Level error:\nTemporal formula used as set.",
1216
+ });
1217
+ }
1218
+ inner.set(assumption.name, {
1219
+ kind: "Formal",
1220
+ arity: assumption.arity,
1221
+ level: NEW_SYMBOL_LEVELS[assumption.level],
1222
+ });
859
1223
  return set ? [set] : [];
860
1224
  }
861
1225
  return [
@@ -880,27 +1244,35 @@ export const checkModuleLevels = (
880
1244
  warnings: SanyError[],
881
1245
  ) => {
882
1246
  const analyzer = createLevelAnalyzer(context);
883
- const getLevel = (expressions: Expression[]) =>
884
- Math.max(0, ...expressions.map((expression) => analyzer.analyze(expression, new Map()).level));
885
- const getStepLevel = (step: ProofStep) => {
1247
+ const getLevel = (expressions: Expression[], scope: Scope) =>
1248
+ Math.max(0, ...expressions.map((expression) => analyzer.analyze(expression, scope).level));
1249
+ const getStepLevel = (step: ProofStep, scope: Scope) => {
886
1250
  const body = step.body;
887
- if (body.kind === "Have" || body.kind === "Case") return getLevel([body.expression]);
888
- if (body.kind === "Witness") return getLevel(body.expressions);
889
- if (body.kind === "Take") return getLevel(body.bounds.map((bound) => bound.set));
1251
+ if (body.kind === "Have" || body.kind === "Case") return getLevel([body.expression], scope);
1252
+ if (body.kind === "Witness") return getLevel(body.expressions, scope);
1253
+ if (body.kind === "Take")
1254
+ return getLevel(
1255
+ body.bounds.map((bound) => bound.set),
1256
+ scope,
1257
+ );
890
1258
  if (body.kind === "Pick") {
891
- return getLevel([body.body, ...body.bounds.map((bound) => bound.set)]);
1259
+ return getLevel([body.body, ...body.bounds.map((bound) => bound.set)], scope);
892
1260
  }
893
1261
  if (body.kind !== "Assert") return 0;
894
1262
  return body.statement.kind === "AssumeProve"
895
- ? analyzeAssumeProve(body.statement, new Map(), analyzer).level
896
- : getLevel([body.statement]);
1263
+ ? analyzeAssumeProve(body.statement, scope, analyzer).level
1264
+ : getLevel([body.statement], scope);
897
1265
  };
1266
+ const checkFacts = (facts: Fact[], scope: Scope) =>
1267
+ facts.forEach((fact) => {
1268
+ if (fact.kind !== "ModuleFact") analyzer.analyze(fact, scope);
1269
+ });
898
1270
  const checkTemporalGoal = (proof: Proof | undefined): SanyError[] =>
899
1271
  proof?.kind !== "Steps"
900
1272
  ? []
901
1273
  : proof.steps.flatMap((step) => {
902
1274
  const location = formatRange(step.statement);
903
- const isConstant = () => getStepLevel(step) === 0;
1275
+ const isConstant = () => getStepLevel(step, new Map()) === 0;
904
1276
  if (
905
1277
  step.body.kind === "Have" ||
906
1278
  step.body.kind === "Take" ||
@@ -920,62 +1292,129 @@ export const checkModuleLevels = (
920
1292
  }
921
1293
  return step.body.kind === "Qed" ? checkTemporalGoal(step.proof) : [];
922
1294
  });
923
- const checkProof = (proof: Proof | undefined): SanyError[] =>
924
- proof?.kind !== "Steps"
925
- ? []
926
- : proof.steps.flatMap((step) => {
927
- const body = step.body;
928
- const isTemporal = () => getStepLevel(step) === TEMPORAL_LEVEL;
929
- const pickErrors =
930
- body.kind === "Pick" && body.bounds.length > 0 && isTemporal()
931
- ? body.bounds
932
- .filter((bound) => getLevel([bound.set]) !== 0)
933
- .flatMap((bound) =>
934
- bound.set.location.range
935
- ? [
936
- {
937
- location: formatRange(bound.set.location.range),
938
- message: "Non-constant bound of temporal PICK.",
939
- },
940
- ]
941
- : [],
942
- )
943
- : [];
944
- return [
945
- ...checkProof(step.proof),
946
- ...pickErrors,
947
- ...(step.proof?.kind === "Steps" && isTemporal() ? checkTemporalGoal(step.proof) : []),
948
- ];
1295
+ const checkProof = (proof: Proof | undefined, scope: Scope): SanyError[] => {
1296
+ if (proof?.kind === "By") {
1297
+ checkFacts(proof.facts, scope);
1298
+ return analyzer.errors.splice(0);
1299
+ }
1300
+ if (proof?.kind !== "Steps") return [];
1301
+ const inner = new Map(scope);
1302
+ return proof.steps.flatMap((step) => {
1303
+ const body = step.body;
1304
+ if (body.kind === "Use" || body.kind === "Hide") checkFacts(body.facts, inner);
1305
+ if (body.kind === "Define") {
1306
+ body.definitions.forEach((definition) => {
1307
+ if (definition.kind === "Instance") return;
1308
+ inner.set(definition.name, { kind: "Let", definition, scope: inner });
1309
+ analyzer.analyzeDefinition(definition, inner);
949
1310
  });
950
- const errors = collectSemanticErrors(
951
- [
952
- ...module.definitions
953
- .filter((definition) => !definition.name.includes("!"))
954
- .map((definition) => ({
955
- location: definition.location,
956
- check: () => analyzer.analyzeDefinition(definition, new Map()),
957
- })),
958
- ...module.assumptions.map((assumption) => ({
959
- location: assumption.location,
960
- check: () => analyzer.analyze(assumption.expression, new Map()),
961
- })),
962
- ...module.theorems.map((theorem) => ({
963
- location: theorem.location,
964
- check: () => {
965
- const data =
966
- theorem.statement.kind === "AssumeProve"
967
- ? analyzeAssumeProve(theorem.statement, new Map(), analyzer)
968
- : analyzer.analyze(theorem.statement, new Map());
969
- const errors = [
970
- ...checkProof(theorem.proof),
971
- ...(data.level === TEMPORAL_LEVEL ? checkTemporalGoal(theorem.proof) : []),
972
- ];
973
- if (errors.length > 0) throw createSanyError(errors);
974
- },
975
- })),
976
- ...instances,
977
- ],
978
- warnings,
979
- );
980
- if (errors.length > 0) throw createSanyError(errors, false, undefined, warnings);
1311
+ }
1312
+ const isTemporal = getStepLevel(step, inner) === TEMPORAL_LEVEL;
1313
+ const pickErrors =
1314
+ body.kind === "Pick" && body.bounds.length > 0 && isTemporal
1315
+ ? body.bounds
1316
+ .filter((bound) => getLevel([bound.set], inner) !== 0)
1317
+ .flatMap((bound) =>
1318
+ bound.set.location.range
1319
+ ? [
1320
+ {
1321
+ location: formatRange(bound.set.location.range),
1322
+ message: "Non-constant bound of temporal PICK.",
1323
+ },
1324
+ ]
1325
+ : [],
1326
+ )
1327
+ : [];
1328
+ return [
1329
+ ...analyzer.errors.splice(0),
1330
+ ...checkProof(step.proof, inner),
1331
+ ...pickErrors,
1332
+ ...(step.proof?.kind === "Steps" && isTemporal ? checkTemporalGoal(step.proof) : []),
1333
+ ];
1334
+ });
1335
+ };
1336
+ const statementLevels = new Map<Expression | AssumeProve, number>();
1337
+ const getStatementLevel = (statement: Expression | AssumeProve) => {
1338
+ const cached = statementLevels.get(statement);
1339
+ if (cached !== undefined) return cached;
1340
+ const level =
1341
+ statement.kind === "AssumeProve"
1342
+ ? analyzeAssumeProve(statement, new Map(), analyzer).level
1343
+ : analyzer.analyze(statement, new Map()).level;
1344
+ statementLevels.set(statement, level);
1345
+ return level;
1346
+ };
1347
+ const statements = [
1348
+ ...module.theorems,
1349
+ ...module.assumptions.map((assumption) => ({
1350
+ ...assumption,
1351
+ statement: assumption.expression,
1352
+ })),
1353
+ ];
1354
+ const statementBodies = new Set(statements.map((statement) => statement.statement));
1355
+ const sections = getRecursiveSections(new Map(), module.units, module.hasRecursiveLet);
1356
+ const createCheck = (location: SourceLocation, run: () => void) => ({
1357
+ location,
1358
+ check: (reported: SanyError[]) => {
1359
+ run();
1360
+ reported.push(...analyzer.errors.splice(0));
1361
+ },
1362
+ });
1363
+ return {
1364
+ sections: sections.map((section) =>
1365
+ createCheck(section.location, () => analyzer.checkRecursiveSection(section.members)),
1366
+ ),
1367
+ check: (isInner: boolean) =>
1368
+ [
1369
+ (isInner ? sections : []).map((section) =>
1370
+ createCheck(section.location, () => analyzer.checkPrimedArguments(section.members)),
1371
+ ),
1372
+ module.definitions
1373
+ .filter(
1374
+ (definition) => !definition.name.includes("!") && !statementBodies.has(definition.body),
1375
+ )
1376
+ .map((definition) =>
1377
+ createCheck(definition.location, () =>
1378
+ analyzer.analyzeDefinition(definition, new Map()),
1379
+ ),
1380
+ ),
1381
+ statements
1382
+ .filter((statement) => statement.name !== undefined)
1383
+ .map((statement) =>
1384
+ createCheck(statement.location, () => getStatementLevel(statement.statement)),
1385
+ ),
1386
+ [
1387
+ ...module.assumptions.map((assumption) => ({
1388
+ location: assumption.location,
1389
+ check: (reported: SanyError[]) => {
1390
+ const level = getStatementLevel(assumption.expression);
1391
+ reported.push(...analyzer.errors.splice(0));
1392
+ const range = assumption.location.range;
1393
+ if (level !== CONSTANT_LEVEL && range) {
1394
+ reported.push({
1395
+ location: formatRange(range),
1396
+ message: `Level error: assumptions must be level 0 (Constant), \nbut this one has level ${level}.`,
1397
+ });
1398
+ }
1399
+ },
1400
+ })),
1401
+ ...module.theorems.map((theorem) => ({
1402
+ location: theorem.location,
1403
+ check: (reported: SanyError[]) => {
1404
+ const level = getStatementLevel(theorem.statement);
1405
+ reported.push(
1406
+ ...analyzer.errors.splice(0),
1407
+ ...checkProof(theorem.proof, new Map()),
1408
+ ...(level === TEMPORAL_LEVEL ? checkTemporalGoal(theorem.proof) : []),
1409
+ ...analyzer.errors.splice(0),
1410
+ );
1411
+ },
1412
+ })),
1413
+ ...module.uses.map((use) =>
1414
+ createCheck(use.location, () => checkFacts(use.facts, new Map())),
1415
+ ),
1416
+ ...instances,
1417
+ ],
1418
+ ].flatMap((units) => collectSemanticErrors(units, warnings)),
1419
+ };
981
1420
  };