tla-ts 0.0.4-dev.0be9567 → 0.0.4-dev.43f28be

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 (311) hide show
  1. package/README.md +27 -141
  2. package/dist/deciders.cjs +366 -0
  3. package/dist/deciders.js +366 -0
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +35 -1
  6. package/dist/index.d.ts +35 -1
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +1 -4
  9. package/dist/parallel-worker.js +1 -4
  10. package/dist/prove-worker.cjs +9 -0
  11. package/dist/prove-worker.d.cts +9 -0
  12. package/dist/prove-worker.d.ts +9 -0
  13. package/dist/prove-worker.js +9 -0
  14. package/dist/prove.cjs +996 -0
  15. package/dist/prove.js +996 -0
  16. package/dist/run-cli.cjs +517 -47
  17. package/dist/run-cli.js +517 -47
  18. package/dist/tlapm.cjs +10 -0
  19. package/dist/tlapm.js +10 -0
  20. package/dist/transfer.cjs +38 -44
  21. package/dist/transfer.js +38 -44
  22. package/dist/worker.cjs +21 -0
  23. package/dist/worker.js +21 -0
  24. package/package.json +21 -12
  25. package/src/check.ts +1 -0
  26. package/src/errors.ts +86 -0
  27. package/src/evaluate.ts +54 -19
  28. package/src/index.ts +10 -0
  29. package/src/{obligation-action.ts → obligations/action.ts} +258 -37
  30. package/src/{obligation-anon.ts → obligations/anon.ts} +13 -7
  31. package/src/obligations/ctx.ts +64 -0
  32. package/src/{obligation-deref.ts → obligations/deref.ts} +2 -2
  33. package/src/{obligation-expression.ts → obligations/expression.ts} +54 -8
  34. package/src/{obligation-format.ts → obligations/format.ts} +6 -5
  35. package/src/{obligation-generate.ts → obligations/generate.ts} +134 -61
  36. package/src/{obligations.ts → obligations/index.ts} +28 -12
  37. package/src/{obligation-levels.ts → obligations/levels.ts} +12 -2
  38. package/src/{obligation-module.ts → obligations/module.ts} +46 -20
  39. package/src/obligations/pickle.ts +100 -0
  40. package/src/obligations/pragma.ts +189 -0
  41. package/src/{obligation-printer.ts → obligations/printer.ts} +9 -63
  42. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -1
  43. package/src/{obligation-source.ts → obligations/source.ts} +91 -35
  44. package/src/obligations/temporal.ts +319 -0
  45. package/src/{obligation-tuples.ts → obligations/tuples.ts} +1 -1
  46. package/src/ocaml-marshal.ts +166 -0
  47. package/src/parallel-worker.ts +2 -18
  48. package/src/parallel.ts +10 -43
  49. package/src/prove/decide-pool.ts +100 -0
  50. package/src/prove/deciders.ts +33 -0
  51. package/src/prove/isabelle/LICENSE +36 -0
  52. package/src/prove/isabelle/LICENSE-tlapm +26 -0
  53. package/src/prove/isabelle/decide.ts +47 -0
  54. package/src/prove/isabelle/encode.ts +508 -0
  55. package/src/prove/isabelle/isar/inner-syntax.ts +579 -0
  56. package/src/prove/isabelle/isar/method.ts +367 -0
  57. package/src/prove/isabelle/isar/proof.ts +28 -0
  58. package/src/prove/isabelle/isar/statement.ts +57 -0
  59. package/src/prove/isabelle/isar/theory.ts +192 -0
  60. package/src/prove/isabelle/isar/type-check.ts +278 -0
  61. package/src/prove/isabelle/provers/blast/blast.ts +258 -0
  62. package/src/prove/isabelle/provers/blast/branch.ts +322 -0
  63. package/src/prove/isabelle/provers/blast/prove.ts +347 -0
  64. package/src/prove/isabelle/provers/blast/rules.ts +330 -0
  65. package/src/prove/isabelle/provers/blast/state.ts +180 -0
  66. package/src/prove/isabelle/provers/blast/term.ts +547 -0
  67. package/src/prove/isabelle/provers/clasimp.ts +150 -0
  68. package/src/prove/isabelle/provers/classical.ts +389 -0
  69. package/src/prove/isabelle/provers/hypsubst.ts +441 -0
  70. package/src/prove/isabelle/pure/bicompose.ts +174 -0
  71. package/src/prove/isabelle/pure/consts.ts +32 -0
  72. package/src/prove/isabelle/pure/conv.ts +79 -0
  73. package/src/prove/isabelle/pure/drule.ts +264 -0
  74. package/src/prove/isabelle/pure/envir.ts +363 -0
  75. package/src/prove/isabelle/pure/goal.ts +53 -0
  76. package/src/prove/isabelle/pure/interrupt.ts +16 -0
  77. package/src/prove/isabelle/pure/list.ts +12 -0
  78. package/src/prove/isabelle/pure/logic.ts +402 -0
  79. package/src/prove/isabelle/pure/name.ts +110 -0
  80. package/src/prove/isabelle/pure/net.ts +262 -0
  81. package/src/prove/isabelle/pure/object-logic.ts +41 -0
  82. package/src/prove/isabelle/pure/pattern.ts +650 -0
  83. package/src/prove/isabelle/pure/raw-simplifier.ts +353 -0
  84. package/src/prove/isabelle/pure/rewriter.ts +602 -0
  85. package/src/prove/isabelle/pure/search.ts +68 -0
  86. package/src/prove/isabelle/pure/seq.ts +156 -0
  87. package/src/prove/isabelle/pure/simplifier.ts +112 -0
  88. package/src/prove/isabelle/pure/table.ts +208 -0
  89. package/src/prove/isabelle/pure/tactic.ts +276 -0
  90. package/src/prove/isabelle/pure/tactical.ts +347 -0
  91. package/src/prove/isabelle/pure/term-ord.ts +159 -0
  92. package/src/prove/isabelle/pure/term.ts +808 -0
  93. package/src/prove/isabelle/pure/thm.ts +806 -0
  94. package/src/prove/isabelle/pure/type.ts +133 -0
  95. package/src/prove/isabelle/pure/unify.ts +753 -0
  96. package/src/prove/isabelle/pure/variable.ts +25 -0
  97. package/src/prove/isabelle/tla/classical-setup.ts +101 -0
  98. package/src/prove/isabelle/tla/context.ts +74 -0
  99. package/src/prove/isabelle/tla/logic-data.ts +5 -0
  100. package/src/prove/isabelle/tla/logic.ts +215 -0
  101. package/src/prove/isabelle/tla/simpdata.ts +241 -0
  102. package/src/prove/isabelle/tools/intuitionistic.ts +132 -0
  103. package/src/prove/ocaml.ts +22 -0
  104. package/src/prove/prep/action.ts +520 -0
  105. package/src/prove/prep/defs.ts +33 -0
  106. package/src/prove/prep/elab.ts +156 -0
  107. package/src/prove/prep/enabled-axioms.ts +189 -0
  108. package/src/prove/prep/enabled.ts +43 -0
  109. package/src/prove/prep/fingerprint.ts +388 -0
  110. package/src/prove/prep/flatten.ts +70 -0
  111. package/src/prove/prep/level-comparison.ts +552 -0
  112. package/src/prove/prep/md5.ts +67 -0
  113. package/src/prove/prep/pragma.ts +221 -0
  114. package/src/prove/prep/trivial.ts +22 -0
  115. package/src/prove/prove-worker.ts +27 -0
  116. package/src/prove/prove.ts +518 -0
  117. package/src/prove/ptl/decide.ts +68 -0
  118. package/src/prove/ptl/encode.ts +256 -0
  119. package/src/prove/ptl/sat.ts +151 -0
  120. package/src/prove/ptl/tableau.ts +276 -0
  121. package/src/prove/smt/axiomatize.ts +69 -0
  122. package/src/prove/smt/axioms.ts +210 -0
  123. package/src/prove/smt/context.ts +108 -0
  124. package/src/prove/smt/data.ts +665 -0
  125. package/src/prove/smt/encode.ts +169 -0
  126. package/src/prove/smt/extensionality.ts +63 -0
  127. package/src/prove/smt/flatten.ts +127 -0
  128. package/src/prove/smt/format.ts +143 -0
  129. package/src/prove/smt/instances.ts +182 -0
  130. package/src/prove/smt/rewrite.ts +784 -0
  131. package/src/prove/smt/simplify.ts +57 -0
  132. package/src/prove/smt/solver/act-cache.ts +265 -0
  133. package/src/prove/smt/solver/arith-rewriter.ts +962 -0
  134. package/src/prove/smt/solver/array.ts +22 -0
  135. package/src/prove/smt/solver/asserted-formulas.ts +469 -0
  136. package/src/prove/smt/solver/ast-lt.ts +157 -0
  137. package/src/prove/smt/solver/ast-util.ts +147 -0
  138. package/src/prove/smt/solver/ast.ts +1315 -0
  139. package/src/prove/smt/solver/auf-solver.ts +572 -0
  140. package/src/prove/smt/solver/case-split-queue.ts +178 -0
  141. package/src/prove/smt/solver/cg-table.ts +175 -0
  142. package/src/prove/smt/solver/clause.ts +276 -0
  143. package/src/prove/smt/solver/conflict-resolution.ts +343 -0
  144. package/src/prove/smt/solver/context.ts +1292 -0
  145. package/src/prove/smt/solver/ctx-simplify.ts +334 -0
  146. package/src/prove/smt/solver/der.ts +224 -0
  147. package/src/prove/smt/solver/dyn-ack.ts +141 -0
  148. package/src/prove/smt/solver/e-matching.ts +659 -0
  149. package/src/prove/smt/solver/enode.ts +259 -0
  150. package/src/prove/smt/solver/expr-ref.ts +21 -0
  151. package/src/prove/smt/solver/expr-safe-replace.ts +172 -0
  152. package/src/prove/smt/solver/fingerprints.ts +92 -0
  153. package/src/prove/smt/solver/flat-literals.ts +51 -0
  154. package/src/prove/smt/solver/goal.ts +138 -0
  155. package/src/prove/smt/solver/hash.ts +173 -0
  156. package/src/prove/smt/solver/hashtable.ts +166 -0
  157. package/src/prove/smt/solver/internalizer.ts +1381 -0
  158. package/src/prove/smt/solver/lbool.ts +5 -0
  159. package/src/prove/smt/solver/literal.ts +24 -0
  160. package/src/prove/smt/solver/lp/bound-propagator.ts +391 -0
  161. package/src/prove/smt/solver/lp/constraints.ts +78 -0
  162. package/src/prove/smt/solver/lp/containers.ts +296 -0
  163. package/src/prove/smt/solver/lp/core-solver.ts +504 -0
  164. package/src/prove/smt/solver/lp/cross-nested.ts +224 -0
  165. package/src/prove/smt/solver/lp/dep-intervals.ts +656 -0
  166. package/src/prove/smt/solver/lp/dependency.ts +51 -0
  167. package/src/prove/smt/solver/lp/dioph-eq.ts +1181 -0
  168. package/src/prove/smt/solver/lp/explanation.ts +46 -0
  169. package/src/prove/smt/solver/lp/gomory.ts +255 -0
  170. package/src/prove/smt/solver/lp/hnf-cutter.ts +125 -0
  171. package/src/prove/smt/solver/lp/hnf.ts +281 -0
  172. package/src/prove/smt/solver/lp/int-cube.ts +295 -0
  173. package/src/prove/smt/solver/lp/int-solver.ts +514 -0
  174. package/src/prove/smt/solver/lp/lar-solver.ts +816 -0
  175. package/src/prove/smt/solver/lp/lar-term.ts +62 -0
  176. package/src/prove/smt/solver/lp/lp-settings.ts +91 -0
  177. package/src/prove/smt/solver/lp/maximize-term.ts +347 -0
  178. package/src/prove/smt/solver/lp/nex-creator.ts +381 -0
  179. package/src/prove/smt/solver/lp/nex.ts +120 -0
  180. package/src/prove/smt/solver/lp/nla-backoff.ts +43 -0
  181. package/src/prove/smt/solver/lp/nla-basics.ts +398 -0
  182. package/src/prove/smt/solver/lp/nla-core.ts +968 -0
  183. package/src/prove/smt/solver/lp/nla-divisions.ts +332 -0
  184. package/src/prove/smt/solver/lp/nla-emonics.ts +373 -0
  185. package/src/prove/smt/solver/lp/nla-factorization.ts +30 -0
  186. package/src/prove/smt/solver/lp/nla-grobner.ts +904 -0
  187. package/src/prove/smt/solver/lp/nla-horner.ts +126 -0
  188. package/src/prove/smt/solver/lp/nla-intervals.ts +265 -0
  189. package/src/prove/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  190. package/src/prove/smt/solver/lp/nla-monotone.ts +59 -0
  191. package/src/prove/smt/solver/lp/nla-order.ts +307 -0
  192. package/src/prove/smt/solver/lp/nla-patcher.ts +112 -0
  193. package/src/prove/smt/solver/lp/nla-tangents.ts +251 -0
  194. package/src/prove/smt/solver/lp/nla-throttle.ts +85 -0
  195. package/src/prove/smt/solver/lp/nla-types.ts +124 -0
  196. package/src/prove/smt/solver/lp/nla-var-eqs.ts +141 -0
  197. package/src/prove/smt/solver/lp/nra-solver.ts +440 -0
  198. package/src/prove/smt/solver/lp/numeric-pair.ts +65 -0
  199. package/src/prove/smt/solver/lp/pdd-interval.ts +31 -0
  200. package/src/prove/smt/solver/lp/pdd-simplifier.ts +184 -0
  201. package/src/prove/smt/solver/lp/pdd-solver.ts +408 -0
  202. package/src/prove/smt/solver/lp/pdd.ts +971 -0
  203. package/src/prove/smt/solver/lp/random-updater.ts +138 -0
  204. package/src/prove/smt/solver/lp/static-matrix.ts +246 -0
  205. package/src/prove/smt/solver/lp/union-find.ts +96 -0
  206. package/src/prove/smt/solver/mam-compiler.ts +847 -0
  207. package/src/prove/smt/solver/mam-interpreter.ts +400 -0
  208. package/src/prove/smt/solver/maximize-ac-sharing.ts +118 -0
  209. package/src/prove/smt/solver/model-checker.ts +347 -0
  210. package/src/prove/smt/solver/model-evaluator.ts +262 -0
  211. package/src/prove/smt/solver/model-finder.ts +155 -0
  212. package/src/prove/smt/solver/model-generator.ts +97 -0
  213. package/src/prove/smt/solver/model-macro-solver.ts +728 -0
  214. package/src/prove/smt/solver/nlsat/algebraic.ts +1161 -0
  215. package/src/prove/smt/solver/nlsat/atoms.ts +238 -0
  216. package/src/prove/smt/solver/nlsat/evaluator.ts +303 -0
  217. package/src/prove/smt/solver/nlsat/explain.ts +607 -0
  218. package/src/prove/smt/solver/nlsat/interval-set.ts +351 -0
  219. package/src/prove/smt/solver/nlsat/levelwise.ts +740 -0
  220. package/src/prove/smt/solver/nlsat/mpbq.ts +161 -0
  221. package/src/prove/smt/solver/nlsat/polynomial.ts +1722 -0
  222. package/src/prove/smt/solver/nlsat/solver.ts +911 -0
  223. package/src/prove/smt/solver/nlsat/types.ts +43 -0
  224. package/src/prove/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  225. package/src/prove/smt/solver/nlsat/upolynomial.ts +996 -0
  226. package/src/prove/smt/solver/nnf.ts +469 -0
  227. package/src/prove/smt/solver/pattern-inference.ts +351 -0
  228. package/src/prove/smt/solver/poly-rewriter.ts +477 -0
  229. package/src/prove/smt/solver/propagate-values.ts +83 -0
  230. package/src/prove/smt/solver/proto-model.ts +551 -0
  231. package/src/prove/smt/solver/pull-quant.ts +139 -0
  232. package/src/prove/smt/solver/qe-lite-der.ts +526 -0
  233. package/src/prove/smt/solver/qe-lite-fm.ts +576 -0
  234. package/src/prove/smt/solver/qe-lite.ts +381 -0
  235. package/src/prove/smt/solver/qi-queue.ts +362 -0
  236. package/src/prove/smt/solver/quant-tactics.ts +117 -0
  237. package/src/prove/smt/solver/quantifier-analyzer.ts +562 -0
  238. package/src/prove/smt/solver/quantifier-manager.ts +186 -0
  239. package/src/prove/smt/solver/random-gen.ts +10 -0
  240. package/src/prove/smt/solver/rational.ts +165 -0
  241. package/src/prove/smt/solver/ref-vector.ts +62 -0
  242. package/src/prove/smt/solver/relevancy.ts +247 -0
  243. package/src/prove/smt/solver/rewriter-tpl.ts +1159 -0
  244. package/src/prove/smt/solver/rewriter.ts +843 -0
  245. package/src/prove/smt/solver/rlimit.ts +79 -0
  246. package/src/prove/smt/solver/smtlib-parser.ts +526 -0
  247. package/src/prove/smt/solver/solver.ts +71 -0
  248. package/src/prove/smt/solver/sort.ts +35 -0
  249. package/src/prove/smt/solver/sticky-generations.ts +69 -0
  250. package/src/prove/smt/solver/theory-lra-axioms.ts +340 -0
  251. package/src/prove/smt/solver/theory-lra-bounds.ts +226 -0
  252. package/src/prove/smt/solver/theory-lra-final-check.ts +252 -0
  253. package/src/prove/smt/solver/theory-lra-internalize.ts +476 -0
  254. package/src/prove/smt/solver/theory-lra-model.ts +243 -0
  255. package/src/prove/smt/solver/theory-lra-propagate.ts +405 -0
  256. package/src/prove/smt/solver/theory-lra-state.ts +43 -0
  257. package/src/prove/smt/solver/theory-lra.ts +56 -0
  258. package/src/prove/smt/solver/var-subst.ts +258 -0
  259. package/src/prove/smt/solver/z3-license.txt +10 -0
  260. package/src/prove/smt/table.ts +170 -0
  261. package/src/prove/tlapm/tlapm.ts +97 -0
  262. package/src/prove/tlaps-module.ts +510 -0
  263. package/src/prove/verdict.ts +18 -0
  264. package/src/prove/zenon/LICENSE +32 -0
  265. package/src/prove/zenon/check/check.ts +105 -0
  266. package/src/prove/zenon/check/definitions.ts +144 -0
  267. package/src/prove/zenon/check/equality.ts +182 -0
  268. package/src/prove/zenon/check/functions.ts +62 -0
  269. package/src/prove/zenon/check/keys.ts +125 -0
  270. package/src/prove/zenon/check/propositional.ts +104 -0
  271. package/src/prove/zenon/check/records.ts +188 -0
  272. package/src/prove/zenon/check/relations.ts +121 -0
  273. package/src/prove/zenon/check/rewrites.ts +224 -0
  274. package/src/prove/zenon/check/sets.ts +302 -0
  275. package/src/prove/zenon/check/terms.ts +127 -0
  276. package/src/prove/zenon/check/tla.ts +126 -0
  277. package/src/prove/zenon/decide.ts +113 -0
  278. package/src/prove/zenon/encode.ts +444 -0
  279. package/src/prove/zenon/eqrel.ts +300 -0
  280. package/src/prove/zenon/equality-rules.ts +435 -0
  281. package/src/prove/zenon/expr.ts +551 -0
  282. package/src/prove/zenon/index-table.ts +350 -0
  283. package/src/prove/zenon/isar-case.ts +513 -0
  284. package/src/prove/zenon/isar.ts +1249 -0
  285. package/src/prove/zenon/limits.ts +15 -0
  286. package/src/prove/zenon/llproof.ts +173 -0
  287. package/src/prove/zenon/mltoll.ts +1566 -0
  288. package/src/prove/zenon/node.ts +297 -0
  289. package/src/prove/zenon/ocaml.ts +169 -0
  290. package/src/prove/zenon/parse.ts +247 -0
  291. package/src/prove/zenon/phrase.ts +191 -0
  292. package/src/prove/zenon/proof.ts +198 -0
  293. package/src/prove/zenon/propositional-rules.ts +387 -0
  294. package/src/prove/zenon/rules.ts +94 -0
  295. package/src/prove/zenon/search.ts +288 -0
  296. package/src/prove/zenon/tla/functions.ts +151 -0
  297. package/src/prove/zenon/tla/llproof.ts +480 -0
  298. package/src/prove/zenon/tla/records.ts +225 -0
  299. package/src/prove/zenon/tla/rewrites.ts +447 -0
  300. package/src/prove/zenon/tla/sets.ts +304 -0
  301. package/src/prove/zenon/tla/terms.ts +181 -0
  302. package/src/prove/zenon/tla/tla.ts +506 -0
  303. package/src/run-cli.ts +338 -62
  304. package/src/successors.ts +24 -5
  305. package/src/tlapm-cache.ts +244 -0
  306. package/src/tlc-random.ts +55 -32
  307. package/src/tlc-version.ts +8 -7
  308. package/src/values.ts +47 -4
  309. package/src/worker.ts +65 -0
  310. package/dist/parallel.cjs +0 -12
  311. package/dist/parallel.js +0 -12
