tla-ts 0.0.3 → 0.0.4-dev.2a873ee

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 (370) hide show
  1. package/README.md +46 -115
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/deciders.cjs +366 -0
  5. package/dist/deciders.js +366 -0
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +194 -8
  8. package/dist/index.d.ts +194 -8
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -4
  11. package/dist/parallel-worker.js +1 -4
  12. package/dist/prove-worker.cjs +9 -0
  13. package/dist/prove-worker.d.cts +9 -0
  14. package/dist/prove-worker.d.ts +9 -0
  15. package/dist/prove-worker.js +9 -0
  16. package/dist/prove.cjs +996 -0
  17. package/dist/prove.js +996 -0
  18. package/dist/run-cli.cjs +37 -20
  19. package/dist/run-cli.js +37 -20
  20. package/dist/tlapm.cjs +10 -0
  21. package/dist/tlapm.js +10 -0
  22. package/dist/transfer.cjs +1387 -18
  23. package/dist/transfer.js +1387 -18
  24. package/dist/worker.cjs +21 -0
  25. package/dist/worker.js +21 -0
  26. package/package.json +24 -11
  27. package/src/ast.ts +149 -8
  28. package/src/bags.ts +4 -7
  29. package/src/builtins.ts +29 -11
  30. package/src/bundled-modules.ts +3 -3
  31. package/src/canonical.ts +4 -3
  32. package/src/check.ts +1540 -235
  33. package/src/cli-options.ts +12 -6
  34. package/src/cli.ts +8 -1
  35. package/src/codegen.ts +98 -39
  36. package/src/config.ts +254 -181
  37. package/src/dependencies.ts +2 -2
  38. package/src/environment.ts +540 -140
  39. package/src/errors.ts +284 -4
  40. package/src/evaluate.ts +1043 -293
  41. package/src/exit-codes.ts +22 -43
  42. package/src/fingerprints.ts +46 -11
  43. package/src/index.ts +11 -0
  44. package/src/instances.ts +19 -16
  45. package/src/java-overrides.ts +104 -25
  46. package/src/levels.ts +191 -45
  47. package/src/lexer.ts +127 -30
  48. package/src/live-check.ts +867 -0
  49. package/src/liveness.ts +218 -572
  50. package/src/{obligation-action.ts → obligations/action.ts} +247 -69
  51. package/src/{obligation-anon.ts → obligations/anon.ts} +49 -47
  52. package/src/obligations/ctx.ts +64 -0
  53. package/src/{obligation-deref.ts → obligations/deref.ts} +51 -92
  54. package/src/{obligation-expression.ts → obligations/expression.ts} +117 -57
  55. package/src/{obligation-format.ts → obligations/format.ts} +7 -8
  56. package/src/{obligation-generate.ts → obligations/generate.ts} +170 -192
  57. package/src/{obligations.ts → obligations/index.ts} +32 -16
  58. package/src/{obligation-levels.ts → obligations/levels.ts} +26 -28
  59. package/src/{obligation-module.ts → obligations/module.ts} +113 -121
  60. package/src/obligations/pickle.ts +98 -0
  61. package/src/obligations/pragma.ts +189 -0
  62. package/src/{obligation-printer.ts → obligations/printer.ts} +22 -80
  63. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -2
  64. package/src/{obligation-source.ts → obligations/source.ts} +156 -99
  65. package/src/obligations/temporal.ts +321 -0
  66. package/src/{obligation-tuples.ts → obligations/tuples.ts} +38 -54
  67. package/src/ocaml-marshal.ts +166 -0
  68. package/src/parallel-worker.ts +169 -224
  69. package/src/parallel.ts +140 -81
  70. package/src/parser.ts +456 -147
  71. package/src/pcal-ast.ts +770 -0
  72. package/src/pcal-parse.ts +1523 -0
  73. package/src/pcal-tokenize.ts +516 -0
  74. package/src/pcal-translate.ts +1230 -0
  75. package/src/pcal-validate.ts +454 -0
  76. package/src/prove/decide-pool.ts +95 -0
  77. package/src/prove/deciders.ts +33 -0
  78. package/src/prove/first-order.ts +78 -0
  79. package/src/prove/isabelle/LICENSE +36 -0
  80. package/src/prove/isabelle/LICENSE-tlapm +26 -0
  81. package/src/prove/isabelle/decide.ts +47 -0
  82. package/src/prove/isabelle/encode.ts +446 -0
  83. package/src/prove/isabelle/isar/inner-syntax.ts +579 -0
  84. package/src/prove/isabelle/isar/method.ts +367 -0
  85. package/src/prove/isabelle/isar/proof.ts +28 -0
  86. package/src/prove/isabelle/isar/statement.ts +57 -0
  87. package/src/prove/isabelle/isar/theory.ts +192 -0
  88. package/src/prove/isabelle/isar/type-check.ts +278 -0
  89. package/src/prove/isabelle/provers/blast/blast.ts +258 -0
  90. package/src/prove/isabelle/provers/blast/branch.ts +322 -0
  91. package/src/prove/isabelle/provers/blast/prove.ts +347 -0
  92. package/src/prove/isabelle/provers/blast/rules.ts +330 -0
  93. package/src/prove/isabelle/provers/blast/state.ts +180 -0
  94. package/src/prove/isabelle/provers/blast/term.ts +546 -0
  95. package/src/prove/isabelle/provers/clasimp.ts +150 -0
  96. package/src/prove/isabelle/provers/classical.ts +389 -0
  97. package/src/prove/isabelle/provers/hypsubst.ts +433 -0
  98. package/src/prove/isabelle/pure/bicompose.ts +174 -0
  99. package/src/prove/isabelle/pure/consts.ts +32 -0
  100. package/src/prove/isabelle/pure/conv.ts +79 -0
  101. package/src/prove/isabelle/pure/drule.ts +264 -0
  102. package/src/prove/isabelle/pure/envir.ts +331 -0
  103. package/src/prove/isabelle/pure/goal.ts +53 -0
  104. package/src/prove/isabelle/pure/interrupt.ts +16 -0
  105. package/src/prove/isabelle/pure/list.ts +12 -0
  106. package/src/prove/isabelle/pure/logic.ts +330 -0
  107. package/src/prove/isabelle/pure/name.ts +98 -0
  108. package/src/prove/isabelle/pure/net.ts +215 -0
  109. package/src/prove/isabelle/pure/object-logic.ts +41 -0
  110. package/src/prove/isabelle/pure/pattern.ts +631 -0
  111. package/src/prove/isabelle/pure/raw-simplifier.ts +338 -0
  112. package/src/prove/isabelle/pure/rewriter.ts +602 -0
  113. package/src/prove/isabelle/pure/search.ts +68 -0
  114. package/src/prove/isabelle/pure/seq.ts +133 -0
  115. package/src/prove/isabelle/pure/simplifier.ts +106 -0
  116. package/src/prove/isabelle/pure/table.ts +201 -0
  117. package/src/prove/isabelle/pure/tactic.ts +168 -0
  118. package/src/prove/isabelle/pure/tactical.ts +264 -0
  119. package/src/prove/isabelle/pure/term-ord.ts +105 -0
  120. package/src/prove/isabelle/pure/term.ts +688 -0
  121. package/src/prove/isabelle/pure/thm.ts +783 -0
  122. package/src/prove/isabelle/pure/type.ts +121 -0
  123. package/src/prove/isabelle/pure/unify.ts +753 -0
  124. package/src/prove/isabelle/pure/variable.ts +25 -0
  125. package/src/prove/isabelle/tla/classical-setup.ts +101 -0
  126. package/src/prove/isabelle/tla/context.ts +74 -0
  127. package/src/prove/isabelle/tla/logic-data.ts +5 -0
  128. package/src/prove/isabelle/tla/logic.ts +215 -0
  129. package/src/prove/isabelle/tla/simpdata.ts +241 -0
  130. package/src/prove/isabelle/tools/intuitionistic.ts +132 -0
  131. package/src/prove/ocaml.ts +22 -0
  132. package/src/prove/prep/action.ts +508 -0
  133. package/src/prove/prep/defs.ts +33 -0
  134. package/src/prove/prep/elab.ts +156 -0
  135. package/src/prove/prep/enabled-axioms.ts +189 -0
  136. package/src/prove/prep/enabled.ts +43 -0
  137. package/src/prove/prep/fingerprint.ts +388 -0
  138. package/src/prove/prep/flatten.ts +70 -0
  139. package/src/prove/prep/level-comparison.ts +529 -0
  140. package/src/prove/prep/md5.ts +67 -0
  141. package/src/prove/prep/pragma.ts +221 -0
  142. package/src/prove/prep/trivial.ts +22 -0
  143. package/src/prove/prove-worker.ts +22 -0
  144. package/src/prove/prove.ts +498 -0
  145. package/src/prove/ptl/decide.ts +68 -0
  146. package/src/prove/ptl/encode.ts +255 -0
  147. package/src/prove/ptl/sat.ts +151 -0
  148. package/src/prove/ptl/tableau.ts +276 -0
  149. package/src/prove/smt/axiomatize.ts +69 -0
  150. package/src/prove/smt/axioms.ts +209 -0
  151. package/src/prove/smt/context.ts +108 -0
  152. package/src/prove/smt/data.ts +636 -0
  153. package/src/prove/smt/encode.ts +164 -0
  154. package/src/prove/smt/extensionality.ts +65 -0
  155. package/src/prove/smt/flatten.ts +112 -0
  156. package/src/prove/smt/format.ts +154 -0
  157. package/src/prove/smt/instances.ts +181 -0
  158. package/src/prove/smt/rewrite.ts +772 -0
  159. package/src/prove/smt/simplify.ts +57 -0
  160. package/src/prove/smt/solver/act-cache.ts +265 -0
  161. package/src/prove/smt/solver/arith-rewriter.ts +962 -0
  162. package/src/prove/smt/solver/array.ts +22 -0
  163. package/src/prove/smt/solver/asserted-formulas.ts +469 -0
  164. package/src/prove/smt/solver/ast-lt.ts +157 -0
  165. package/src/prove/smt/solver/ast-util.ts +91 -0
  166. package/src/prove/smt/solver/ast.ts +1315 -0
  167. package/src/prove/smt/solver/auf-solver.ts +572 -0
  168. package/src/prove/smt/solver/case-split-queue.ts +178 -0
  169. package/src/prove/smt/solver/cg-table.ts +175 -0
  170. package/src/prove/smt/solver/clause.ts +276 -0
  171. package/src/prove/smt/solver/conflict-resolution.ts +343 -0
  172. package/src/prove/smt/solver/context.ts +1292 -0
  173. package/src/prove/smt/solver/ctx-simplify.ts +334 -0
  174. package/src/prove/smt/solver/der.ts +224 -0
  175. package/src/prove/smt/solver/dyn-ack.ts +141 -0
  176. package/src/prove/smt/solver/e-matching.ts +659 -0
  177. package/src/prove/smt/solver/enode.ts +259 -0
  178. package/src/prove/smt/solver/expr-ref.ts +21 -0
  179. package/src/prove/smt/solver/expr-safe-replace.ts +172 -0
  180. package/src/prove/smt/solver/fingerprints.ts +92 -0
  181. package/src/prove/smt/solver/flat-literals.ts +51 -0
  182. package/src/prove/smt/solver/goal.ts +138 -0
  183. package/src/prove/smt/solver/hash.ts +173 -0
  184. package/src/prove/smt/solver/hashtable.ts +166 -0
  185. package/src/prove/smt/solver/internalizer.ts +1381 -0
  186. package/src/prove/smt/solver/lbool.ts +5 -0
  187. package/src/prove/smt/solver/literal.ts +24 -0
  188. package/src/prove/smt/solver/lp/bound-propagator.ts +391 -0
  189. package/src/prove/smt/solver/lp/constraints.ts +78 -0
  190. package/src/prove/smt/solver/lp/containers.ts +296 -0
  191. package/src/prove/smt/solver/lp/core-solver.ts +504 -0
  192. package/src/prove/smt/solver/lp/cross-nested.ts +224 -0
  193. package/src/prove/smt/solver/lp/dep-intervals.ts +642 -0
  194. package/src/prove/smt/solver/lp/dependency.ts +51 -0
  195. package/src/prove/smt/solver/lp/dioph-eq.ts +1181 -0
  196. package/src/prove/smt/solver/lp/explanation.ts +46 -0
  197. package/src/prove/smt/solver/lp/gomory.ts +255 -0
  198. package/src/prove/smt/solver/lp/hnf-cutter.ts +125 -0
  199. package/src/prove/smt/solver/lp/hnf.ts +281 -0
  200. package/src/prove/smt/solver/lp/int-cube.ts +295 -0
  201. package/src/prove/smt/solver/lp/int-solver.ts +514 -0
  202. package/src/prove/smt/solver/lp/lar-solver.ts +816 -0
  203. package/src/prove/smt/solver/lp/lar-term.ts +62 -0
  204. package/src/prove/smt/solver/lp/lp-settings.ts +91 -0
  205. package/src/prove/smt/solver/lp/maximize-term.ts +347 -0
  206. package/src/prove/smt/solver/lp/nex-creator.ts +381 -0
  207. package/src/prove/smt/solver/lp/nex.ts +120 -0
  208. package/src/prove/smt/solver/lp/nla-backoff.ts +43 -0
  209. package/src/prove/smt/solver/lp/nla-basics.ts +398 -0
  210. package/src/prove/smt/solver/lp/nla-core.ts +968 -0
  211. package/src/prove/smt/solver/lp/nla-divisions.ts +332 -0
  212. package/src/prove/smt/solver/lp/nla-emonics.ts +373 -0
  213. package/src/prove/smt/solver/lp/nla-factorization.ts +30 -0
  214. package/src/prove/smt/solver/lp/nla-grobner.ts +904 -0
  215. package/src/prove/smt/solver/lp/nla-horner.ts +126 -0
  216. package/src/prove/smt/solver/lp/nla-intervals.ts +265 -0
  217. package/src/prove/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  218. package/src/prove/smt/solver/lp/nla-monotone.ts +59 -0
  219. package/src/prove/smt/solver/lp/nla-order.ts +307 -0
  220. package/src/prove/smt/solver/lp/nla-patcher.ts +112 -0
  221. package/src/prove/smt/solver/lp/nla-tangents.ts +251 -0
  222. package/src/prove/smt/solver/lp/nla-throttle.ts +85 -0
  223. package/src/prove/smt/solver/lp/nla-types.ts +124 -0
  224. package/src/prove/smt/solver/lp/nla-var-eqs.ts +141 -0
  225. package/src/prove/smt/solver/lp/nra-solver.ts +440 -0
  226. package/src/prove/smt/solver/lp/numeric-pair.ts +65 -0
  227. package/src/prove/smt/solver/lp/pdd-interval.ts +31 -0
  228. package/src/prove/smt/solver/lp/pdd-simplifier.ts +184 -0
  229. package/src/prove/smt/solver/lp/pdd-solver.ts +408 -0
  230. package/src/prove/smt/solver/lp/pdd.ts +971 -0
  231. package/src/prove/smt/solver/lp/random-updater.ts +138 -0
  232. package/src/prove/smt/solver/lp/static-matrix.ts +246 -0
  233. package/src/prove/smt/solver/lp/union-find.ts +96 -0
  234. package/src/prove/smt/solver/mam-compiler.ts +847 -0
  235. package/src/prove/smt/solver/mam-interpreter.ts +400 -0
  236. package/src/prove/smt/solver/maximize-ac-sharing.ts +118 -0
  237. package/src/prove/smt/solver/model-checker.ts +347 -0
  238. package/src/prove/smt/solver/model-evaluator.ts +262 -0
  239. package/src/prove/smt/solver/model-finder.ts +155 -0
  240. package/src/prove/smt/solver/model-generator.ts +97 -0
  241. package/src/prove/smt/solver/model-macro-solver.ts +728 -0
  242. package/src/prove/smt/solver/nlsat/algebraic.ts +1161 -0
  243. package/src/prove/smt/solver/nlsat/atoms.ts +238 -0
  244. package/src/prove/smt/solver/nlsat/evaluator.ts +303 -0
  245. package/src/prove/smt/solver/nlsat/explain.ts +607 -0
  246. package/src/prove/smt/solver/nlsat/interval-set.ts +351 -0
  247. package/src/prove/smt/solver/nlsat/levelwise.ts +737 -0
  248. package/src/prove/smt/solver/nlsat/mpbq.ts +161 -0
  249. package/src/prove/smt/solver/nlsat/polynomial.ts +1722 -0
  250. package/src/prove/smt/solver/nlsat/solver.ts +911 -0
  251. package/src/prove/smt/solver/nlsat/types.ts +43 -0
  252. package/src/prove/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  253. package/src/prove/smt/solver/nlsat/upolynomial.ts +996 -0
  254. package/src/prove/smt/solver/nnf.ts +469 -0
  255. package/src/prove/smt/solver/pattern-inference.ts +351 -0
  256. package/src/prove/smt/solver/poly-rewriter.ts +477 -0
  257. package/src/prove/smt/solver/propagate-values.ts +83 -0
  258. package/src/prove/smt/solver/proto-model.ts +551 -0
  259. package/src/prove/smt/solver/pull-quant.ts +139 -0
  260. package/src/prove/smt/solver/qe-lite-der.ts +526 -0
  261. package/src/prove/smt/solver/qe-lite-fm.ts +576 -0
  262. package/src/prove/smt/solver/qe-lite.ts +381 -0
  263. package/src/prove/smt/solver/qi-queue.ts +362 -0
  264. package/src/prove/smt/solver/quant-tactics.ts +117 -0
  265. package/src/prove/smt/solver/quantifier-analyzer.ts +562 -0
  266. package/src/prove/smt/solver/quantifier-manager.ts +186 -0
  267. package/src/prove/smt/solver/random-gen.ts +10 -0
  268. package/src/prove/smt/solver/rational.ts +165 -0
  269. package/src/prove/smt/solver/ref-vector.ts +62 -0
  270. package/src/prove/smt/solver/relevancy.ts +247 -0
  271. package/src/prove/smt/solver/rewriter-tpl.ts +1159 -0
  272. package/src/prove/smt/solver/rewriter.ts +843 -0
  273. package/src/prove/smt/solver/rlimit.ts +79 -0
  274. package/src/prove/smt/solver/smtlib-parser.ts +526 -0
  275. package/src/prove/smt/solver/solver.ts +71 -0
  276. package/src/prove/smt/solver/sort.ts +35 -0
  277. package/src/prove/smt/solver/sticky-generations.ts +69 -0
  278. package/src/prove/smt/solver/theory-lra-axioms.ts +340 -0
  279. package/src/prove/smt/solver/theory-lra-bounds.ts +226 -0
  280. package/src/prove/smt/solver/theory-lra-final-check.ts +252 -0
  281. package/src/prove/smt/solver/theory-lra-internalize.ts +476 -0
  282. package/src/prove/smt/solver/theory-lra-model.ts +243 -0
  283. package/src/prove/smt/solver/theory-lra-propagate.ts +405 -0
  284. package/src/prove/smt/solver/theory-lra-state.ts +43 -0
  285. package/src/prove/smt/solver/theory-lra.ts +56 -0
  286. package/src/prove/smt/solver/var-subst.ts +258 -0
  287. package/src/prove/smt/solver/z3-license.txt +10 -0
  288. package/src/prove/smt/table.ts +170 -0
  289. package/src/prove/tlapm/tlapm.ts +96 -0
  290. package/src/prove/tlaps-module.ts +510 -0
  291. package/src/prove/verdict.ts +18 -0
  292. package/src/prove/zenon/LICENSE +32 -0
  293. package/src/prove/zenon/check/check.ts +105 -0
  294. package/src/prove/zenon/check/definitions.ts +144 -0
  295. package/src/prove/zenon/check/equality.ts +182 -0
  296. package/src/prove/zenon/check/functions.ts +62 -0
  297. package/src/prove/zenon/check/keys.ts +125 -0
  298. package/src/prove/zenon/check/propositional.ts +104 -0
  299. package/src/prove/zenon/check/records.ts +188 -0
  300. package/src/prove/zenon/check/relations.ts +121 -0
  301. package/src/prove/zenon/check/rewrites.ts +224 -0
  302. package/src/prove/zenon/check/sets.ts +302 -0
  303. package/src/prove/zenon/check/terms.ts +127 -0
  304. package/src/prove/zenon/check/tla.ts +126 -0
  305. package/src/prove/zenon/decide.ts +113 -0
  306. package/src/prove/zenon/encode.ts +379 -0
  307. package/src/prove/zenon/eqrel.ts +300 -0
  308. package/src/prove/zenon/equality-rules.ts +435 -0
  309. package/src/prove/zenon/expr.ts +551 -0
  310. package/src/prove/zenon/index-table.ts +350 -0
  311. package/src/prove/zenon/isar-case.ts +513 -0
  312. package/src/prove/zenon/isar.ts +1249 -0
  313. package/src/prove/zenon/limits.ts +15 -0
  314. package/src/prove/zenon/llproof.ts +173 -0
  315. package/src/prove/zenon/mltoll.ts +1566 -0
  316. package/src/prove/zenon/node.ts +297 -0
  317. package/src/prove/zenon/ocaml.ts +169 -0
  318. package/src/prove/zenon/parse.ts +247 -0
  319. package/src/prove/zenon/phrase.ts +191 -0
  320. package/src/prove/zenon/proof.ts +198 -0
  321. package/src/prove/zenon/propositional-rules.ts +387 -0
  322. package/src/prove/zenon/rules.ts +94 -0
  323. package/src/prove/zenon/search.ts +288 -0
  324. package/src/prove/zenon/tla/functions.ts +151 -0
  325. package/src/prove/zenon/tla/llproof.ts +480 -0
  326. package/src/prove/zenon/tla/records.ts +225 -0
  327. package/src/prove/zenon/tla/rewrites.ts +447 -0
  328. package/src/prove/zenon/tla/sets.ts +304 -0
  329. package/src/prove/zenon/tla/terms.ts +162 -0
  330. package/src/prove/zenon/tla/tla.ts +506 -0
  331. package/src/randomization.ts +24 -7
  332. package/src/resolve.ts +1481 -426
  333. package/src/run-cli.ts +1483 -212
  334. package/src/runtime.ts +19 -1
  335. package/src/sany-builtins.ts +147 -0
  336. package/src/sany-generator.ts +3128 -0
  337. package/src/sany-levels.ts +1208 -0
  338. package/src/sany-lexer.ts +545 -0
  339. package/src/sany-linter.ts +122 -0
  340. package/src/sany-modules.ts +1398 -0
  341. package/src/sany-nodes.ts +463 -0
  342. package/src/sany-parse-error.ts +2161 -0
  343. package/src/sany-report.ts +356 -0
  344. package/src/sany-selectors.ts +738 -0
  345. package/src/sany-source.ts +248 -0
  346. package/src/sany-xml.ts +1017 -0
  347. package/src/spec-description.ts +42 -11
  348. package/src/standard-modules.ts +203 -148
  349. package/src/standard-ranges.ts +116 -0
  350. package/src/state-graph.ts +180 -0
  351. package/src/subexpressions.ts +231 -171
  352. package/src/substitution-levels.ts +38 -17
  353. package/src/successors.ts +241 -110
  354. package/src/symmetry.ts +194 -54
  355. package/src/tableau.ts +54 -25
  356. package/src/tlapm-cache.ts +236 -0
  357. package/src/tlc-ext.ts +42 -29
  358. package/src/tlc-messages.ts +329 -0
  359. package/src/tlc-module.ts +52 -43
  360. package/src/tlc-modules.ts +4 -0
  361. package/src/tlc-order.ts +78 -10
  362. package/src/tlc-random.ts +84 -33
  363. package/src/tlc-replay.ts +655 -0
  364. package/src/tlc-summary.ts +20 -5
  365. package/src/tlc-version.ts +19 -0
  366. package/src/transfer.ts +15 -3
  367. package/src/values.ts +787 -190
  368. package/src/worker.ts +65 -0
  369. package/dist/parallel.cjs +0 -12
  370. package/dist/parallel.js +0 -12