@@ -0,0 +1,911 @@
1
+ // Ported from Z3 (src/nlsat/nlsat_solver.cpp, src/nlsat/nlsat_justification.h), MIT license, see
2
+ // z3-license.txt. The nlsat search of Jovanovic and de Moura: Boolean variables first, then the
3
+ // arithmetic variables in order, each a stage. A stage assigns its variable outside the intervals
4
+ // that the clauses watching it exclude, and a conflict learns the explanation of the excluded
5
+ // line. Only Z3's default nlsat parameters are ported: lazy 0, simplify_conflicts, reorder and
6
+ // randomize on, shuffle_vars, inline_vars, minimize_conflicts and check_lemmas off, seed 0. So
7
+ // nlsat_simplify and the bounds of eliminated variables, which only inline_vars makes, are not
8
+ // ported. Neither are what nra never uses: Boolean variables beyond true, transcendental
9
+ // constraints, check(assumptions), check_limit, retract, and set_max_var, without which
10
+ // select_witness never picks the maximal value. The search counts its steps against the resource
11
+ // limit, but not the memory, which Z3 also bounds by max_memory.
12
+ import { SmtCanceledError } from "../../../../errors";
13
+ import { L_FALSE, L_TRUE, L_UNDEF } from "../lbool";
14
+ import { type Dependency, linearize, mkJoin, mkLeaf } from "../lp/dependency";
15
+ import { RandomGen } from "../random-gen";
16
+ import { Rational } from "../rational";
17
+ import type { ResourceLimit } from "../rlimit";
18
+ import { AlgebraicManager, Anum } from "./algebraic";
19
+ import { AtomTable, FALSE_LITERAL, ScopedLiterals, TRUE_LITERAL } from "./atoms";
20
+ import { Evaluator } from "./evaluator";
21
+ import { Explain } from "./explain";
22
+ import type { IntervalSet } from "./interval-set";
23
+ import { NULL_VAR, type Polynomial, PolynomialCache, PolynomialManager } from "./polynomial";
24
+ import { type Clause, type IneqAtom, type IneqKind, isIneqAtom } from "./types";
25
+
26
+ // null_bool_var: past every Boolean variable.
27
+ const NULL_BOOL_VAR = Infinity;
28
+
29
+ // m_restart_threshold: the conflicts between two reorderings of the variables.
30
+ const RESTART_THRESHOLD = 10000;
31
+
32
+ type Justification =
33
+ | { kind: "decision" }
34
+ | { kind: "clause"; clause: Clause }
35
+ | { kind: "lazy"; literals: number[]; clauses: Clause[] };
36
+
37
+ const DECISION: Justification = { kind: "decision" };
38
+
39
+ type Trail =
40
+ | { kind: "assignment"; boolVar: number }
41
+ | { kind: "infeasible"; old: IntervalSet | null }
42
+ | { kind: "level" }
43
+ | { kind: "stage" }
44
+ | { kind: "eq"; old: IneqAtom | null };
45
+
46
+ export class NlsatSolver {
47
+ readonly pm = new PolynomialManager();
48
+ readonly am = new AlgebraicManager();
49
+ private cache = new PolynomialCache(this.pm);
50
+ private bvalues: number[] = [];
51
+ private levels: number[] = [];
52
+ private justifications: (Justification | null)[] = [];
53
+ private bwatches: Clause[][] = [];
54
+ private isDead: boolean[] = [];
55
+ private atoms = new AtomTable(this.pm, this.cache, {
56
+ onMk: (boolVar) => {
57
+ this.bvalues[boolVar] = L_UNDEF;
58
+ this.levels[boolVar] = Infinity;
59
+ this.justifications[boolVar] = null;
60
+ this.bwatches[boolVar] = [];
61
+ this.isDead[boolVar] = false;
62
+ },
63
+ onDelete: (boolVar) => {
64
+ this.isDead[boolVar] = true;
65
+ this.bvalues[boolVar] = L_UNDEF;
66
+ },
67
+ });
68
+ private assignment: (Anum | undefined)[] = [];
69
+ private evaluator = new Evaluator(this.pm, this.am, this.assignment);
70
+ private ism = this.evaluator.ism;
71
+ private clauses: Clause[] = [];
72
+ private learned: Clause[] = [];
73
+ private nextClauseId = 0;
74
+ private isInt: boolean[] = [];
75
+ private watches: Clause[][] = [];
76
+ private infeasible: (IntervalSet | null)[] = [];
77
+ private var2eq: (IneqAtom | null)[] = [];
78
+ // perm: internal to external variables. invPerm: external to internal.
79
+ private perm: number[] = [];
80
+ private invPerm: number[] = [];
81
+ private explain = new Explain(this.pm, this.am, this.cache, {
82
+ atoms: this.atoms,
83
+ sample: this.assignment,
84
+ getValue: (literal) => this.value(literal),
85
+ var2eq: this.var2eq,
86
+ });
87
+ private bk = 0;
88
+ private xk = NULL_VAR;
89
+ private scopeLevel = 0;
90
+ private trail: Trail[] = [];
91
+ private marks: boolean[] = [];
92
+ private markCount = 0;
93
+ private lemma = new ScopedLiterals(this.atoms);
94
+ private lazyClause = new ScopedLiterals(this.atoms);
95
+ private lemmaAssumptions: Dependency = null;
96
+ private randomSeed = 0;
97
+ private isReordered = false;
98
+ // max_conflicts: nra sets it before each check.
99
+ maxConflicts = Infinity;
100
+ readonly stats = {
101
+ conflicts: 0,
102
+ restarts: 0,
103
+ propagations: 0,
104
+ decisions: 0,
105
+ stages: 0,
106
+ irrationalAssignments: 0,
107
+ };
108
+
109
+ // m_rlimit: the steps of the search count against the limit, and against the budget of this
110
+ // solver, which Z3 sets with a scoped_rlimit on a child limit.
111
+ steps = 0;
112
+
113
+ constructor(
114
+ private limit: ResourceLimit | null = null,
115
+ private budget = Infinity,
116
+ ) {
117
+ // mk_true_bvar: the clause [true], whose literal the first Boolean stage assigns.
118
+ this.mkClause([TRUE_LITERAL], false, null);
119
+ }
120
+
121
+ private checkpoint() {
122
+ this.steps++;
123
+ if ((this.limit !== null && !this.limit.inc()) || this.steps > this.budget)
124
+ throw new SmtCanceledError();
125
+ }
126
+
127
+ mkVar(isInt: boolean) {
128
+ const variable = this.isInt.length;
129
+ this.isInt.push(isInt);
130
+ this.watches.push([]);
131
+ this.infeasible.push(null);
132
+ this.var2eq.push(null);
133
+ this.perm.push(variable);
134
+ this.invPerm.push(variable);
135
+ return variable;
136
+ }
137
+
138
+ mkIneqLiteral(kind: IneqKind, polynomials: readonly Polynomial[], isEven: readonly boolean[]) {
139
+ return this.atoms.mkIneqLiteral(kind, polynomials, isEven);
140
+ }
141
+
142
+ getAtom(literal: number) {
143
+ return this.atoms.getAtom(literal);
144
+ }
145
+
146
+ // mk_external_clause: an input clause, which depends on assumption when it is not null.
147
+ mkExternalClause(literals: readonly number[], assumption: number | null) {
148
+ this.mkClause(literals, false, assumption === null ? null : mkLeaf(assumption));
149
+ }
150
+
151
+ // value(x): the model's value of x, zero when unassigned.
152
+ getValue(variable: number) {
153
+ return this.assignment[variable] ?? new Anum(Rational.zero);
154
+ }
155
+
156
+ // get_core: the assumptions of the input clauses the last conflict depends on.
157
+ getCore() {
158
+ return linearize([this.lemmaAssumptions]);
159
+ }
160
+
161
+ private getMaxVar(clause: Clause) {
162
+ let result = NULL_VAR;
163
+ for (const literal of clause.literals) {
164
+ const atom = this.atoms.getAtom(literal);
165
+ if (atom !== null && (result === NULL_VAR || atom.maxVar > result)) result = atom.maxVar;
166
+ }
167
+ return result;
168
+ }
169
+
170
+ private getClauseDegree(clause: Clause) {
171
+ if (this.getMaxVar(clause) === NULL_VAR) return 0;
172
+ let max = 0;
173
+ for (const literal of clause.literals) {
174
+ const atom = this.atoms.getAtom(literal);
175
+ if (atom !== null) max = Math.max(max, this.atoms.getDegree(atom));
176
+ }
177
+ return max;
178
+ }
179
+
180
+ // lit_lt: Boolean literals first, then by maximal variable, degree, inequalities before
181
+ // equations, and index.
182
+ private compareLiterals(first: number, second: number) {
183
+ const firstAtom = this.atoms.getAtom(first);
184
+ const secondAtom = this.atoms.getAtom(second);
185
+ if (firstAtom === null || secondAtom === null) {
186
+ if (firstAtom === null && secondAtom === null) return first - second;
187
+ return firstAtom === null ? -1 : 1;
188
+ }
189
+ if (firstAtom.maxVar !== secondAtom.maxVar) return firstAtom.maxVar - secondAtom.maxVar;
190
+ const firstDegree = this.atoms.getDegree(firstAtom);
191
+ const secondDegree = this.atoms.getDegree(secondAtom);
192
+ if (firstDegree !== secondDegree) return firstDegree - secondDegree;
193
+ const isFirstEq = firstAtom.kind === "EQ";
194
+ const isSecondEq = secondAtom.kind === "EQ";
195
+ if (isFirstEq !== isSecondEq) return isFirstEq ? 1 : -1;
196
+ return first - second;
197
+ }
198
+
199
+ private mkClause(literals: readonly number[], isLearned: boolean, assumptions: Dependency) {
200
+ const clause: Clause = {
201
+ id: this.nextClauseId++,
202
+ literals: literals.length === 0 ? [FALSE_LITERAL] : [...literals],
203
+ isLearned,
204
+ assumptions,
205
+ isActive: false,
206
+ };
207
+ for (const literal of clause.literals) this.atoms.incRef(literal);
208
+ clause.literals.sort((first, second) => this.compareLiterals(first, second));
209
+ (isLearned ? this.learned : this.clauses).push(clause);
210
+ this.addClauseToWatches(clause);
211
+ return clause;
212
+ }
213
+
214
+ private addClauseToWatches(clause: Clause) {
215
+ const variable = this.getMaxVar(clause);
216
+ if (variable !== NULL_VAR) this.watches[variable].push(clause);
217
+ else this.bwatches[Math.max(...clause.literals.map((literal) => literal >> 1))].push(clause);
218
+ }
219
+
220
+ private delClause(clause: Clause) {
221
+ const variable = this.getMaxVar(clause);
222
+ const watches =
223
+ variable !== NULL_VAR
224
+ ? this.watches[variable]
225
+ : this.bwatches[Math.max(...clause.literals.map((literal) => literal >> 1))];
226
+ const index = watches.indexOf(clause);
227
+ if (index !== -1) watches.splice(index, 1);
228
+ for (const literal of clause.literals) this.atoms.decRef(literal);
229
+ }
230
+
231
+ // Search.
232
+
233
+ private unassignBoolVar(boolVar: number) {
234
+ this.bvalues[boolVar] = L_UNDEF;
235
+ this.levels[boolVar] = Infinity;
236
+ this.justifications[boolVar] = null;
237
+ if (this.atoms.atoms[boolVar] === null && boolVar < this.bk) this.bk = boolVar;
238
+ }
239
+
240
+ private undoUntil(predicate: () => boolean) {
241
+ while (predicate() && this.trail.length > 0) {
242
+ const entry = this.trail[this.trail.length - 1];
243
+ switch (entry.kind) {
244
+ case "assignment":
245
+ this.unassignBoolVar(entry.boolVar);
246
+ break;
247
+ case "infeasible":
248
+ if (this.xk !== NULL_VAR && this.xk < this.infeasible.length)
249
+ this.infeasible[this.xk] = entry.old;
250
+ break;
251
+ case "stage":
252
+ if (this.xk === 0) this.xk = NULL_VAR;
253
+ else if (this.xk !== NULL_VAR) this.assignment[--this.xk] = undefined;
254
+ break;
255
+ case "level":
256
+ this.scopeLevel--;
257
+ break;
258
+ case "eq":
259
+ if (this.xk !== NULL_VAR && this.var2eq.length > this.xk)
260
+ this.var2eq[this.xk] = entry.old;
261
+ break;
262
+ }
263
+ this.trail.pop();
264
+ }
265
+ }
266
+
267
+ private undoUntilLevel(level: number) {
268
+ this.undoUntil(() => this.scopeLevel > level);
269
+ }
270
+
271
+ private undoUntilStage(variable: number) {
272
+ this.undoUntil(() => this.xk !== variable);
273
+ }
274
+
275
+ private newLevel() {
276
+ this.scopeLevel++;
277
+ this.trail.push({ kind: "level" });
278
+ }
279
+
280
+ private getAssignedValue(literal: number) {
281
+ const value = this.bvalues[literal >> 1];
282
+ return (literal & 1) === 1 ? -value : value;
283
+ }
284
+
285
+ private setLiteralToTrue(literal: number, justification: Justification) {
286
+ if (justification.kind === "decision") this.stats.decisions++;
287
+ else this.stats.propagations++;
288
+ const boolVar = literal >> 1;
289
+ this.bvalues[boolVar] = (literal & 1) === 1 ? L_FALSE : L_TRUE;
290
+ this.levels[boolVar] = this.scopeLevel;
291
+ this.justifications[boolVar] = justification;
292
+ this.trail.push({ kind: "assignment", boolVar });
293
+ this.updateEq(boolVar, justification);
294
+ }
295
+
296
+ private decideLiteral(literal: number) {
297
+ this.newLevel();
298
+ this.setLiteralToTrue(literal, DECISION);
299
+ }
300
+
301
+ // value: the assigned value, else the atom's value once its maximal variable is assigned.
302
+ private value(literal: number) {
303
+ const assigned = this.getAssignedValue(literal);
304
+ if (assigned !== L_UNDEF) return assigned;
305
+ const atom = this.atoms.getAtom(literal);
306
+ if (atom === null || this.assignment[atom.maxVar] === undefined) return L_UNDEF;
307
+ return this.evaluator.eval(atom, (literal & 1) === 1) ? L_TRUE : L_FALSE;
308
+ }
309
+
310
+ private isClauseSatisfied(clause: Clause) {
311
+ return clause.literals.some((literal) => this.value(literal) === L_TRUE);
312
+ }
313
+
314
+ private processBooleanClause(clause: Clause) {
315
+ let undefCount = 0;
316
+ let selected = -1;
317
+ for (const [index, literal] of clause.literals.entries()) {
318
+ if (this.value(literal) === L_FALSE) continue;
319
+ undefCount++;
320
+ if (selected === -1) selected = index;
321
+ }
322
+ if (undefCount === 0) return false;
323
+ if (undefCount === 1)
324
+ this.setLiteralToTrue(clause.literals[selected], { kind: "clause", clause });
325
+ else this.decideLiteral(clause.literals[selected]);
326
+ return true;
327
+ }
328
+
329
+ // R_propagate: literal is true, because with the justifications of set it is infeasible.
330
+ private propagate(literal: number, set: IntervalSet | null, isLiteralIncluded = true) {
331
+ const justifications = this.ism.getJustifications(set);
332
+ const literals = [...justifications.literals];
333
+ if (isLiteralIncluded) literals.push(literal ^ 1);
334
+ this.setLiteralToTrue(literal, { kind: "lazy", literals, clauses: justifications.clauses });
335
+ }
336
+
337
+ private updateInfeasible(set: IntervalSet | null) {
338
+ const old = this.infeasible[this.xk];
339
+ this.trail.push({ kind: "infeasible", old });
340
+ this.infeasible[this.xk] = this.ism.mkUnion(set, old);
341
+ }
342
+
343
+ // updt_eq: the equation of least degree that holds for the current variable, for the
344
+ // explanation to simplify with.
345
+ private updateEq(boolVar: number, justification: Justification) {
346
+ if (this.bvalues[boolVar] !== L_TRUE) return;
347
+ const atom = this.atoms.atoms[boolVar];
348
+ if (
349
+ atom === null ||
350
+ !isIneqAtom(atom) ||
351
+ atom.kind !== "EQ" ||
352
+ atom.polynomials.length > 1 ||
353
+ atom.isEven[0]
354
+ )
355
+ return;
356
+ if (justification.kind === "clause" && justification.clause.assumptions !== null) return;
357
+ if (
358
+ justification.kind === "lazy" &&
359
+ (justification.clauses.length > 0 || justification.literals.length > 0)
360
+ )
361
+ return;
362
+ const old = this.var2eq[this.xk];
363
+ if (old !== null && this.atoms.getDegree(old) <= this.atoms.getDegree(atom)) return;
364
+ this.trail.push({ kind: "eq", old });
365
+ this.var2eq[this.xk] = atom;
366
+ }
367
+
368
+ private processArithClause(clause: Clause) {
369
+ let undefCount = 0;
370
+ let selected = -1;
371
+ let selectedSet: IntervalSet | null = null;
372
+ const xkSet = this.infeasible[this.xk];
373
+ for (const [index, literal] of clause.literals.entries()) {
374
+ this.checkpoint();
375
+ if (this.value(literal) === L_FALSE) continue;
376
+ if (this.value(literal) === L_TRUE) return true;
377
+ const atom = this.atoms.getAtom(literal)!;
378
+ const set = this.evaluator.infeasibleIntervals(atom, (literal & 1) === 1, clause);
379
+ if (set === null) {
380
+ this.propagate(literal, null);
381
+ return true;
382
+ }
383
+ if (this.ism.isFull(set)) {
384
+ this.propagate(literal ^ 1, null);
385
+ continue;
386
+ }
387
+ if (this.ism.subset(set, xkSet)) {
388
+ this.propagate(literal, xkSet);
389
+ return true;
390
+ }
391
+ const union = this.ism.mkUnion(set, xkSet);
392
+ if (this.ism.isFull(union)) {
393
+ this.propagate(literal ^ 1, union, false);
394
+ continue;
395
+ }
396
+ undefCount++;
397
+ if (selected === -1) {
398
+ selected = index;
399
+ selectedSet = set;
400
+ }
401
+ }
402
+ if (undefCount === 0) return false;
403
+ if (undefCount === 1)
404
+ this.setLiteralToTrue(clause.literals[selected], { kind: "clause", clause });
405
+ else this.decideLiteral(clause.literals[selected]);
406
+ this.updateInfeasible(selectedSet);
407
+ return true;
408
+ }
409
+
410
+ private processClause(clause: Clause) {
411
+ if (this.isClauseSatisfied(clause)) return true;
412
+ return this.xk === NULL_VAR
413
+ ? this.processBooleanClause(clause)
414
+ : this.processArithClause(clause);
415
+ }
416
+
417
+ private processClauses(clauses: readonly Clause[]) {
418
+ for (const clause of clauses) if (!this.processClause(clause)) return clause;
419
+ return null;
420
+ }
421
+
422
+ private peekNextBoolVar() {
423
+ for (; this.bk < this.atoms.atoms.length; this.bk++)
424
+ if (
425
+ !this.isDead[this.bk] &&
426
+ this.atoms.atoms[this.bk] === null &&
427
+ this.bvalues[this.bk] === L_UNDEF
428
+ )
429
+ return;
430
+ this.bk = NULL_BOOL_VAR;
431
+ }
432
+
433
+ private newStage() {
434
+ this.stats.stages++;
435
+ this.trail.push({ kind: "stage" });
436
+ this.xk = this.xk === NULL_VAR ? 0 : this.xk + 1;
437
+ }
438
+
439
+ // select_witness: a value outside the infeasible intervals, at random among the candidates.
440
+ private selectWitness() {
441
+ const witness = this.ism.pickInComplement(this.infeasible[this.xk], true);
442
+ if (!this.am.isRational(witness)) this.stats.irrationalAssignments++;
443
+ this.assignment[this.xk] = witness;
444
+ }
445
+
446
+ private search() {
447
+ this.bk = 0;
448
+ this.xk = NULL_VAR;
449
+ while (true) {
450
+ if (this.stats.conflicts > 0 && this.stats.conflicts % RESTART_THRESHOLD === 0)
451
+ this.reorderAtRestart();
452
+ if (this.xk === NULL_VAR) {
453
+ this.peekNextBoolVar();
454
+ if (this.bk === NULL_BOOL_VAR) this.newStage();
455
+ } else this.newStage();
456
+ if (this.bk === NULL_BOOL_VAR && this.xk >= this.isInt.length) return L_TRUE;
457
+ while (true) {
458
+ this.checkpoint();
459
+ const conflict = this.processClauses(
460
+ this.xk === NULL_VAR ? this.bwatches[this.bk] : this.watches[this.xk],
461
+ );
462
+ if (conflict === null) break;
463
+ if (!this.resolve(conflict)) return L_FALSE;
464
+ if (this.stats.conflicts >= this.maxConflicts) return L_UNDEF;
465
+ }
466
+ if (this.xk === NULL_VAR) {
467
+ if (this.bvalues[this.bk] === L_UNDEF) {
468
+ this.decideLiteral(2 * this.bk + 1);
469
+ this.bk++;
470
+ }
471
+ } else this.selectWitness();
472
+ }
473
+ }
474
+
475
+ // gc: drops the learned clauses that took no part in a conflict since the last collection,
476
+ // once they outnumber the input clauses four to one.
477
+ private gc() {
478
+ if (this.learned.length <= 4 * this.clauses.length) return;
479
+ this.resetWatches();
480
+ this.atoms.reinitCache();
481
+ let kept = 0;
482
+ for (const [index, clause] of this.learned.entries()) {
483
+ if (index - kept < this.clauses.length && clause.literals.length > 1 && !clause.isActive)
484
+ this.delClause(clause);
485
+ else {
486
+ this.learned[kept++] = clause;
487
+ clause.isActive = false;
488
+ }
489
+ }
490
+ this.learned.length = kept;
491
+ this.reattachArithClauses(this.clauses);
492
+ this.reattachArithClauses(this.learned);
493
+ }
494
+
495
+ private undoToBase() {
496
+ this.initSearch();
497
+ this.bk = 0;
498
+ this.xk = NULL_VAR;
499
+ }
500
+
501
+ // do_reorder
502
+ private reorderAtRestart() {
503
+ this.undoToBase();
504
+ this.stats.restarts++;
505
+ this.stats.conflicts++;
506
+ if (this.isReordered) this.restoreOrder();
507
+ this.applyReorder();
508
+ }
509
+
510
+ // try_reorder
511
+ private tryReorder() {
512
+ this.gc();
513
+ if (this.stats.restarts % 10 !== 0) return;
514
+ if (this.isReordered) this.restoreOrder();
515
+ this.applyReorder();
516
+ }
517
+
518
+ // search_check: the search, again after each model that gives an integer variable a fraction,
519
+ // with the lemma that the variable lies outside the open interval between the integers around
520
+ // its value.
521
+ private searchCheck() {
522
+ this.stats.conflicts = 0;
523
+ this.stats.restarts = 0;
524
+ while (true) {
525
+ const result = this.search();
526
+ if (result !== L_TRUE) return result;
527
+ this.stats.restarts++;
528
+ this.tryReorder();
529
+ const bounds: [number, Rational][] = [];
530
+ for (let variable = 0; variable < this.isInt.length; variable++) {
531
+ const value = this.assignment[variable];
532
+ if (!this.isInt[variable] || value === undefined || this.am.isInt(value)) continue;
533
+ const below = this.am.intLt(value).value;
534
+ if (!(below instanceof Rational)) continue;
535
+ let lower = below;
536
+ while (true) {
537
+ lower = lower.add(Rational.one);
538
+ if (this.am.compare(value, new Anum(lower)) <= 0) {
539
+ lower = lower.sub(Rational.one);
540
+ break;
541
+ }
542
+ }
543
+ bounds.push([variable, lower]);
544
+ }
545
+ if (bounds.length === 0) return result;
546
+ this.initSearch();
547
+ for (const bound of bounds) {
548
+ this.lemma.reset();
549
+ const below = this.pm.mkLinear([1n], [bound[0]], -bound[1].num);
550
+ this.lemma.push(this.mkIneqLiteral("GT", [below], [false]) ^ 1);
551
+ const above = this.pm.mkLinear([1n], [bound[0]], -bound[1].num - 1n);
552
+ this.lemma.push(this.mkIneqLiteral("LT", [above], [false]) ^ 1);
553
+ this.mkClause(this.lemma.literals, true, null);
554
+ }
555
+ }
556
+ }
557
+
558
+ private initSearch() {
559
+ this.undoUntil(() => true);
560
+ while (this.scopeLevel > 0) this.scopeLevel--;
561
+ this.xk = NULL_VAR;
562
+ this.bvalues.fill(L_UNDEF);
563
+ this.assignment.length = 0;
564
+ }
565
+
566
+ // check: satisfiable, unsatisfiable or unknown once maxConflicts conflicts passed. The variables
567
+ // are reordered for the search and restored after it.
568
+ check() {
569
+ this.initSearch();
570
+ this.explain.isFullDimensional = this.clauses.every((clause) =>
571
+ clause.literals.every((literal) => this.isFullDimensional(literal)),
572
+ );
573
+ const isReordered = this.canReorder();
574
+ if (isReordered) this.reorderHeuristically();
575
+ for (const watches of this.watches) this.sortClausesByDegree(watches);
576
+ const result = this.searchCheck();
577
+ if (isReordered) this.restoreOrder();
578
+ return result;
579
+ }
580
+
581
+ private isFullDimensional(literal: number) {
582
+ const atom = this.atoms.getAtom(literal);
583
+ if (atom === null) return true;
584
+ const isNeg = (literal & 1) === 1;
585
+ switch (atom.kind) {
586
+ case "EQ":
587
+ case "ROOT_EQ":
588
+ case "ROOT_LE":
589
+ case "ROOT_GE":
590
+ return isNeg;
591
+ default:
592
+ return !isNeg;
593
+ }
594
+ }
595
+
596
+ // sort_clauses_by_degree
597
+ private sortClausesByDegree(clauses: Clause[]) {
598
+ if (clauses.length <= 1) return;
599
+ const degrees = clauses.map((clause) => this.getClauseDegree(clause));
600
+ const order = clauses
601
+ .map((_clause, index) => index)
602
+ .sort((first, second) => degrees[first] - degrees[second] || first - second);
603
+ const sorted = order.map((index) => clauses[index]);
604
+ for (let index = 0; index < sorted.length; index++) clauses[index] = sorted[index];
605
+ }
606
+
607
+ // check(rvalues, clause): the assignment's verdict on the clauses. A falsified clause gives the
608
+ // literal of least degree among the falsified clauses, and the lemma of the linear cell around
609
+ // the assignment in which that literal stays false. Like Z3, only that case restores the
610
+ // assignment.
611
+ checkAssignment(values: readonly (Anum | undefined)[]) {
612
+ const saved = this.assignment.map((value) =>
613
+ value === undefined ? undefined : this.am.copy(value),
614
+ );
615
+ this.setAssignment(values);
616
+ let best: number | null = null;
617
+ let result = L_TRUE;
618
+ for (const clause of this.clauses) {
619
+ const literalValues = clause.literals.map((literal) => this.value(literal));
620
+ if (literalValues.some((value) => value === L_TRUE)) continue;
621
+ if (!literalValues.every((value) => value === L_FALSE)) {
622
+ result = L_UNDEF;
623
+ continue;
624
+ }
625
+ for (const literal of clause.literals)
626
+ if (
627
+ best === null ||
628
+ this.atoms.getDegree(this.atoms.getAtom(literal)!) <
629
+ this.atoms.getDegree(this.atoms.getAtom(best)!)
630
+ )
631
+ best = literal;
632
+ }
633
+ if (best === null) return { result, clause: [] };
634
+ this.lazyClause.reset();
635
+ this.explain.computeLinearExplanation([best], this.lazyClause);
636
+ const clause = [...this.lazyClause.literals, best ^ 1];
637
+ this.setAssignment(saved);
638
+ return { result: L_FALSE, clause };
639
+ }
640
+
641
+ private setAssignment(values: readonly (Anum | undefined)[]) {
642
+ this.assignment.length = 0;
643
+ for (const [variable, value] of values.entries())
644
+ this.assignment[variable] = value === undefined ? undefined : this.am.copy(value);
645
+ }
646
+
647
+ // Conflict resolution.
648
+
649
+ private processAntecedent(antecedent: number) {
650
+ this.checkpoint();
651
+ const boolVar = antecedent >> 1;
652
+ if (this.getAssignedValue(antecedent) === L_UNDEF) {
653
+ this.checkpoint();
654
+ if (!this.marks[boolVar]) {
655
+ this.marks[boolVar] = true;
656
+ this.lemma.push(antecedent);
657
+ }
658
+ return;
659
+ }
660
+ if (this.marks[boolVar]) return;
661
+ this.marks[boolVar] = true;
662
+ if (this.levels[boolVar] === this.scopeLevel && this.atoms.getMaxVar(antecedent) === this.xk)
663
+ this.markCount++;
664
+ else this.lemma.push(antecedent);
665
+ }
666
+
667
+ private resolveLiterals(boolVar: number, literals: readonly number[]) {
668
+ for (const literal of literals) if (literal >> 1 !== boolVar) this.processAntecedent(literal);
669
+ }
670
+
671
+ private resolveClause(boolVar: number, clause: Clause) {
672
+ clause.isActive = true;
673
+ this.resolveLiterals(boolVar, clause.literals);
674
+ this.lemmaAssumptions = mkJoin(clause.assumptions, this.lemmaAssumptions);
675
+ }
676
+
677
+ // resolve_lazy_justification: the explanation of the excluded line, with the negations of the
678
+ // literals that excluded it, as the clause to resolve with.
679
+ private resolveLazyJustification(boolVar: number, literals: number[], clauses: Clause[]) {
680
+ this.lazyClause.reset();
681
+ this.explain.computeConflictExplanation(literals, this.lazyClause);
682
+ for (const literal of literals) this.lazyClause.push(literal ^ 1);
683
+ this.checkpoint();
684
+ this.resolveLiterals(boolVar, this.lazyClause.literals);
685
+ for (const clause of clauses)
686
+ this.lemmaAssumptions = mkJoin(clause.assumptions, this.lemmaAssumptions);
687
+ }
688
+
689
+ private resetMarks() {
690
+ for (const literal of this.lemma.literals) this.marks[literal >> 1] = false;
691
+ }
692
+
693
+ // scoped_reset_marks
694
+ private releaseMarks() {
695
+ if (this.markCount > 0) {
696
+ this.markCount = 0;
697
+ this.marks.fill(false);
698
+ } else this.resetMarks();
699
+ }
700
+
701
+ // resolve: learns a lemma from the conflict and backjumps. False when the lemma is empty.
702
+ private resolve(conflict: Clause) {
703
+ let conflictClause = conflict;
704
+ while (true) {
705
+ this.stats.conflicts++;
706
+ this.markCount = 0;
707
+ this.lemma.reset();
708
+ this.lemmaAssumptions = null;
709
+ try {
710
+ const lemma = this.learn(conflictClause);
711
+ if (lemma === null) return false;
712
+ if (lemma === true || this.processClause(lemma)) return true;
713
+ conflictClause = lemma;
714
+ } finally {
715
+ this.releaseMarks();
716
+ }
717
+ }
718
+ }
719
+
720
+ // The body of resolve for one conflict: null for the empty lemma, true when the conflict clause
721
+ // itself is the lemma and now propagates, else the learned clause.
722
+ private learn(conflict: Clause): Clause | true | null {
723
+ this.resolveClause(-1, conflict);
724
+ let top = this.trail.length;
725
+ let isDecision = false;
726
+ while (true) {
727
+ while (this.markCount > 0) {
728
+ this.checkpoint();
729
+ const entry = this.trail[top - 1];
730
+ if (entry.kind === "assignment" && this.marks[entry.boolVar]) {
731
+ const boolVar = entry.boolVar;
732
+ this.markCount--;
733
+ this.marks[boolVar] = false;
734
+ const justification = this.justifications[boolVar]!;
735
+ if (justification.kind === "clause") this.resolveClause(boolVar, justification.clause);
736
+ else if (justification.kind === "lazy")
737
+ this.resolveLazyJustification(boolVar, justification.literals, justification.clauses);
738
+ else {
739
+ isDecision = true;
740
+ this.lemma.push(2 * boolVar + (this.bvalues[boolVar] === L_TRUE ? 1 : 0));
741
+ }
742
+ }
743
+ top--;
744
+ }
745
+ if (isDecision) break;
746
+ const literals = this.lemma.literals;
747
+ if (literals.every((literal) => this.atoms.getMaxVar(literal) !== this.xk)) break;
748
+ let maxLevel = 0;
749
+ for (const literal of literals)
750
+ if (this.getAssignedValue(literal) === L_FALSE)
751
+ maxLevel = Math.max(maxLevel, this.levels[literal >> 1]);
752
+ // remove_literals_from_lvl
753
+ let kept = 0;
754
+ for (const literal of literals) {
755
+ const boolVar = literal >> 1;
756
+ if (
757
+ this.getAssignedValue(literal) === L_FALSE &&
758
+ this.levels[boolVar] === maxLevel &&
759
+ this.atoms.getMaxVar(literal) === this.xk
760
+ ) {
761
+ this.markCount++;
762
+ continue;
763
+ }
764
+ this.lemma.set(kept++, literal);
765
+ }
766
+ this.lemma.shrink(kept);
767
+ this.undoUntilLevel(maxLevel);
768
+ top = this.trail.length;
769
+ }
770
+ if (this.lemma.size === 0) return null;
771
+ this.resetMarks();
772
+ const literals = this.lemma.literals;
773
+ if (!isDecision) {
774
+ let maxVar = NULL_VAR;
775
+ for (const literal of literals) {
776
+ const variable = this.atoms.getMaxVar(literal);
777
+ if (variable !== NULL_VAR && (maxVar === NULL_VAR || variable > maxVar)) maxVar = variable;
778
+ }
779
+ this.undoUntilStage(maxVar);
780
+ return this.mkClause(literals, true, this.lemmaAssumptions);
781
+ }
782
+ if (literals.every((literal) => this.atoms.getAtom(literal) === null)) {
783
+ const boolVar = literals[literals.length - 1] >> 1;
784
+ this.undoUntil(() => this.bvalues[boolVar] !== L_UNDEF);
785
+ } else this.undoUntilLevel(this.findNewLevel(literals));
786
+ if (
787
+ literals.length === conflict.literals.length &&
788
+ literals.every((literal, index) => literal === conflict.literals[index])
789
+ ) {
790
+ this.processClause(conflict);
791
+ return true;
792
+ }
793
+ return this.mkClause(literals, true, this.lemmaAssumptions);
794
+ }
795
+
796
+ // find_new_level_arith_lemma: the highest level of a literal of the current stage other than the
797
+ // last, else the level below the current one.
798
+ private findNewLevel(literals: readonly number[]) {
799
+ let level = -1;
800
+ for (const literal of literals.slice(0, -1))
801
+ if (this.atoms.getMaxVar(literal) === this.xk)
802
+ level = Math.max(level, this.levels[literal >> 1]);
803
+ return level === -1 ? this.scopeLevel - 1 : level;
804
+ }
805
+
806
+ // Variable order.
807
+
808
+ private canReorder() {
809
+ return [...this.learned, ...this.clauses].every((clause) =>
810
+ clause.literals.every(
811
+ (literal) => this.atoms.getAtom(literal)?.kind.startsWith("ROOT") !== true,
812
+ ),
813
+ );
814
+ }
815
+
816
+ // apply_reorder
817
+ private applyReorder() {
818
+ this.isReordered = false;
819
+ if (!this.canReorder()) return;
820
+ this.reorderHeuristically();
821
+ this.isReordered = true;
822
+ }
823
+
824
+ // heuristic_reorder: higher maximal degree first, then more occurrences, then a random order.
825
+ private reorderHeuristically() {
826
+ const count = this.isInt.length;
827
+ const maxDegrees = Array.from({ length: count }, () => 0);
828
+ const occurrences = Array.from({ length: count }, () => 0);
829
+ const collect = (polynomial: Polynomial) => {
830
+ const variables = new Set(polynomial.ms.flatMap((monomial) => [...monomial.vars]));
831
+ for (const variable of variables) {
832
+ occurrences[variable]++;
833
+ maxDegrees[variable] = Math.max(maxDegrees[variable], this.pm.degree(polynomial, variable));
834
+ }
835
+ };
836
+ for (const clause of [...this.clauses, ...this.learned])
837
+ for (const literal of clause.literals) {
838
+ const atom = this.atoms.getAtom(literal);
839
+ if (atom === null) continue;
840
+ if (isIneqAtom(atom)) atom.polynomials.forEach(collect);
841
+ else collect(atom.polynomial);
842
+ }
843
+ // init_shuffle
844
+ const shuffle = Array.from({ length: count }, (_value, index) => index);
845
+ const random = new RandomGen(++this.randomSeed);
846
+ for (let index = count; index-- > 0;) {
847
+ const other = random.next() % (index + 1);
848
+ [shuffle[index], shuffle[other]] = [shuffle[other], shuffle[index]];
849
+ }
850
+ const order = Array.from({ length: count }, (_value, index) => index).sort(
851
+ (first, second) =>
852
+ maxDegrees[second] - maxDegrees[first] ||
853
+ occurrences[second] - occurrences[first] ||
854
+ shuffle[first] - shuffle[second],
855
+ );
856
+ const permutation: number[] = [];
857
+ for (const [position, variable] of order.entries()) permutation[variable] = position;
858
+ this.reorder(permutation);
859
+ }
860
+
861
+ // reorder: renames each variable x to permutation[x], in the polynomials, the assignment and
862
+ // the watches.
863
+ private reorder(permutation: readonly number[]) {
864
+ let kept = 0;
865
+ for (const clause of this.learned) {
866
+ if (clause.literals.some((literal) => this.atoms.getAtom(literal)?.kind.startsWith("ROOT")))
867
+ this.delClause(clause);
868
+ else this.learned[kept++] = clause;
869
+ }
870
+ this.learned.length = kept;
871
+ this.atoms.reinitCache();
872
+ this.resetWatches();
873
+ const assignment: (Anum | undefined)[] = [];
874
+ for (const [variable, value] of this.assignment.entries())
875
+ if (value !== undefined) assignment[permutation[variable]] = value;
876
+ this.undoUntilStage(NULL_VAR);
877
+ this.cache.reset();
878
+ const invPerm = this.invPerm.map((variable) => permutation[variable]);
879
+ for (const [external, internal] of invPerm.entries()) this.perm[internal] = external;
880
+ const isInt = [...this.isInt];
881
+ for (const [variable, flag] of isInt.entries()) this.isInt[permutation[variable]] = flag;
882
+ this.invPerm = invPerm;
883
+ const polynomials = new Set<Polynomial>();
884
+ for (const atom of this.atoms.atoms) {
885
+ if (atom === null || atom === undefined) continue;
886
+ if (isIneqAtom(atom)) for (const polynomial of atom.polynomials) polynomials.add(polynomial);
887
+ else polynomials.add(atom.polynomial);
888
+ }
889
+ this.pm.rename(permutation, polynomials);
890
+ this.atoms.reinitCache();
891
+ this.setAssignment(assignment);
892
+ this.reattachArithClauses(this.clauses);
893
+ this.reattachArithClauses(this.learned);
894
+ }
895
+
896
+ // restore_order
897
+ restoreOrder() {
898
+ this.reorder([...this.perm]);
899
+ }
900
+
901
+ private resetWatches() {
902
+ for (const watches of this.watches) watches.length = 0;
903
+ }
904
+
905
+ private reattachArithClauses(clauses: readonly Clause[]) {
906
+ for (const clause of clauses) {
907
+ const variable = this.getMaxVar(clause);
908
+ if (variable !== NULL_VAR) this.watches[variable].push(clause);
909
+ }
910
+ }
911
+ }