@@ -0,0 +1,1315 @@
1
+ // Ported from Z3 (src/ast/ast.h, src/ast/ast.cpp), MIT license, see z3-license.txt.
2
+ // A hash-consed DAG of applications, de Bruijn variables and quantifiers, as in Z3's ast_manager.
3
+ import { SmtInvariantError } from "../../../errors";
4
+ import { FlatLiterals } from "./flat-literals";
5
+ import { astArrayHash, bytesHash, combineHash, getCompositeHash, mkMix, stringHash } from "./hash";
6
+ import { ObjMap } from "./hashtable";
7
+ import { Rational } from "./rational";
8
+ import { grow, shrink } from "./array";
9
+ import type { ResourceLimit } from "./rlimit";
10
+
11
+ export const KIND_APP = 0;
12
+ export const KIND_VAR = 1;
13
+ export const KIND_QUANTIFIER = 2;
14
+
15
+ export const SORT_BOOL = 0;
16
+ export const SORT_INT = 1;
17
+ export const SORT_REAL = 2;
18
+
19
+ export const FAMILY_BASIC = 0;
20
+ export const FAMILY_ARITH = 1;
21
+ export const FAMILY_USER = 2;
22
+ // Model values: the elements that a model gives to an uninterpreted sort.
23
+ export const FAMILY_MODEL_VALUE = 3;
24
+
25
+ export const OP_TRUE = 0;
26
+ export const OP_FALSE = 1;
27
+ export const OP_EQ = 2;
28
+ export const OP_DISTINCT = 3;
29
+ export const OP_ITE = 4;
30
+ export const OP_AND = 5;
31
+ export const OP_OR = 6;
32
+ export const OP_XOR = 7;
33
+ export const OP_NOT = 8;
34
+ export const OP_IMPLIES = 9;
35
+ export const OP_NUM = 10;
36
+ export const OP_LE = 11;
37
+ export const OP_GE = 12;
38
+ export const OP_LT = 13;
39
+ export const OP_GT = 14;
40
+ export const OP_ADD = 15;
41
+ export const OP_SUB = 16;
42
+ export const OP_UMINUS = 17;
43
+ export const OP_MUL = 18;
44
+ export const OP_IDIV = 19;
45
+ export const OP_MOD = 20;
46
+ export const OP_ABS = 21;
47
+ export const OP_PATTERN = 22;
48
+ export const OP_DIV = 23;
49
+ export const OP_TO_REAL = 24;
50
+ export const OP_TO_INT = 25;
51
+ export const OP_IS_INT = 26;
52
+ // Z3's div0, idiv0 and mod0: division by zero, which theory_lra's found_underspecified equates with
53
+ // the division it stands for.
54
+ export const OP_DIV0 = 27;
55
+ export const OP_IDIV0 = 28;
56
+ export const OP_MOD0 = 29;
57
+ export const OP_UNINTERPRETED = 30;
58
+ const OP_MODEL_VALUE = 31;
59
+
60
+ // A Z3 symbol: a string, or a number for a numerical symbol, which Z3 prints as k!n.
61
+ export type SmtSymbol = string | number;
62
+
63
+ const getSymbolName = (symbol: SmtSymbol) => (typeof symbol === "number" ? `k!${symbol}` : symbol);
64
+
65
+ export interface FuncDecl {
66
+ name: SmtSymbol;
67
+ family: number;
68
+ op: number;
69
+ domain: number[];
70
+ range: number;
71
+ isSkolem: boolean;
72
+ // Z3's small id of the declaration, which its matcher hashes.
73
+ smallId: number;
74
+ }
75
+
76
+ interface QuantifierData {
77
+ isForall: boolean;
78
+ sorts: number[];
79
+ // The names of the variables, which tell apart quantifiers that differ only in them, as in Z3.
80
+ names: SmtSymbol[];
81
+ body: number;
82
+ // Applications of the pattern declaration to the terms of each multi-pattern.
83
+ patterns: number[];
84
+ weight: number;
85
+ qid: string;
86
+ }
87
+
88
+ const BUILTIN_DECLS: [string, number, number, number][] = [
89
+ ["true", FAMILY_BASIC, OP_TRUE, SORT_BOOL],
90
+ ["false", FAMILY_BASIC, OP_FALSE, SORT_BOOL],
91
+ ["=", FAMILY_BASIC, OP_EQ, SORT_BOOL],
92
+ ["distinct", FAMILY_BASIC, OP_DISTINCT, SORT_BOOL],
93
+ ["ite", FAMILY_BASIC, OP_ITE, -1],
94
+ ["and", FAMILY_BASIC, OP_AND, SORT_BOOL],
95
+ ["or", FAMILY_BASIC, OP_OR, SORT_BOOL],
96
+ ["xor", FAMILY_BASIC, OP_XOR, SORT_BOOL],
97
+ ["not", FAMILY_BASIC, OP_NOT, SORT_BOOL],
98
+ ["=>", FAMILY_BASIC, OP_IMPLIES, SORT_BOOL],
99
+ ["num", FAMILY_ARITH, OP_NUM, SORT_INT],
100
+ ["<=", FAMILY_ARITH, OP_LE, SORT_BOOL],
101
+ [">=", FAMILY_ARITH, OP_GE, SORT_BOOL],
102
+ ["<", FAMILY_ARITH, OP_LT, SORT_BOOL],
103
+ [">", FAMILY_ARITH, OP_GT, SORT_BOOL],
104
+ ["+", FAMILY_ARITH, OP_ADD, SORT_INT],
105
+ ["-", FAMILY_ARITH, OP_SUB, SORT_INT],
106
+ ["-", FAMILY_ARITH, OP_UMINUS, SORT_INT],
107
+ ["*", FAMILY_ARITH, OP_MUL, SORT_INT],
108
+ ["div", FAMILY_ARITH, OP_IDIV, SORT_INT],
109
+ ["mod", FAMILY_ARITH, OP_MOD, SORT_INT],
110
+ ["abs", FAMILY_ARITH, OP_ABS, SORT_INT],
111
+ ["pattern", FAMILY_BASIC, OP_PATTERN, SORT_BOOL],
112
+ ["/", FAMILY_ARITH, OP_DIV, SORT_REAL],
113
+ ["to_real", FAMILY_ARITH, OP_TO_REAL, SORT_REAL],
114
+ ["to_int", FAMILY_ARITH, OP_TO_INT, SORT_INT],
115
+ ["is_int", FAMILY_ARITH, OP_IS_INT, SORT_BOOL],
116
+ ["/0", FAMILY_ARITH, OP_DIV0, SORT_REAL],
117
+ ["div0", FAMILY_ARITH, OP_IDIV0, SORT_INT],
118
+ ["mod0", FAMILY_ARITH, OP_MOD0, SORT_INT],
119
+ ];
120
+
121
+ // Z3's family ids and decl kinds, which its AST hashes include.
122
+ const Z3_BASIC_FAMILY = 0;
123
+ const Z3_PATTERN_FAMILY = 2;
124
+ const Z3_MODEL_VALUE_FAMILY = 3;
125
+ const Z3_USER_SORT_FAMILY = 4;
126
+ const Z3_ARITH_FAMILY = 5;
127
+ const Z3_RECFUN_FAMILY = 10;
128
+ const Z3_NULL = 0xffffffff;
129
+ // The name, Z3 decl kind and arity of each builtin, whose Z3 declaration has this many arguments
130
+ // whatever the number of arguments of the application (-1 for the arguments' own number).
131
+ const Z3_BUILTINS = new Map<number, [string, number, number]>([
132
+ [OP_TRUE, ["true", 0, 0]],
133
+ [OP_FALSE, ["false", 1, 0]],
134
+ [OP_EQ, ["=", 2, 2]],
135
+ [OP_DISTINCT, ["distinct", 3, -1]],
136
+ [OP_ITE, ["if", 4, 3]],
137
+ [OP_AND, ["and", 5, 2]],
138
+ [OP_OR, ["or", 6, 2]],
139
+ [OP_XOR, ["xor", 7, 2]],
140
+ [OP_NOT, ["not", 8, 1]],
141
+ [OP_IMPLIES, ["=>", 9, 2]],
142
+ [OP_LE, ["<=", 2, 2]],
143
+ [OP_GE, [">=", 3, 2]],
144
+ [OP_LT, ["<", 4, 2]],
145
+ [OP_GT, [">", 5, 2]],
146
+ [OP_ADD, ["+", 6, 2]],
147
+ [OP_SUB, ["-", 7, 2]],
148
+ [OP_UMINUS, ["-", 8, 1]],
149
+ [OP_MUL, ["*", 9, 2]],
150
+ [OP_IDIV, ["div", 11, 2]],
151
+ [OP_MOD, ["mod", 16, 2]],
152
+ [OP_ABS, ["abs", 21, 1]],
153
+ [OP_PATTERN, ["pattern", 0, -1]],
154
+ [OP_DIV, ["/", 10, 2]],
155
+ [OP_TO_REAL, ["to_real", 18, 1]],
156
+ [OP_TO_INT, ["to_int", 19, 1]],
157
+ [OP_IS_INT, ["is_int", 20, 1]],
158
+ [OP_DIV0, ["/0", 12, 2]],
159
+ [OP_IDIV0, ["div0", 13, 2]],
160
+ [OP_MOD0, ["mod0", 17, 2]],
161
+ ]);
162
+
163
+ // The small ids of the Int declarations Z3 makes when it starts, from arith_decl_plugin::set_manager,
164
+ // which Real terms share. The declarations of Real terms only have the ids of Real's /, Int's
165
+ // to_real, Real's to_int and is_int. Z3 makes =, ite, distinct, pattern, numeral, /0, div0 and mod0
166
+ // declarations per signature on first use, so they get -1 here, and their small ids are kept by
167
+ // signature.
168
+ const Z3_SMALL_IDS = new Map([
169
+ [OP_TRUE, 1],
170
+ [OP_FALSE, 2],
171
+ [OP_AND, 3],
172
+ [OP_OR, 4],
173
+ [OP_XOR, 5],
174
+ [OP_NOT, 6],
175
+ [OP_IMPLIES, 7],
176
+ [OP_LE, 17],
177
+ [OP_GE, 18],
178
+ [OP_LT, 19],
179
+ [OP_GT, 20],
180
+ [OP_ADD, 36],
181
+ [OP_SUB, 37],
182
+ [OP_MUL, 38],
183
+ [OP_IDIV, 39],
184
+ [OP_MOD, 41],
185
+ [OP_UMINUS, 42],
186
+ [OP_ABS, 50],
187
+ [OP_DIV, 24],
188
+ [OP_TO_REAL, 43],
189
+ [OP_TO_INT, 45],
190
+ [OP_IS_INT, 47],
191
+ ]);
192
+
193
+ // The small id of the first sort or declaration a problem declares, after Z3's own.
194
+ const FIRST_DECLARED_SMALL_ID = 143;
195
+
196
+ // The ids of Z3's own expressions when it starts: the undef proof, true and false, then pi, euler, a
197
+ // bit-vector numeral, fifteen real variables and a sum of two of them, which no problem shares.
198
+ const FIRST_FREE_ID = 22;
199
+ // MAX_SMALL_NUM_TO_CACHE: arith_decl_plugin holds the numerals below it once it makes them.
200
+ const MAX_SMALL_NUM_TO_CACHE = 16;
201
+ // The sorts that finite_set_decl_plugin::init makes.
202
+ const NUM_FINITE_SET_PLUGIN_SORTS = 7;
203
+
204
+ // symbol::hash: a numerical symbol hashes to its number.
205
+ const getSymbolHash = (symbol: SmtSymbol) =>
206
+ typeof symbol === "number" ? symbol : stringHash(symbol, 17);
207
+
208
+ // Whether a sort is Int or Real.
209
+ export const isArithSort = (sort: number) => sort === SORT_INT || sort === SORT_REAL;
210
+
211
+ // mpz_manager::hash: the absolute value of an integer below 2^32, else the hash of its 32-bit digits,
212
+ // least significant first.
213
+ const getIntegerHash = (value: bigint) => {
214
+ const magnitude = value < 0n ? -value : value;
215
+ if (magnitude <= 0xffffffffn) return Number(magnitude);
216
+ const digits: number[] = [];
217
+ for (let rest = magnitude; rest > 0n; rest >>= 32n) digits.push(Number(rest & 0xffffffffn));
218
+ return bytesHash(new Uint8Array(Uint32Array.from(digits).buffer), 17);
219
+ };
220
+
221
+ // decl_info::hash.
222
+ const getInfoHash = (family: number, kind: number, parameterHashes: number[]) =>
223
+ mkMix(family, kind, parameterHashes.length === 0 ? 0 : getCompositeHash(parameterHashes));
224
+
225
+ // The kinds of an integer signature, in its low three bits.
226
+ const SIGNATURE_EQ = 0;
227
+ const SIGNATURE_ITE = 1;
228
+ const SIGNATURE_DIV0 = 2;
229
+ const SIGNATURE_MODEL_VALUE = 3;
230
+ const SIGNATURE_NUMERAL = 4;
231
+
232
+ // A builtin declaration that Z3 makes once per signature: its small id, and the references that
233
+ // applications and model values hold to it.
234
+ interface SignatureDecl {
235
+ smallId: number;
236
+ refCount: number;
237
+ }
238
+
239
+ export class AstManager {
240
+ // The tables of the expressions are typed arrays indexed by expression, which the collector does
241
+ // not scan. They have room for more expressions than numNodes and double when full, which
242
+ // replaces them, so a caller does not keep one across the creation of an expression.
243
+ private numNodes = 0;
244
+ kinds = new Uint8Array(1024);
245
+ // The declaration of an application.
246
+ decls = new Int32Array(1024);
247
+ // The arguments of every expression end to end: those of expr are argPool[argStarts[expr]] up to
248
+ // argPool[argStarts[expr + 1]]. Variables and constants take an empty range and a quantifier
249
+ // takes its body. Both grow by doubling, which replaces the arrays.
250
+ private argPool = new Int32Array(1024);
251
+ private argStarts = new Int32Array(1024);
252
+ sorts = new Int32Array(1024);
253
+ // The index of a variable or model value, or of a numeral's value in numeralValues.
254
+ values = new Int32Array(1024);
255
+ private numeralValues: Rational[] = [];
256
+ // The integer numerals by value, which finds one without building its key in the table.
257
+ private intNumerals = new Map<bigint, number>();
258
+ // One more than the largest free de Bruijn index, so 0 means the expression is ground.
259
+ freeVarBounds = new Int32Array(1024);
260
+ hasQuantifierFlags = new Uint8Array(1024);
261
+ depths = new Int32Array(1024);
262
+ // Z3's hash of each expression, which orders Z3's hash tables.
263
+ hashes = new Uint32Array(1024);
264
+ quantifiers = new Map<number, QuantifierData>();
265
+ // The marks that the rewriters of this manager share to flatten conjunctions and disjunctions.
266
+ readonly flatLiterals = new FlatLiterals(this);
267
+ funcDecls: FuncDecl[] = [];
268
+ sortNames: string[] = ["Bool", "Int", "Real"];
269
+ private sortHashes = [
270
+ combineHash(getSymbolHash("Bool"), getInfoHash(Z3_BASIC_FAMILY, 0, [])),
271
+ combineHash(getSymbolHash("Int"), getInfoHash(Z3_ARITH_FAMILY, 1, [])),
272
+ combineHash(getSymbolHash("Real"), getInfoHash(Z3_ARITH_FAMILY, 0, [])),
273
+ ];
274
+ // The hash of each uninterpreted declaration, and of each builtin by its Z3 declaration.
275
+ private declHashes: number[] = [];
276
+ // The hash of each builtin declaration other than pattern by op, argument sort, range and number
277
+ // of arguments: open addressing with linear probing, with the four keys of slot i at 4 i in
278
+ // builtinKeys and -1 for an empty slot.
279
+ private builtinKeys = new Int32Array(4 * 256).fill(-1);
280
+ private builtinHashes = new Uint32Array(256);
281
+ private numBuiltinHashes = 0;
282
+ // The hash of each pattern declaration by its domain and range.
283
+ private patternHashes = new Map<string, number>();
284
+ private table = new Map<string, number>();
285
+ // The hash-consing table of applications: open addressing with linear probing over the handles,
286
+ // -1 for an empty slot, which takes a few bytes per application where a map of buckets takes
287
+ // dozens. Applications stay in it when they are deleted, so a lookup can create them again.
288
+ private appHandles = new Int32Array(1024).fill(-1);
289
+ private appHashes = new Int32Array(1024);
290
+ private numApps = 0;
291
+ // id_gen for sorts and declarations: the small id of the next one, and the ids of deleted ones,
292
+ // which Z3 reuses the last freed first. Z3 keeps the declarations of = and ite, and deletes the
293
+ // others with their last reference.
294
+ private nextSmallId = FIRST_DECLARED_SMALL_ID;
295
+ private freeSmallIds: number[] = [];
296
+ private numDecls = FIRST_DECLARED_SMALL_ID;
297
+ // The small id and the number of live applications of each builtin declaration that Z3 makes
298
+ // per signature, by its signature.
299
+ private signatureDecls = new Map<number | string, SignatureDecl>();
300
+ // The references to each user declaration: the script holds the declared ones, and applications
301
+ // and models hold the fresh ones. A deleted declaration keeps its small id here, in case an
302
+ // application of it is created again.
303
+ private declRefCounts: number[] = [];
304
+ // The named expressions of the recfun plugin, by declaration.
305
+ readonly macros = new ObjMap<number>((decl) => this.declHashes[decl]);
306
+ private deletedDecls = new Set<number>();
307
+ // ast_manager::m_fresh_id, which numbers fresh declarations and variable names.
308
+ private freshId = 0;
309
+ // Z3's id of each expression, which orders Z3's sorts. Like Z3, the manager counts references and
310
+ // gives the id of a deleted expression to the next expression it creates, so its ids follow
311
+ // Z3's. A deleted expression stays in the tables with the id -1 until it is created again.
312
+ ids = new Int32Array(1024);
313
+ private refCounts = new Int32Array(1024);
314
+ private freeIds: number[] = [];
315
+ private nextId = 1;
316
+ private numLive = 0;
317
+ // The expressions that the open withTemporaries hold, like the expr_ref temporaries of Z3
318
+ // functions on the C++ stack: the innermost holds those from temporariesMark on, and -1 marks that
319
+ // no temporaries are held.
320
+ private temporaries: number[] = [];
321
+ private temporariesMark = -1;
322
+ // The arguments mkApp copies out of a caller's array that starts past index 0.
323
+ private argBuffer: number[] = [];
324
+ // m_small_ints and m_small_reals: the numerals below MAX_SMALL_NUM_TO_CACHE, which are held.
325
+ private smallInts: number[] = [];
326
+ private smallReals: number[] = [];
327
+ private isFiniteSetPluginInitialized = false;
328
+ readonly trueExpr: number;
329
+ readonly falseExpr: number;
330
+
331
+ constructor(readonly limit: ResourceLimit) {
332
+ for (const builtin of BUILTIN_DECLS)
333
+ this.funcDecls.push({
334
+ name: builtin[0],
335
+ family: builtin[1],
336
+ op: builtin[2],
337
+ domain: [],
338
+ range: builtin[3],
339
+ isSkolem: false,
340
+ smallId: Z3_SMALL_IDS.get(builtin[2]) ?? -1,
341
+ });
342
+ this.trueExpr = this.mkApp(OP_TRUE, [], SORT_BOOL);
343
+ this.falseExpr = this.mkApp(OP_FALSE, [], SORT_BOOL);
344
+ this.incRef(this.trueExpr);
345
+ this.incRef(this.falseExpr);
346
+ this.nextId = FIRST_FREE_ID;
347
+ }
348
+
349
+ getRefCount(expr: number) {
350
+ return this.refCounts[expr];
351
+ }
352
+
353
+ // get_num_asts: the live expressions, declarations and sorts, with Z3's own expressions.
354
+ getNumAsts() {
355
+ return this.numLive + FIRST_FREE_ID - 2 + this.numDecls;
356
+ }
357
+
358
+ // The declaration that a held signature names.
359
+ private getSignatureDecl(key: number | string) {
360
+ const signatureDecl = this.signatureDecls.get(key);
361
+ if (signatureDecl === undefined)
362
+ throw new SmtInvariantError(`the signature ${key} is not held`);
363
+ return signatureDecl;
364
+ }
365
+
366
+ private mkSmallId() {
367
+ this.numDecls++;
368
+ return this.freeSmallIds.pop() ?? this.nextSmallId++;
369
+ }
370
+
371
+ // finite_set_decl_plugin::init, which the first final check of theory_finite_set runs when it
372
+ // makes a set.range declaration: the plugin makes the sorts A and B, three FiniteSet sorts and two
373
+ // Array sorts, which the manager keeps. The set.range declaration is released at once.
374
+ initFiniteSetPlugin() {
375
+ if (this.isFiniteSetPluginInitialized) return;
376
+ this.isFiniteSetPluginInitialized = true;
377
+ for (let index = 0; index < NUM_FINITE_SET_PLUGIN_SORTS; index++) this.mkSmallId();
378
+ this.freeSmallIds.push(this.mkSmallId());
379
+ this.numDecls--;
380
+ }
381
+
382
+ // insert_macro: cmd_context keeps a named expression as a recursive function with one case, whose
383
+ // declaration and case predicate it holds. The recfun plugin maps the declaration to the
384
+ // expression, which a model of the context takes as the declaration's interpretation.
385
+ mkMacro(name: string, expr: number) {
386
+ const decl = this.funcDecls.length;
387
+ this.declHashes[decl] = this.getFuncDeclHash(
388
+ name,
389
+ [],
390
+ this.sorts[expr],
391
+ getInfoHash(Z3_RECFUN_FAMILY, 0, [0]),
392
+ );
393
+ this.funcDecls.push({
394
+ name,
395
+ family: FAMILY_USER,
396
+ op: OP_UNINTERPRETED,
397
+ domain: [],
398
+ range: this.sorts[expr],
399
+ isSkolem: false,
400
+ smallId: this.mkSmallId(),
401
+ });
402
+ this.declRefCounts[decl] = 1;
403
+ this.mkSmallId();
404
+ this.macros.set(decl, expr);
405
+ }
406
+
407
+ // The signature of a builtin declaration that Z3 makes on first use, or null for a declaration
408
+ // that is not one. The low three bits of an integer signature tell its kind: an equality or ite
409
+ // by sort, a division by zero or model value by declaration, or a numeral by its value, which a
410
+ // numeral expression has alone. A distinct or pattern is keyed by its domain.
411
+ private getSignature(expr: number) {
412
+ const decl = this.decls[expr];
413
+ if (decl === OP_NUM) return 8 * this.values[expr] + SIGNATURE_NUMERAL;
414
+ if (decl === OP_EQ) return 8 * this.sorts[this.getArg(expr, 0)] + SIGNATURE_EQ;
415
+ if (decl === OP_ITE) return 8 * this.sorts[expr] + SIGNATURE_ITE;
416
+ if (decl === OP_DIV0 || decl === OP_IDIV0 || decl === OP_MOD0) return 8 * decl + SIGNATURE_DIV0;
417
+ if (decl === OP_DISTINCT || decl === OP_PATTERN)
418
+ return `${decl}:${this.mapArgs(expr, (arg) => this.sorts[arg]).join(",")}`;
419
+ if (this.funcDecls[decl].family === FAMILY_MODEL_VALUE) return 8 * decl + SIGNATURE_MODEL_VALUE;
420
+ return null;
421
+ }
422
+
423
+ // The id that Z3 gives the declaration of an application.
424
+ getDeclId(expr: number) {
425
+ const signature = this.getSignature(expr);
426
+ return signature === null
427
+ ? this.funcDecls[this.decls[expr]].smallId
428
+ : this.getSignatureDecl(signature).smallId;
429
+ }
430
+
431
+ // An application holds its declaration, which Z3 makes with its first application.
432
+ private holdDecl(expr: number) {
433
+ const decl = this.decls[expr];
434
+ if (this.funcDecls[decl].family === FAMILY_USER) {
435
+ this.incDeclRef(decl);
436
+ return;
437
+ }
438
+ const key = this.getSignature(expr);
439
+ if (key === null) return;
440
+ const signatureDecl = this.signatureDecls.get(key);
441
+ if (signatureDecl !== undefined) {
442
+ signatureDecl.refCount++;
443
+ return;
444
+ }
445
+ const smallId = this.mkSmallId();
446
+ // Z3 keeps the equality and ite declarations once it makes them.
447
+ this.signatureDecls.set(key, { smallId, refCount: decl === OP_EQ || decl === OP_ITE ? 2 : 1 });
448
+ if (decl !== OP_NUM && this.funcDecls[decl].family === FAMILY_MODEL_VALUE)
449
+ this.funcDecls[decl].smallId = smallId;
450
+ }
451
+
452
+ // The small id of the declaration a deleted application releases for good, or -1 when the
453
+ // declaration stays.
454
+ private releaseDecl(expr: number) {
455
+ const decl = this.decls[expr];
456
+ if (this.funcDecls[decl].family === FAMILY_USER) {
457
+ this.declRefCounts[decl]--;
458
+ if (this.declRefCounts[decl] > 0) return -1;
459
+ this.deletedDecls.add(decl);
460
+ return this.funcDecls[decl].smallId;
461
+ }
462
+ const key = this.getSignature(expr);
463
+ if (key === null) return -1;
464
+ const signatureDecl = this.getSignatureDecl(key);
465
+ signatureDecl.refCount--;
466
+ if (signatureDecl.refCount > 0) return -1;
467
+ this.signatureDecls.delete(key);
468
+ return signatureDecl.smallId;
469
+ }
470
+
471
+ incRef(expr: number) {
472
+ this.refCounts[expr]++;
473
+ }
474
+
475
+ // A model value's declaration is counted under its signature, like the applications that hold it.
476
+ incDeclRef(decl: number) {
477
+ if (this.funcDecls[decl].family === FAMILY_MODEL_VALUE) {
478
+ const key = 8 * decl + SIGNATURE_MODEL_VALUE;
479
+ const signatureDecl = this.signatureDecls.get(key);
480
+ if (signatureDecl !== undefined) {
481
+ signatureDecl.refCount++;
482
+ return;
483
+ }
484
+ const smallId = this.mkSmallId();
485
+ this.signatureDecls.set(key, { smallId, refCount: 1 });
486
+ this.funcDecls[decl].smallId = smallId;
487
+ return;
488
+ }
489
+ if (this.deletedDecls.delete(decl)) this.funcDecls[decl].smallId = this.mkSmallId();
490
+ this.declRefCounts[decl]++;
491
+ }
492
+
493
+ decDeclRef(decl: number) {
494
+ if (this.funcDecls[decl].family === FAMILY_MODEL_VALUE) {
495
+ const key = 8 * decl + SIGNATURE_MODEL_VALUE;
496
+ const signatureDecl = this.getSignatureDecl(key);
497
+ signatureDecl.refCount--;
498
+ if (signatureDecl.refCount > 0) return;
499
+ this.freeSmallIds.push(signatureDecl.smallId);
500
+ this.signatureDecls.delete(key);
501
+ this.numDecls--;
502
+ return;
503
+ }
504
+ this.declRefCounts[decl]--;
505
+ if (this.declRefCounts[decl] > 0) return;
506
+ this.deletedDecls.add(decl);
507
+ this.freeSmallIds.push(this.funcDecls[decl].smallId);
508
+ this.numDecls--;
509
+ }
510
+
511
+ // Runs body, holding each expression it creates until it returns, then releases them, the last
512
+ // created first. The caller gets a reference to each expression that getKept picks from the
513
+ // result, by default the result itself, and releases it.
514
+ withTemporaries<T>(
515
+ body: () => T,
516
+ getKept: (result: T) => number[] = (result) => [result as number],
517
+ ) {
518
+ const outer = this.beginTemporaries();
519
+ const result = body();
520
+ for (const kept of getKept(result)) this.incRef(kept);
521
+ this.endTemporaries(outer);
522
+ return result;
523
+ }
524
+
525
+ // withTemporaries without closures, for the hot paths: the caller passes what beginTemporaries
526
+ // returns to endTemporaries, and takes its references before it.
527
+ beginTemporaries() {
528
+ const outer = this.temporariesMark;
529
+ this.temporariesMark = this.temporaries.length;
530
+ return outer;
531
+ }
532
+
533
+ endTemporaries(outer: number) {
534
+ const temporaries = this.temporaries;
535
+ const mark = this.temporariesMark;
536
+ this.temporariesMark = outer;
537
+ for (let index = temporaries.length - 1; index >= mark; index--)
538
+ this.decRef(temporaries[index]);
539
+ shrink(temporaries, mark);
540
+ }
541
+
542
+ // Runs body without temporaries, for code whose references are counted explicitly.
543
+ withoutTemporaries<T>(body: () => T) {
544
+ const outer = this.temporariesMark;
545
+ this.temporariesMark = -1;
546
+ const result = body();
547
+ this.temporariesMark = outer;
548
+ return result;
549
+ }
550
+
551
+ // Hands a reference the caller owns to the innermost withTemporaries, or releases it now.
552
+ releaseLater(expr: number) {
553
+ if (this.temporariesMark === -1) this.decRef(expr);
554
+ else this.temporaries.push(expr);
555
+ }
556
+
557
+ // dec_ref and delete_node: an expression without references is deleted, and so are its children
558
+ // and declaration that lose their last reference, in the order of Z3's worklist. A released
559
+ // declaration's small id goes on the worklist as -1 - id.
560
+ decRef(expr: number) {
561
+ if (this.ids[expr] === -1) return;
562
+ this.refCounts[expr]--;
563
+ if (this.refCounts[expr] > 0) return;
564
+ const worklist = [expr];
565
+ for (let node = worklist.pop(); node !== undefined; node = worklist.pop()) {
566
+ if (node < 0) {
567
+ this.freeSmallIds.push(-1 - node);
568
+ this.numDecls--;
569
+ continue;
570
+ }
571
+ this.deleteNode(node);
572
+ if (this.kinds[node] === KIND_APP) {
573
+ const smallId = this.releaseDecl(node);
574
+ if (smallId !== -1) worklist.push(-1 - smallId);
575
+ }
576
+ // The children: the arguments of an application, and the body and then the patterns of a
577
+ // quantifier.
578
+ if (this.kinds[node] !== KIND_QUANTIFIER) {
579
+ const end = this.argStarts[node + 1];
580
+ for (let index = this.argStarts[node]; index < end; index++)
581
+ this.releaseChild(this.argPool[index], worklist);
582
+ continue;
583
+ }
584
+ const data = this.getQuantifier(node);
585
+ this.releaseChild(data.body, worklist);
586
+ for (const pattern of data.patterns) this.releaseChild(pattern, worklist);
587
+ }
588
+ }
589
+
590
+ private releaseChild(child: number, worklist: number[]) {
591
+ this.refCounts[child]--;
592
+ if (this.refCounts[child] === 0) worklist.push(child);
593
+ }
594
+
595
+ private deleteNode(expr: number) {
596
+ this.numLive--;
597
+ this.freeIds.push(this.ids[expr]);
598
+ this.ids[expr] = -1;
599
+ }
600
+
601
+ // register_node_core: a new expression takes an id and a reference to each child.
602
+ private registerNode(expr: number) {
603
+ this.ids[expr] = this.freeIds.pop() ?? this.nextId++;
604
+ this.numLive++;
605
+ this.refCounts[expr] = 0;
606
+ // The children: the arguments of an application, and the body and then the patterns of a
607
+ // quantifier.
608
+ if (this.kinds[expr] !== KIND_QUANTIFIER) {
609
+ const end = this.argStarts[expr + 1];
610
+ for (let index = this.argStarts[expr]; index < end; index++)
611
+ this.incRef(this.revive(this.argPool[index]));
612
+ } else {
613
+ const data = this.getQuantifier(expr);
614
+ this.incRef(this.revive(data.body));
615
+ for (const pattern of data.patterns) this.incRef(this.revive(pattern));
616
+ }
617
+ if (this.kinds[expr] === KIND_APP) this.holdDecl(expr);
618
+ if (this.temporariesMark === -1) return;
619
+ this.incRef(expr);
620
+ this.temporaries.push(expr);
621
+ }
622
+
623
+ // The arguments of an application, and the body of a quantifier as its one argument.
624
+ getNumArgs(expr: number) {
625
+ return this.argStarts[expr + 1] - this.argStarts[expr];
626
+ }
627
+
628
+ getArg(expr: number, index: number) {
629
+ return this.argPool[this.argStarts[expr] + index];
630
+ }
631
+
632
+ // Appends the arguments to target, for a caller that needs them as an array.
633
+ pushArgs(expr: number, target: number[]) {
634
+ const end = this.argStarts[expr + 1];
635
+ for (let index = this.argStarts[expr]; index < end; index++) target.push(this.argPool[index]);
636
+ }
637
+
638
+ // A new array of the arguments.
639
+ getArgs(expr: number) {
640
+ const args: number[] = [];
641
+ this.pushArgs(expr, args);
642
+ return args;
643
+ }
644
+
645
+ // The callbacks may create expressions, which can replace argPool, so each argument is read anew.
646
+ mapArgs<T>(expr: number, map: (arg: number, index: number) => T) {
647
+ const result: T[] = [];
648
+ for (let index = 0; index < this.getNumArgs(expr); index++)
649
+ result.push(map(this.getArg(expr, index), index));
650
+ return result;
651
+ }
652
+
653
+ someArg(expr: number, predicate: (arg: number, index: number) => boolean) {
654
+ for (let index = 0; index < this.getNumArgs(expr); index++)
655
+ if (predicate(this.getArg(expr, index), index)) return true;
656
+ return false;
657
+ }
658
+
659
+ everyArg(expr: number, predicate: (arg: number, index: number) => boolean) {
660
+ for (let index = 0; index < this.getNumArgs(expr); index++)
661
+ if (!predicate(this.getArg(expr, index), index)) return false;
662
+ return true;
663
+ }
664
+
665
+ // A lookup that finds a deleted expression creates it again.
666
+ private revive(expr: number) {
667
+ if (this.ids[expr] === -1) this.registerNode(expr);
668
+ return expr;
669
+ }
670
+
671
+ mkSort(name: string) {
672
+ this.sortHashes.push(
673
+ combineHash(
674
+ getSymbolHash(name),
675
+ getInfoHash(Z3_USER_SORT_FAMILY, this.sortNames.length - 3, []),
676
+ ),
677
+ );
678
+ this.sortNames.push(name);
679
+ this.mkSmallId();
680
+ return this.sortNames.length - 1;
681
+ }
682
+
683
+ // The hash of a func_decl node: its name, range, info and domain.
684
+ private getFuncDeclHash(name: SmtSymbol, domain: number[], range: number, infoHash: number) {
685
+ return astArrayHash(
686
+ domain,
687
+ this.sortHashes,
688
+ combineHash(combineHash(getSymbolHash(name), this.sortHashes[range]), infoHash),
689
+ );
690
+ }
691
+
692
+ // The name, Z3 decl kind and domain of the Z3 declaration of a builtin application.
693
+ getBuiltinSignature(op: number, args: number[]) {
694
+ const builtin = Z3_BUILTINS.get(op);
695
+ if (builtin === undefined)
696
+ throw new SmtInvariantError(`the operator ${op} has no Z3 declaration`);
697
+ const argSort = op === OP_ITE ? this.sorts[args[1]] : this.sorts[args[0]];
698
+ const arity = builtin[2] === -1 ? args.length : builtin[2];
699
+ const domain = Array.from({ length: arity }, (_, index) =>
700
+ op === OP_PATTERN
701
+ ? this.sorts[args[index]]
702
+ : op === OP_ITE && index === 0
703
+ ? SORT_BOOL
704
+ : argSort,
705
+ );
706
+ return { name: builtin[0], kind: builtin[1], domain };
707
+ }
708
+
709
+ // The hash of a pattern's Z3 declaration.
710
+ private getPatternHash(args: number[], range: number) {
711
+ const key = `${args.map((arg) => this.sorts[arg]).join(",")}:${range}`;
712
+ const existing = this.patternHashes.get(key);
713
+ if (existing !== undefined) return existing;
714
+ const hash = this.mkBuiltinHash(OP_PATTERN, args, range);
715
+ this.patternHashes.set(key, hash);
716
+ return hash;
717
+ }
718
+
719
+ // The slot in builtinHashes of the hash of a builtin's Z3 declaration, other than a pattern's. The
720
+ // domain depends only on the sort of an argument and the number of arguments, which key the cache
721
+ // with the op and range. It returns the slot, a small integer, because V8 boxes a hash it returns.
722
+ private getBuiltinSlot(op: number, args: number[], range: number) {
723
+ const argSort = args.length === 0 ? 0 : this.sorts[op === OP_ITE ? args[1] : args[0]];
724
+ const count = args.length;
725
+ const slot = this.findBuiltinSlot(op, argSort, range, count);
726
+ if (this.builtinKeys[4 * slot] !== -1) return slot;
727
+ const hash = this.mkBuiltinHash(op, args, range);
728
+ if (2 * (this.numBuiltinHashes + 1) > this.builtinHashes.length) {
729
+ const keys = this.builtinKeys;
730
+ const hashes = this.builtinHashes;
731
+ this.builtinKeys = new Int32Array(2 * keys.length).fill(-1);
732
+ this.builtinHashes = new Uint32Array(2 * hashes.length);
733
+ this.numBuiltinHashes = 0;
734
+ for (let index = 0; index < 4 * hashes.length; index += 4)
735
+ if (keys[index] !== -1)
736
+ this.insertBuiltinHash(
737
+ keys[index],
738
+ keys[index + 1],
739
+ keys[index + 2],
740
+ keys[index + 3],
741
+ hashes[index / 4],
742
+ );
743
+ }
744
+ return this.insertBuiltinHash(op, argSort, range, count, hash);
745
+ }
746
+
747
+ // The slot of the builtin hash with these keys, or the free slot where it goes.
748
+ private findBuiltinSlot(op: number, argSort: number, range: number, count: number) {
749
+ const keys = this.builtinKeys;
750
+ const mask = this.builtinHashes.length - 1;
751
+ let slot =
752
+ (Math.imul(Math.imul(Math.imul(op, 0x9e3779b1) + argSort, 0x9e3779b1) + range, 0x9e3779b1) +
753
+ count) &
754
+ mask;
755
+ while (
756
+ keys[4 * slot] !== -1 &&
757
+ (keys[4 * slot] !== op ||
758
+ keys[4 * slot + 1] !== argSort ||
759
+ keys[4 * slot + 2] !== range ||
760
+ keys[4 * slot + 3] !== count)
761
+ )
762
+ slot = (slot + 1) & mask;
763
+ return slot;
764
+ }
765
+
766
+ private insertBuiltinHash(
767
+ op: number,
768
+ argSort: number,
769
+ range: number,
770
+ count: number,
771
+ hash: number,
772
+ ) {
773
+ const slot = this.findBuiltinSlot(op, argSort, range, count);
774
+ this.builtinKeys.set([op, argSort, range, count], 4 * slot);
775
+ this.builtinHashes[slot] = hash;
776
+ this.numBuiltinHashes++;
777
+ return slot;
778
+ }
779
+
780
+ private mkBuiltinHash(op: number, args: number[], range: number) {
781
+ const signature = this.getBuiltinSignature(op, args);
782
+ const family =
783
+ op === OP_PATTERN ? Z3_PATTERN_FAMILY : op < OP_NUM ? Z3_BASIC_FAMILY : Z3_ARITH_FAMILY;
784
+ return this.getFuncDeclHash(
785
+ signature.name,
786
+ signature.domain,
787
+ range,
788
+ getInfoHash(family, signature.kind, []),
789
+ );
790
+ }
791
+
792
+ // The hash of a user declaration, which Z3's tables of declarations hash.
793
+ getDeclHash(decl: number) {
794
+ return this.declHashes[decl];
795
+ }
796
+
797
+ mkFuncDecl(name: SmtSymbol, domain: number[], range: number, isSkolem = false) {
798
+ this.declHashes[this.funcDecls.length] = this.getFuncDeclHash(
799
+ name,
800
+ domain,
801
+ range,
802
+ isSkolem ? getInfoHash(Z3_NULL, Z3_NULL, []) : 0,
803
+ );
804
+ this.funcDecls.push({
805
+ name,
806
+ family: FAMILY_USER,
807
+ op: OP_UNINTERPRETED,
808
+ domain,
809
+ range,
810
+ isSkolem,
811
+ smallId: this.mkSmallId(),
812
+ });
813
+ this.declRefCounts[this.funcDecls.length - 1] = 1;
814
+ return this.funcDecls.length - 1;
815
+ }
816
+
817
+ // mk_fresh_func_decl: without a prefix the name is the numerical symbol of the fresh id.
818
+ mkFreshFuncDecl(prefix: SmtSymbol | null, domain: number[], range: number, isSkolem = true) {
819
+ const name = prefix === null ? this.freshId : `${getSymbolName(prefix)}!${this.freshId}`;
820
+ this.freshId++;
821
+ const decl = this.mkFuncDecl(name, domain, range, isSkolem);
822
+ this.declRefCounts[decl] = 0;
823
+ return decl;
824
+ }
825
+
826
+ // mk_fresh_var_name.
827
+ mkFreshVarName(prefix: string | null) {
828
+ const name = `${prefix ?? "var"}!${this.freshId}`;
829
+ this.freshId++;
830
+ return name;
831
+ }
832
+
833
+ private intern(
834
+ key: string,
835
+ kind: number,
836
+ decl: number,
837
+ args: number[],
838
+ sort: number,
839
+ value: number,
840
+ getHash: () => number,
841
+ ) {
842
+ const existing = this.table.get(key);
843
+ if (existing !== undefined) return this.revive(existing);
844
+ const id = this.create(kind, decl, args, sort, value, getHash());
845
+ this.table.set(key, id);
846
+ this.registerNode(id);
847
+ return id;
848
+ }
849
+
850
+ private create(
851
+ kind: number,
852
+ decl: number,
853
+ args: number[],
854
+ sort: number,
855
+ value: number,
856
+ hash: number,
857
+ ) {
858
+ const id = this.numNodes++;
859
+ if (id === this.kinds.length) {
860
+ this.kinds = grow(this.kinds);
861
+ this.decls = grow(this.decls);
862
+ this.sorts = grow(this.sorts);
863
+ this.values = grow(this.values);
864
+ this.freeVarBounds = grow(this.freeVarBounds);
865
+ this.hasQuantifierFlags = grow(this.hasQuantifierFlags);
866
+ this.depths = grow(this.depths);
867
+ this.hashes = grow(this.hashes);
868
+ this.ids = grow(this.ids);
869
+ this.refCounts = grow(this.refCounts);
870
+ }
871
+ this.hashes[id] = hash;
872
+ this.kinds[id] = kind;
873
+ this.decls[id] = decl;
874
+ // Like Z3, a node keeps its own copy of the arguments, so callers may reuse their arrays.
875
+ const start = this.argStarts[id];
876
+ const end = start + args.length;
877
+ if (end > this.argPool.length) {
878
+ const pool = new Int32Array(Math.max(2 * this.argPool.length, end));
879
+ pool.set(this.argPool);
880
+ this.argPool = pool;
881
+ }
882
+ for (let index = 0; index < args.length; index++) this.argPool[start + index] = args[index];
883
+ if (id + 2 > this.argStarts.length) {
884
+ const starts = new Int32Array(2 * this.argStarts.length);
885
+ starts.set(this.argStarts);
886
+ this.argStarts = starts;
887
+ }
888
+ this.argStarts[id + 1] = end;
889
+ this.sorts[id] = sort;
890
+ this.values[id] = value;
891
+ let freeVarBound = kind === KIND_VAR ? value + 1 : 0;
892
+ let hasQuantifier = kind === KIND_QUANTIFIER;
893
+ let depth = 1;
894
+ for (let index = 0; index < args.length; index++) {
895
+ const arg = args[index];
896
+ if (this.freeVarBounds[arg] > freeVarBound) freeVarBound = this.freeVarBounds[arg];
897
+ if (this.hasQuantifierFlags[arg]) hasQuantifier = true;
898
+ if (this.depths[arg] + 1 > depth) depth = this.depths[arg] + 1;
899
+ }
900
+ this.freeVarBounds[id] = freeVarBound;
901
+ this.hasQuantifierFlags[id] = hasQuantifier ? 1 : 0;
902
+ this.depths[id] = depth;
903
+ return id;
904
+ }
905
+
906
+ // The op of a builtin declaration doubles as its index in funcDecls. The arguments are those of
907
+ // args from start on, so that a rewriter passes its result stack without copying it.
908
+ mkApp(decl: number, args: number[], sort: number, start = 0) {
909
+ const funcDecl = this.funcDecls[decl];
910
+ // Numerals and model values carry their value, so only mkNumeral and mkModelValue create them.
911
+ if (decl === OP_NUM || funcDecl.family === FAMILY_MODEL_VALUE)
912
+ throw new SmtInvariantError(`${funcDecl.name} needs a value`);
913
+ let hash = decl;
914
+ for (let index = start; index < args.length; index++)
915
+ hash = (Math.imul(hash, 0x9e3779b1) + args[index]) | 0;
916
+ const count = args.length - start;
917
+ const mask = this.appHandles.length - 1;
918
+ let slot = hash & mask;
919
+ for (; this.appHandles[slot] !== -1; slot = (slot + 1) & mask) {
920
+ const candidate = this.appHandles[slot];
921
+ if (this.appHashes[slot] !== hash || this.decls[candidate] !== decl) continue;
922
+ const poolStart = this.argStarts[candidate];
923
+ if (this.argStarts[candidate + 1] - poolStart !== count) continue;
924
+ let isSame = true;
925
+ for (let index = 0; index < count && isSame; index++)
926
+ isSame = this.argPool[poolStart + index] === args[start + index];
927
+ if (isSame) return this.revive(candidate);
928
+ }
929
+ if (start > 0) {
930
+ shrink(this.argBuffer, 0);
931
+ for (let index = start; index < args.length; index++) this.argBuffer.push(args[index]);
932
+ }
933
+ const nodeArgs = start > 0 ? this.argBuffer : args;
934
+ // The slot comes first, since finding it may replace builtinHashes with one twice the size.
935
+ const builtinSlot =
936
+ funcDecl.family === FAMILY_USER || funcDecl.op === OP_PATTERN
937
+ ? -1
938
+ : this.getBuiltinSlot(funcDecl.op, nodeArgs, sort);
939
+ const declHash =
940
+ funcDecl.family === FAMILY_USER
941
+ ? this.declHashes[decl]
942
+ : builtinSlot === -1
943
+ ? this.getPatternHash(nodeArgs, sort)
944
+ : this.builtinHashes[builtinSlot];
945
+ const id = this.create(
946
+ KIND_APP,
947
+ decl,
948
+ nodeArgs,
949
+ sort,
950
+ 0,
951
+ astArrayHash(nodeArgs, this.hashes, declHash),
952
+ );
953
+ // The lookup ended at a free slot, which the application takes unless the table doubles.
954
+ if (2 * (this.numApps + 1) > this.appHandles.length) {
955
+ const handles = this.appHandles;
956
+ const hashes = this.appHashes;
957
+ this.appHandles = new Int32Array(2 * handles.length).fill(-1);
958
+ this.appHashes = new Int32Array(2 * handles.length);
959
+ this.numApps = 0;
960
+ for (let index = 0; index < handles.length; index++)
961
+ if (handles[index] !== -1) this.insertApp(hashes[index], handles[index]);
962
+ this.insertApp(hash, id);
963
+ } else {
964
+ this.appHandles[slot] = id;
965
+ this.appHashes[slot] = hash;
966
+ this.numApps++;
967
+ }
968
+ this.registerNode(id);
969
+ return id;
970
+ }
971
+
972
+ private insertApp(hash: number, id: number) {
973
+ const mask = this.appHandles.length - 1;
974
+ let slot = hash & mask;
975
+ while (this.appHandles[slot] !== -1) slot = (slot + 1) & mask;
976
+ this.appHandles[slot] = id;
977
+ this.appHashes[slot] = hash;
978
+ this.numApps++;
979
+ }
980
+
981
+ // A numeral's declaration has the parameters (value, is_int), and a rational hashes as
982
+ // hash(numerator) + 3 hash(denominator).
983
+ private internNumeral(key: string, value: Rational, sort: number) {
984
+ const existing = this.table.get(key);
985
+ if (existing !== undefined) return this.revive(existing);
986
+ this.numeralValues.push(value);
987
+ const isInt = sort === SORT_INT;
988
+ return this.intern(key, KIND_APP, OP_NUM, [], sort, this.numeralValues.length - 1, () =>
989
+ this.getFuncDeclHash(
990
+ isInt ? "Int" : "Real",
991
+ [],
992
+ sort,
993
+ getInfoHash(Z3_ARITH_FAMILY, 0, [
994
+ (getIntegerHash(value.num) + 3 * getIntegerHash(value.den)) >>> 0,
995
+ isInt ? 1 : 0,
996
+ ]),
997
+ ),
998
+ );
999
+ }
1000
+
1001
+ mkRealNumeral(value: Rational) {
1002
+ const numeral = this.internNumeral(`r${value}`, value, SORT_REAL);
1003
+ return value.isInt() ? this.holdSmallNumeral(numeral, value.num, this.smallReals) : numeral;
1004
+ }
1005
+
1006
+ mkNumeral(value: bigint) {
1007
+ const existing = this.intNumerals.get(value);
1008
+ if (existing !== undefined)
1009
+ return this.holdSmallNumeral(this.revive(existing), value, this.smallInts);
1010
+ const numeral = this.internNumeral(`n${value}`, Rational.of(value), SORT_INT);
1011
+ this.intNumerals.set(value, numeral);
1012
+ return this.holdSmallNumeral(numeral, value, this.smallInts);
1013
+ }
1014
+
1015
+ private holdSmallNumeral(numeral: number, value: bigint, cache: number[]) {
1016
+ if (value < 0n || value >= MAX_SMALL_NUM_TO_CACHE) return numeral;
1017
+ const index = Number(value);
1018
+ if (cache[index] !== undefined) return numeral;
1019
+ this.incRef(numeral);
1020
+ cache[index] = numeral;
1021
+ return numeral;
1022
+ }
1023
+
1024
+ // mk_numeral(value, is_int).
1025
+ mkNumeralOfSort(value: Rational, sort: number) {
1026
+ return sort === SORT_INT ? this.mkNumeral(value.num) : this.mkRealNumeral(value);
1027
+ }
1028
+
1029
+ // mk_model_value: the element with this index in the universe of an uninterpreted sort.
1030
+ mkModelValue(index: number, sort: number) {
1031
+ const key = `m${sort}:${index}`;
1032
+ const existing = this.table.get(key);
1033
+ if (existing !== undefined) return this.revive(existing);
1034
+ this.funcDecls.push({
1035
+ name: `${this.sortNames[sort]}!val!${index}`,
1036
+ family: FAMILY_MODEL_VALUE,
1037
+ op: OP_MODEL_VALUE,
1038
+ domain: [],
1039
+ range: sort,
1040
+ isSkolem: false,
1041
+ smallId: -1,
1042
+ });
1043
+ const decl = this.funcDecls.length - 1;
1044
+ this.declHashes[decl] = this.getFuncDeclHash(
1045
+ this.funcDecls[decl].name,
1046
+ [],
1047
+ sort,
1048
+ getInfoHash(Z3_MODEL_VALUE_FAMILY, 0, [index, this.sortHashes[sort]]),
1049
+ );
1050
+ return this.intern(key, KIND_APP, decl, [], sort, index, () => this.declHashes[decl]);
1051
+ }
1052
+
1053
+ mkFreshConst(prefix: SmtSymbol | null, sort: number) {
1054
+ return this.mkApp(this.mkFreshFuncDecl(prefix, [], sort), [], sort);
1055
+ }
1056
+
1057
+ mkVar(index: number, sort: number) {
1058
+ return this.intern(`v${index}:${sort}`, KIND_VAR, -1, [], sort, index, () =>
1059
+ combineHash(index, this.sortHashes[sort]),
1060
+ );
1061
+ }
1062
+
1063
+ mkQuantifier(data: QuantifierData) {
1064
+ if (data.names.length !== data.sorts.length)
1065
+ throw new SmtInvariantError("a quantifier needs a name for each variable");
1066
+ const key = `q${data.isForall ? 1 : 0}:${data.sorts.join(",")}:${JSON.stringify(data.names)}:${
1067
+ data.body
1068
+ }:${data.patterns.join(",")}:${data.weight}`;
1069
+ const existing = this.table.get(key);
1070
+ if (existing !== undefined) return this.revive(existing);
1071
+ const id = this.create(
1072
+ KIND_QUANTIFIER,
1073
+ -1,
1074
+ [data.body],
1075
+ SORT_BOOL,
1076
+ 0,
1077
+ mkMix(
1078
+ astArrayHash(data.sorts, this.sortHashes, data.isForall ? 31 : 19),
1079
+ data.patterns.length,
1080
+ this.hashes[data.body],
1081
+ ),
1082
+ );
1083
+ this.table.set(key, id);
1084
+ const bodyBound = this.freeVarBounds[data.body];
1085
+ this.freeVarBounds[id] = Math.max(0, bodyBound - data.sorts.length);
1086
+ this.quantifiers.set(id, {
1087
+ ...data,
1088
+ sorts: [...data.sorts],
1089
+ names: [...data.names],
1090
+ patterns: [...data.patterns],
1091
+ });
1092
+ this.registerNode(id);
1093
+ return id;
1094
+ }
1095
+
1096
+ // mk_pattern: a multi-pattern of a quantifier.
1097
+ mkPattern(terms: number[]) {
1098
+ return this.mkApp(OP_PATTERN, terms, SORT_BOOL);
1099
+ }
1100
+
1101
+ getQuantifier(expr: number) {
1102
+ const data = this.quantifiers.get(expr);
1103
+ if (data === undefined) throw new SmtInvariantError("the expression is not a quantifier");
1104
+ return data;
1105
+ }
1106
+
1107
+ isApp(expr: number) {
1108
+ return this.kinds[expr] === KIND_APP;
1109
+ }
1110
+
1111
+ isVar(expr: number) {
1112
+ return this.kinds[expr] === KIND_VAR;
1113
+ }
1114
+
1115
+ isGround(expr: number) {
1116
+ return this.freeVarBounds[expr] === 0;
1117
+ }
1118
+
1119
+ // Z3's is_ground: an application without variables or quantifiers.
1120
+ isGroundApp(expr: number) {
1121
+ return (
1122
+ this.kinds[expr] === KIND_APP &&
1123
+ this.freeVarBounds[expr] === 0 &&
1124
+ !this.hasQuantifierFlags[expr]
1125
+ );
1126
+ }
1127
+
1128
+ getOp(expr: number) {
1129
+ return this.kinds[expr] === KIND_APP ? this.funcDecls[this.decls[expr]].op : -1;
1130
+ }
1131
+
1132
+ getFamily(expr: number) {
1133
+ return this.kinds[expr] === KIND_APP ? this.funcDecls[this.decls[expr]].family : -1;
1134
+ }
1135
+
1136
+ isBool(expr: number) {
1137
+ return this.sorts[expr] === SORT_BOOL;
1138
+ }
1139
+
1140
+ isInt(expr: number) {
1141
+ return this.sorts[expr] === SORT_INT;
1142
+ }
1143
+
1144
+ isReal(expr: number) {
1145
+ return this.sorts[expr] === SORT_REAL;
1146
+ }
1147
+
1148
+ isTrue(expr: number) {
1149
+ return expr === this.trueExpr;
1150
+ }
1151
+
1152
+ isFalse(expr: number) {
1153
+ return expr === this.falseExpr;
1154
+ }
1155
+
1156
+ isNot(expr: number) {
1157
+ return this.getOp(expr) === OP_NOT;
1158
+ }
1159
+
1160
+ isComplement(first: number, second: number) {
1161
+ return (
1162
+ (this.isNot(first) && this.getArg(first, 0) === second) ||
1163
+ (this.isNot(second) && this.getArg(second, 0) === first) ||
1164
+ (first === this.trueExpr && second === this.falseExpr) ||
1165
+ (first === this.falseExpr && second === this.trueExpr)
1166
+ );
1167
+ }
1168
+
1169
+ isNumeral(expr: number) {
1170
+ return this.getOp(expr) === OP_NUM;
1171
+ }
1172
+
1173
+ // The value of an integer numeral.
1174
+ getNumeral(expr: number) {
1175
+ return this.isNumeral(expr) && this.sorts[expr] === SORT_INT
1176
+ ? this.getNumeralValue(expr)
1177
+ : undefined;
1178
+ }
1179
+
1180
+ // The value of an expression that is an integer numeral.
1181
+ getNumeralValue(expr: number) {
1182
+ return this.numeralValues[this.values[expr]].num;
1183
+ }
1184
+
1185
+ // The value of an expression that is a numeral of either sort.
1186
+ getRationalValue(expr: number) {
1187
+ return this.numeralValues[this.values[expr]];
1188
+ }
1189
+
1190
+ // Unique values are interpreted constants that are distinct from each other, as in Z3.
1191
+ isUniqueValue(expr: number) {
1192
+ const op = this.getOp(expr);
1193
+ return op === OP_NUM || op === OP_TRUE || op === OP_FALSE || op === OP_MODEL_VALUE;
1194
+ }
1195
+
1196
+ // are_distinct: the plugin of the first term's family, or of the second's for a user term, tells
1197
+ // two terms apart. Every plugin separates distinct unique values, and arith also separates b from
1198
+ // (+ b k) and (+ k b) for a nonzero numeral k.
1199
+ areDistinct(first: number, second: number) {
1200
+ if (this.kinds[first] !== KIND_APP || this.kinds[second] !== KIND_APP) return false;
1201
+ if (first !== second && this.isUniqueValue(first) && this.isUniqueValue(second)) return true;
1202
+ const family = this.funcDecls[this.decls[first]].family;
1203
+ if (
1204
+ (family === FAMILY_USER ? this.funcDecls[this.decls[second]].family : family) !== FAMILY_ARITH
1205
+ )
1206
+ return false;
1207
+ const isOffsetOf = (sum: number, term: number) => {
1208
+ if (this.getOp(sum) !== OP_ADD || this.getNumArgs(sum) !== 2) return false;
1209
+ const first = this.getArg(sum, 0);
1210
+ const second = this.getArg(sum, 1);
1211
+ const isNonZero = (expr: number) =>
1212
+ this.isNumeral(expr) && !this.getRationalValue(expr).isZero();
1213
+ return (first === term && isNonZero(second)) || (second === term && isNonZero(first));
1214
+ };
1215
+ return isOffsetOf(first, second) || isOffsetOf(second, first);
1216
+ }
1217
+
1218
+ isModelValue(expr: number) {
1219
+ return this.getOp(expr) === OP_MODEL_VALUE;
1220
+ }
1221
+
1222
+ isUninterpretedSort(sort: number) {
1223
+ return sort > SORT_REAL;
1224
+ }
1225
+
1226
+ // An uninterpreted constant, such as a declared constant or a Skolem constant.
1227
+ isUninterpretedConst(expr: number) {
1228
+ return this.isUninterpreted(expr) && this.getNumArgs(expr) === 0;
1229
+ }
1230
+
1231
+ isUninterpreted(expr: number) {
1232
+ return this.getFamily(expr) === FAMILY_USER;
1233
+ }
1234
+
1235
+ // arith_util::is_times_minus_one: the t of (* -1 t).
1236
+ getTimesMinusOneArg(expr: number) {
1237
+ if (this.getOp(expr) !== OP_MUL || this.getNumArgs(expr) !== 2) return undefined;
1238
+ const coefficient = this.getArg(expr, 0);
1239
+ return this.isNumeral(coefficient) &&
1240
+ this.getRationalValue(coefficient).equals(Rational.minusOne)
1241
+ ? this.getArg(expr, 1)
1242
+ : undefined;
1243
+ }
1244
+
1245
+ // occurs: decl is applied somewhere in expr.
1246
+ isOccurring(decl: number, expr: number) {
1247
+ return this.someSubterm(expr, (current) => this.decls[current] === decl);
1248
+ }
1249
+
1250
+ containsModelValue(expr: number) {
1251
+ return this.someSubterm(expr, (current) => this.isModelValue(current));
1252
+ }
1253
+
1254
+ // for_each_expr: visits the subterms with a stack of its own, so deep terms do not exhaust the call
1255
+ // stack.
1256
+ private someSubterm(expr: number, predicate: (expr: number) => boolean) {
1257
+ const visited = new Set<number>();
1258
+ const todo = [expr];
1259
+ for (let current = todo.pop(); current !== undefined; current = todo.pop()) {
1260
+ if (visited.has(current)) continue;
1261
+ visited.add(current);
1262
+ const kind = this.kinds[current];
1263
+ if (kind === KIND_QUANTIFIER) todo.push(this.getQuantifier(current).body);
1264
+ else if (kind !== KIND_VAR) {
1265
+ if (predicate(current)) return true;
1266
+ this.pushArgs(current, todo);
1267
+ }
1268
+ }
1269
+ return false;
1270
+ }
1271
+
1272
+ mkNot(expr: number) {
1273
+ if (expr === this.trueExpr) return this.falseExpr;
1274
+ if (expr === this.falseExpr) return this.trueExpr;
1275
+ return this.mkApp(OP_NOT, [expr], SORT_BOOL);
1276
+ }
1277
+
1278
+ mkEq(left: number, right: number) {
1279
+ return this.mkApp(OP_EQ, [left, right], SORT_BOOL);
1280
+ }
1281
+
1282
+ mkOr(args: number[]) {
1283
+ if (args.length === 0) return this.falseExpr;
1284
+ if (args.length === 1) return args[0];
1285
+ return this.mkApp(OP_OR, args, SORT_BOOL);
1286
+ }
1287
+
1288
+ mkAnd(args: number[]) {
1289
+ if (args.length === 0) return this.trueExpr;
1290
+ if (args.length === 1) return args[0];
1291
+ return this.mkApp(OP_AND, args, SORT_BOOL);
1292
+ }
1293
+
1294
+ getDeclName(expr: number) {
1295
+ return getSymbolName(this.funcDecls[this.decls[expr]].name);
1296
+ }
1297
+
1298
+ toString(expr: number): string {
1299
+ const kind = this.kinds[expr];
1300
+ if (kind === KIND_VAR) return `(:var ${this.values[expr]})`;
1301
+ if (kind === KIND_QUANTIFIER) {
1302
+ const data = this.getQuantifier(expr);
1303
+ return `(${data.isForall ? "forall" : "exists"} (${data.sorts.length}) ${this.toString(data.body)})`;
1304
+ }
1305
+ if (this.getOp(expr) === OP_NUM) {
1306
+ const value = this.getRationalValue(expr);
1307
+ if (this.sorts[expr] === SORT_INT) return String(value.num);
1308
+ return value.isInt() ? `${value.num}.0` : `(/ ${value.num}.0 ${value.den}.0)`;
1309
+ }
1310
+ const name = this.getDeclName(expr);
1311
+ return this.getNumArgs(expr) === 0
1312
+ ? name
1313
+ : `(${name} ${this.mapArgs(expr, (innerArg) => this.toString(innerArg)).join(" ")})`;
1314
+ }
1315
+ }