tla-ts 0.0.10-dev.63a6693bd → 0.0.10-dev.6b2a6741a

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 (551) hide show
  1. package/README.md +2 -1
  2. package/dist/compile.cjs +3 -3
  3. package/dist/compile.js +1 -1
  4. package/dist/deciders.cjs +41 -37
  5. package/dist/deciders.js +45 -41
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +5 -1
  8. package/dist/index.d.ts +5 -1
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +2682 -426
  15. package/dist/prove.js +2679 -423
  16. package/dist/run.cjs +43 -42
  17. package/dist/run.js +44 -43
  18. package/dist/tlapm.cjs +1 -1
  19. package/dist/tlapm.js +1 -1
  20. package/dist/transfer.cjs +43 -40
  21. package/dist/transfer.js +43 -40
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +1 -1
  25. package/src/ast.ts +4 -3
  26. package/src/bags.ts +46 -28
  27. package/src/check-trace.ts +2 -16
  28. package/src/check.ts +349 -91
  29. package/src/cli/runtime-invariants.ts +20 -56
  30. package/src/cli/tlapm.ts +424 -62
  31. package/src/cli/tlc-arguments.ts +2 -2
  32. package/src/cli/tlc-output.ts +4 -5
  33. package/src/cli/tlc-usage.ts +0 -1
  34. package/src/cli/tlc.ts +26 -7
  35. package/src/cli/xml-exporter.ts +1 -1
  36. package/src/codegen.ts +9 -5
  37. package/src/dependencies.ts +72 -11
  38. package/src/dfid.ts +9 -2
  39. package/src/environment.ts +65 -36
  40. package/src/errors.ts +38 -3
  41. package/src/evaluate.ts +92 -32
  42. package/src/exit-codes.ts +5 -2
  43. package/src/instances.ts +5 -5
  44. package/src/java-overrides.ts +2 -2
  45. package/src/levels.ts +138 -90
  46. package/src/lexer.ts +5 -3
  47. package/src/liveness-checker.ts +572 -204
  48. package/src/liveness.ts +47 -32
  49. package/src/obligations/action.ts +10 -6
  50. package/src/obligations/anonymize.ts +33 -14
  51. package/src/obligations/enabled-axioms.ts +218 -0
  52. package/src/obligations/equality.ts +1 -3
  53. package/src/obligations/expression.ts +18 -6
  54. package/src/obligations/format.ts +0 -2
  55. package/src/obligations/generate.ts +22 -17
  56. package/src/obligations/index.ts +37 -7
  57. package/src/obligations/levels.ts +24 -11
  58. package/src/obligations/module.ts +1 -3
  59. package/src/obligations/normalize.ts +25 -17
  60. package/src/obligations/operators.ts +0 -2
  61. package/src/obligations/pragma.ts +53 -16
  62. package/src/obligations/printer.ts +48 -18
  63. package/src/obligations/proof.ts +3 -2
  64. package/src/obligations/regroup.ts +0 -2
  65. package/src/obligations/simplify.ts +17 -7
  66. package/src/obligations/source.ts +71 -17
  67. package/src/obligations/subexpression.ts +45 -18
  68. package/src/obligations/substitution.ts +1 -3
  69. package/src/obligations/temporal.ts +0 -2
  70. package/src/obligations/tuples.ts +0 -2
  71. package/src/parallel-worker.ts +8 -2
  72. package/src/parallel.ts +7 -2
  73. package/src/parser.ts +664 -287
  74. package/src/pretty-print.ts +1 -1
  75. package/src/prover/deciders.ts +11 -8
  76. package/src/prover/isabelle/decide.ts +3 -25
  77. package/src/prover/isabelle/encode.ts +71 -41
  78. package/src/prover/isabelle/isar/attrib.ts +250 -0
  79. package/src/prover/isabelle/isar/context.ts +335 -0
  80. package/src/prover/isabelle/isar/induct.ts +382 -0
  81. package/src/prover/isabelle/isar/inner-syntax.ts +149 -3
  82. package/src/prover/isabelle/isar/method.ts +506 -198
  83. package/src/prover/isabelle/isar/proof.ts +570 -14
  84. package/src/prover/isabelle/isar/rule-cases.ts +226 -0
  85. package/src/prover/isabelle/isar/theory.ts +479 -69
  86. package/src/prover/isabelle/isar/toplevel.ts +331 -0
  87. package/src/prover/isabelle/isar/type-check.ts +83 -8
  88. package/src/prover/isabelle/provers/blast/blast.ts +0 -2
  89. package/src/prover/isabelle/provers/blast/branch.ts +0 -2
  90. package/src/prover/isabelle/provers/blast/prove.ts +0 -2
  91. package/src/prover/isabelle/provers/blast/rules.ts +0 -2
  92. package/src/prover/isabelle/provers/blast/state.ts +0 -2
  93. package/src/prover/isabelle/provers/blast/term.ts +0 -2
  94. package/src/prover/isabelle/provers/clasimp.ts +1 -3
  95. package/src/prover/isabelle/provers/classical.ts +45 -20
  96. package/src/prover/isabelle/provers/hypsubst.ts +2 -4
  97. package/src/prover/isabelle/pure/bicompose.ts +0 -2
  98. package/src/prover/isabelle/pure/consts.ts +0 -2
  99. package/src/prover/isabelle/pure/conv.ts +0 -2
  100. package/src/prover/isabelle/pure/drule.ts +63 -4
  101. package/src/prover/isabelle/pure/envir.ts +0 -2
  102. package/src/prover/isabelle/pure/goal.ts +1 -3
  103. package/src/prover/isabelle/pure/logic.ts +0 -2
  104. package/src/prover/isabelle/pure/name.ts +0 -2
  105. package/src/prover/isabelle/pure/net.ts +0 -2
  106. package/src/prover/isabelle/pure/object-logic.ts +13 -7
  107. package/src/prover/isabelle/pure/pattern.ts +0 -2
  108. package/src/prover/isabelle/pure/raw-simplifier.ts +0 -2
  109. package/src/prover/isabelle/pure/rewriter.ts +4 -11
  110. package/src/prover/isabelle/pure/search.ts +0 -2
  111. package/src/prover/isabelle/pure/seq.ts +0 -2
  112. package/src/prover/isabelle/pure/simplifier.ts +26 -7
  113. package/src/prover/isabelle/pure/table.ts +0 -2
  114. package/src/prover/isabelle/pure/tactic.ts +0 -2
  115. package/src/prover/isabelle/pure/tactical.ts +0 -2
  116. package/src/prover/isabelle/pure/term-ord.ts +0 -2
  117. package/src/prover/isabelle/pure/term.ts +3 -5
  118. package/src/prover/isabelle/pure/thm.ts +0 -2
  119. package/src/prover/isabelle/pure/type.ts +0 -2
  120. package/src/prover/isabelle/pure/unify.ts +0 -2
  121. package/src/prover/isabelle/pure/variable.ts +0 -2
  122. package/src/prover/isabelle/tla/classical-setup.ts +1 -2
  123. package/src/prover/isabelle/tla/context.ts +51 -9
  124. package/src/prover/isabelle/tla/logic-data.ts +1 -1
  125. package/src/prover/isabelle/tla/logic.ts +40 -1
  126. package/src/prover/isabelle/tla/simpdata.ts +0 -2
  127. package/src/prover/isabelle/tools/intuitionistic.ts +28 -12
  128. package/src/prover/ocaml.ts +4 -1
  129. package/src/prover/prep/action.ts +19 -12
  130. package/src/prover/prep/enabled-axioms.ts +11 -2
  131. package/src/prover/prep/md5.ts +26 -29
  132. package/src/prover/prep/methods.ts +159 -50
  133. package/src/prover/prep/normalize.ts +38 -9
  134. package/src/prover/prove.ts +343 -65
  135. package/src/prover/ptl/decide.ts +95 -50
  136. package/src/prover/ptl/encode.ts +2 -3
  137. package/src/prover/ptl/tableau.ts +28 -2
  138. package/src/prover/smt/arithmetic.ts +310 -0
  139. package/src/prover/smt/axioms.ts +12 -8
  140. package/src/prover/smt/context.ts +42 -6
  141. package/src/prover/smt/data.ts +191 -84
  142. package/src/prover/smt/encode.ts +122 -43
  143. package/src/prover/smt/extensionality.ts +5 -3
  144. package/src/prover/smt/flatten.ts +4 -6
  145. package/src/prover/smt/format.ts +28 -4
  146. package/src/prover/smt/instances.ts +7 -1
  147. package/src/prover/smt/layout.ts +91 -0
  148. package/src/prover/smt/rewrite.ts +483 -116
  149. package/src/prover/smt/simplify.ts +441 -0
  150. package/src/prover/smt/solver/ackermannize-bv-tactic.ts +61 -0
  151. package/src/prover/smt/solver/ackr-helper.ts +179 -0
  152. package/src/prover/smt/solver/ackr-model-converter.ts +105 -0
  153. package/src/prover/smt/solver/act-cache.ts +0 -1
  154. package/src/prover/smt/solver/add-bounds-tactic.ts +59 -0
  155. package/src/prover/smt/solver/aig-tactic.ts +52 -0
  156. package/src/prover/smt/solver/aig.ts +889 -0
  157. package/src/prover/smt/solver/arith-rewriter.ts +613 -6
  158. package/src/prover/smt/solver/arith-terms.ts +121 -0
  159. package/src/prover/smt/solver/array-decl-plugin.ts +175 -0
  160. package/src/prover/smt/solver/array-rewriter.ts +309 -0
  161. package/src/prover/smt/solver/asserted-formulas.ts +93 -15
  162. package/src/prover/smt/solver/ast-lt.ts +165 -11
  163. package/src/prover/smt/solver/ast-util.ts +160 -2
  164. package/src/prover/smt/solver/ast.ts +1449 -41
  165. package/src/prover/smt/solver/auf-solver.ts +0 -1
  166. package/src/prover/smt/solver/bit-blast-tactic.ts +582 -0
  167. package/src/prover/smt/solver/bit-blaster.ts +871 -0
  168. package/src/prover/smt/solver/bound-manager.ts +196 -0
  169. package/src/prover/smt/solver/bound-simplifier.ts +600 -0
  170. package/src/prover/smt/solver/bv-bound-chk.ts +492 -0
  171. package/src/prover/smt/solver/bv-decl-plugin.ts +341 -0
  172. package/src/prover/smt/solver/bv-divrem-bounds.ts +95 -0
  173. package/src/prover/smt/solver/bv-rewriter.ts +1901 -0
  174. package/src/prover/smt/solver/bv1-blast.ts +214 -0
  175. package/src/prover/smt/solver/bv2fpa-converter.ts +174 -0
  176. package/src/prover/smt/solver/bv2int-rewriter.ts +544 -0
  177. package/src/prover/smt/solver/bv2real-rewriter.ts +533 -0
  178. package/src/prover/smt/solver/card2bv.ts +109 -0
  179. package/src/prover/smt/solver/case-split-queue.ts +0 -2
  180. package/src/prover/smt/solver/cg-table.ts +39 -25
  181. package/src/prover/smt/solver/check-logic.ts +330 -0
  182. package/src/prover/smt/solver/clause.ts +0 -1
  183. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +278 -0
  184. package/src/prover/smt/solver/conflict-resolution.ts +78 -2
  185. package/src/prover/smt/solver/context.ts +533 -114
  186. package/src/prover/smt/solver/ctx-simplify.ts +21 -12
  187. package/src/prover/smt/solver/ctx-solver-simplify.ts +122 -0
  188. package/src/prover/smt/solver/datatype-decl-plugin.ts +572 -0
  189. package/src/prover/smt/solver/datatype-rewriter.ts +82 -0
  190. package/src/prover/smt/solver/demodulator.ts +786 -0
  191. package/src/prover/smt/solver/dependent-expr-state.ts +81 -0
  192. package/src/prover/smt/solver/der.ts +38 -10
  193. package/src/prover/smt/solver/diff-neq.ts +205 -0
  194. package/src/prover/smt/solver/distribute-forall.ts +57 -0
  195. package/src/prover/smt/solver/dom-simplify.ts +511 -0
  196. package/src/prover/smt/solver/dt2bv-tactic.ts +260 -0
  197. package/src/prover/smt/solver/dyn-ack.ts +0 -1
  198. package/src/prover/smt/solver/e-matching.ts +6 -7
  199. package/src/prover/smt/solver/elim-small-bv-tactic.ts +129 -0
  200. package/src/prover/smt/solver/elim-uncnstr.ts +542 -0
  201. package/src/prover/smt/solver/enode.ts +100 -3
  202. package/src/prover/smt/solver/eq2bv-tactic.ts +218 -0
  203. package/src/prover/smt/solver/euf/arith-axioms.ts +403 -0
  204. package/src/prover/smt/solver/euf/arith-internalize.ts +653 -0
  205. package/src/prover/smt/solver/euf/arith-solver.ts +889 -0
  206. package/src/prover/smt/solver/euf/array-axioms.ts +527 -0
  207. package/src/prover/smt/solver/euf/array-internalize.ts +428 -0
  208. package/src/prover/smt/solver/euf/array-solver.ts +306 -0
  209. package/src/prover/smt/solver/euf/bv-ackerman.ts +162 -0
  210. package/src/prover/smt/solver/euf/bv-internalize.ts +748 -0
  211. package/src/prover/smt/solver/euf/bv-solver.ts +449 -0
  212. package/src/prover/smt/solver/euf/dt-solver.ts +618 -0
  213. package/src/prover/smt/solver/euf/egraph.ts +901 -0
  214. package/src/prover/smt/solver/euf/euf-solver.ts +1204 -0
  215. package/src/prover/smt/solver/euf/fpa-solver.ts +317 -0
  216. package/src/prover/smt/solver/euf/mam.ts +1046 -0
  217. package/src/prover/smt/solver/euf/q-ematch.ts +829 -0
  218. package/src/prover/smt/solver/euf/q-mbi.ts +587 -0
  219. package/src/prover/smt/solver/euf/q-model-fixer.ts +296 -0
  220. package/src/prover/smt/solver/euf/q-solver.ts +361 -0
  221. package/src/prover/smt/solver/euf/th-solver.ts +328 -0
  222. package/src/prover/smt/solver/euf/th-solvers.ts +30 -0
  223. package/src/prover/smt/solver/expr-ref.ts +0 -1
  224. package/src/prover/smt/solver/expr-safe-replace.ts +26 -2
  225. package/src/prover/smt/solver/expr2polynomial.ts +271 -0
  226. package/src/prover/smt/solver/factor.ts +163 -0
  227. package/src/prover/smt/solver/fd-solver.ts +267 -0
  228. package/src/prover/smt/solver/fingerprints.ts +15 -15
  229. package/src/prover/smt/solver/fix-dl-var.ts +147 -0
  230. package/src/prover/smt/solver/flat-literals.ts +0 -1
  231. package/src/prover/smt/solver/fm-tactic.ts +884 -0
  232. package/src/prover/smt/solver/fpa-decl-plugin.ts +618 -0
  233. package/src/prover/smt/solver/fpa-rewriter.ts +639 -0
  234. package/src/prover/smt/solver/fpa2bv-converter.ts +2251 -0
  235. package/src/prover/smt/solver/fpa2bv-rewriter.ts +349 -0
  236. package/src/prover/smt/solver/fpa2bv-tactic.ts +73 -0
  237. package/src/prover/smt/solver/goal.ts +177 -15
  238. package/src/prover/smt/solver/goal2nlsat.ts +216 -0
  239. package/src/prover/smt/solver/guard-set.ts +219 -0
  240. package/src/prover/smt/solver/hash.ts +0 -1
  241. package/src/prover/smt/solver/hashtable.ts +30 -16
  242. package/src/prover/smt/solver/inf-eps.ts +63 -0
  243. package/src/prover/smt/solver/inj-axiom.ts +101 -0
  244. package/src/prover/smt/solver/internalizer.ts +109 -36
  245. package/src/prover/smt/solver/lackr.ts +381 -0
  246. package/src/prover/smt/solver/lbool.ts +0 -1
  247. package/src/prover/smt/solver/lia2card.ts +268 -0
  248. package/src/prover/smt/solver/lia2pb.ts +154 -0
  249. package/src/prover/smt/solver/literal.ts +0 -1
  250. package/src/prover/smt/solver/logic-tactics.ts +345 -0
  251. package/src/prover/smt/solver/lp/bound-propagator.ts +0 -1
  252. package/src/prover/smt/solver/lp/constraints.ts +0 -1
  253. package/src/prover/smt/solver/lp/containers.ts +7 -2
  254. package/src/prover/smt/solver/lp/core-solver.ts +18 -3
  255. package/src/prover/smt/solver/lp/cross-nested.ts +1 -4
  256. package/src/prover/smt/solver/lp/dep-intervals.ts +0 -3
  257. package/src/prover/smt/solver/lp/dependency.ts +0 -2
  258. package/src/prover/smt/solver/lp/dioph-eq.ts +0 -2
  259. package/src/prover/smt/solver/lp/explanation.ts +0 -1
  260. package/src/prover/smt/solver/lp/gomory.ts +0 -1
  261. package/src/prover/smt/solver/lp/hnf-cutter.ts +0 -1
  262. package/src/prover/smt/solver/lp/hnf.ts +0 -3
  263. package/src/prover/smt/solver/lp/int-cube.ts +3 -4
  264. package/src/prover/smt/solver/lp/int-solver.ts +0 -2
  265. package/src/prover/smt/solver/lp/lar-solver.ts +40 -4
  266. package/src/prover/smt/solver/lp/lar-term.ts +0 -1
  267. package/src/prover/smt/solver/lp/lp-settings.ts +0 -1
  268. package/src/prover/smt/solver/lp/maximize-term.ts +59 -10
  269. package/src/prover/smt/solver/lp/nex-creator.ts +3 -3
  270. package/src/prover/smt/solver/lp/nex.ts +2 -2
  271. package/src/prover/smt/solver/lp/nla-backoff.ts +0 -2
  272. package/src/prover/smt/solver/lp/nla-basics.ts +46 -3
  273. package/src/prover/smt/solver/lp/nla-core.ts +66 -11
  274. package/src/prover/smt/solver/lp/nla-divisions.ts +0 -2
  275. package/src/prover/smt/solver/lp/nla-emonics.ts +0 -1
  276. package/src/prover/smt/solver/lp/nla-factorization.ts +0 -1
  277. package/src/prover/smt/solver/lp/nla-grobner.ts +167 -85
  278. package/src/prover/smt/solver/lp/nla-horner.ts +0 -2
  279. package/src/prover/smt/solver/lp/nla-intervals.ts +0 -1
  280. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +0 -2
  281. package/src/prover/smt/solver/lp/nla-monotone.ts +0 -1
  282. package/src/prover/smt/solver/lp/nla-order.ts +0 -2
  283. package/src/prover/smt/solver/lp/nla-patcher.ts +0 -1
  284. package/src/prover/smt/solver/lp/nla-powers.ts +220 -0
  285. package/src/prover/smt/solver/lp/nla-tangents.ts +0 -2
  286. package/src/prover/smt/solver/lp/nla-throttle.ts +0 -1
  287. package/src/prover/smt/solver/lp/nla-transcendentals.ts +324 -0
  288. package/src/prover/smt/solver/lp/nla-types.ts +0 -2
  289. package/src/prover/smt/solver/lp/nla-var-eqs.ts +0 -1
  290. package/src/prover/smt/solver/lp/nra-solver.ts +163 -99
  291. package/src/prover/smt/solver/lp/numeric-pair.ts +0 -1
  292. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -3
  293. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -21
  294. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -41
  295. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  296. package/src/prover/smt/solver/lp/random-updater.ts +0 -2
  297. package/src/prover/smt/solver/lp/static-matrix.ts +0 -1
  298. package/src/prover/smt/solver/lp/union-find.ts +7 -2
  299. package/src/prover/smt/solver/macro-finder.ts +530 -0
  300. package/src/prover/smt/solver/mam-compiler.ts +118 -88
  301. package/src/prover/smt/solver/mam-interpreter.ts +0 -1
  302. package/src/prover/smt/solver/max-bv-sharing-tactic.ts +17 -0
  303. package/src/prover/smt/solver/max-cliques.ts +105 -0
  304. package/src/prover/smt/solver/maxcore.ts +309 -0
  305. package/src/prover/smt/solver/maximize-ac-sharing.ts +8 -6
  306. package/src/prover/smt/solver/maxlex.ts +115 -0
  307. package/src/prover/smt/solver/maxsmt-base.ts +105 -0
  308. package/src/prover/smt/solver/maxsmt.ts +92 -0
  309. package/src/prover/smt/solver/mbp/mbp-arith.ts +467 -0
  310. package/src/prover/smt/solver/mbp/mbp-basic-tg.ts +101 -0
  311. package/src/prover/smt/solver/mbp/mbp-plugin.ts +287 -0
  312. package/src/prover/smt/solver/mbp/mbp-qel.ts +48 -0
  313. package/src/prover/smt/solver/mbp/mbp-solve-plugin.ts +271 -0
  314. package/src/prover/smt/solver/mbp/mbp-term-graph.ts +606 -0
  315. package/src/prover/smt/solver/model-based-opt.ts +844 -0
  316. package/src/prover/smt/solver/model-checker.ts +17 -26
  317. package/src/prover/smt/solver/model-evaluator.ts +188 -12
  318. package/src/prover/smt/solver/model-finder.ts +0 -1
  319. package/src/prover/smt/solver/model-generator.ts +59 -30
  320. package/src/prover/smt/solver/model-macro-solver.ts +38 -27
  321. package/src/prover/smt/solver/model-printer.ts +214 -0
  322. package/src/prover/smt/solver/mpf.ts +709 -0
  323. package/src/prover/smt/solver/mus.ts +50 -0
  324. package/src/prover/smt/solver/muz/dl-context.ts +410 -0
  325. package/src/prover/smt/solver/muz/dl-mk-bit-blast.ts +97 -0
  326. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +167 -0
  327. package/src/prover/smt/solver/muz/dl-mk-elim-term-ite.ts +125 -0
  328. package/src/prover/smt/solver/muz/dl-mk-interp-tail-simplifier.ts +299 -0
  329. package/src/prover/smt/solver/muz/dl-mk-rule-inliner.ts +455 -0
  330. package/src/prover/smt/solver/muz/dl-mk-slice.ts +340 -0
  331. package/src/prover/smt/solver/muz/dl-mk-subsumption-checker.ts +163 -0
  332. package/src/prover/smt/solver/muz/dl-rule-set.ts +273 -0
  333. package/src/prover/smt/solver/muz/dl-rule-transformer.ts +123 -0
  334. package/src/prover/smt/solver/muz/dl-rule.ts +496 -0
  335. package/src/prover/smt/solver/muz/hnf.ts +201 -0
  336. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +176 -0
  337. package/src/prover/smt/solver/muz/horn-tactic.ts +201 -0
  338. package/src/prover/smt/solver/muz/rule-properties.ts +337 -0
  339. package/src/prover/smt/solver/muz/spacer-context.ts +1404 -0
  340. package/src/prover/smt/solver/muz/spacer-dl-interface.ts +52 -0
  341. package/src/prover/smt/solver/muz/spacer-generalizers.ts +241 -0
  342. package/src/prover/smt/solver/muz/spacer-manager.ts +127 -0
  343. package/src/prover/smt/solver/muz/spacer-pdr.ts +219 -0
  344. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +333 -0
  345. package/src/prover/smt/solver/muz/spacer-util.ts +282 -0
  346. package/src/prover/smt/solver/muz/substitution.ts +203 -0
  347. package/src/prover/smt/solver/nla2bv-tactic.ts +285 -0
  348. package/src/prover/smt/solver/nlqsat.ts +484 -0
  349. package/src/prover/smt/solver/nlsat/algebraic.ts +305 -88
  350. package/src/prover/smt/solver/nlsat/atoms.ts +52 -35
  351. package/src/prover/smt/solver/nlsat/evaluator.ts +0 -1
  352. package/src/prover/smt/solver/nlsat/explain.ts +424 -211
  353. package/src/prover/smt/solver/nlsat/interval-set.ts +1 -2
  354. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -241
  355. package/src/prover/smt/solver/nlsat/mpbq.ts +45 -1
  356. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -683
  357. package/src/prover/smt/solver/nlsat/solver.ts +282 -69
  358. package/src/prover/smt/solver/nlsat/transcendental-eval.ts +310 -0
  359. package/src/prover/smt/solver/nlsat/transcendentals.ts +391 -0
  360. package/src/prover/smt/solver/nlsat/types.ts +0 -2
  361. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -7
  362. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -20
  363. package/src/prover/smt/solver/nlsat-tactic.ts +82 -0
  364. package/src/prover/smt/solver/nnf.ts +105 -23
  365. package/src/prover/smt/solver/normalize-bounds.ts +53 -0
  366. package/src/prover/smt/solver/occf.ts +97 -0
  367. package/src/prover/smt/solver/opt-context.ts +792 -0
  368. package/src/prover/smt/solver/opt-nlsat.ts +386 -0
  369. package/src/prover/smt/solver/opt-pareto.ts +282 -0
  370. package/src/prover/smt/solver/opt-preprocess.ts +101 -0
  371. package/src/prover/smt/solver/opt-solver.ts +311 -0
  372. package/src/prover/smt/solver/opt-value.ts +55 -0
  373. package/src/prover/smt/solver/optsmt.ts +692 -0
  374. package/src/prover/smt/solver/parallel-tactic.ts +299 -0
  375. package/src/prover/smt/solver/pattern-inference.ts +19 -11
  376. package/src/prover/smt/solver/pb-rewriter.ts +281 -0
  377. package/src/prover/smt/solver/pb2bv-tactic.ts +540 -0
  378. package/src/prover/smt/solver/poly-rewriter.ts +202 -57
  379. package/src/prover/smt/solver/probes.ts +511 -0
  380. package/src/prover/smt/solver/propagate-values.ts +37 -21
  381. package/src/prover/smt/solver/proto-model.ts +650 -17
  382. package/src/prover/smt/solver/pull-quant.ts +28 -12
  383. package/src/prover/smt/solver/purify-arith.ts +632 -0
  384. package/src/prover/smt/solver/qe-arith-plugin.ts +1096 -0
  385. package/src/prover/smt/solver/qe-lite-der.ts +2 -3
  386. package/src/prover/smt/solver/qe-lite-fm.ts +3 -4
  387. package/src/prover/smt/solver/qe-lite.ts +37 -17
  388. package/src/prover/smt/solver/qe-mbp.ts +270 -0
  389. package/src/prover/smt/solver/qe.ts +1499 -0
  390. package/src/prover/smt/solver/qel.ts +25 -0
  391. package/src/prover/smt/solver/qi-queue.ts +0 -1
  392. package/src/prover/smt/solver/qsat.ts +814 -0
  393. package/src/prover/smt/solver/quant-hoist.ts +196 -0
  394. package/src/prover/smt/solver/quant-tactics.ts +16 -56
  395. package/src/prover/smt/solver/quantifier-analyzer.ts +9 -10
  396. package/src/prover/smt/solver/quantifier-manager.ts +25 -24
  397. package/src/prover/smt/solver/quasi-macros.ts +243 -0
  398. package/src/prover/smt/solver/random-gen.ts +0 -1
  399. package/src/prover/smt/solver/rational.ts +45 -1
  400. package/src/prover/smt/solver/recfun-decl-plugin.ts +262 -0
  401. package/src/prover/smt/solver/recfun-rewriter.ts +107 -0
  402. package/src/prover/smt/solver/reduce-args.ts +225 -0
  403. package/src/prover/smt/solver/reduce-bv-size.ts +119 -0
  404. package/src/prover/smt/solver/ref-vector.ts +0 -1
  405. package/src/prover/smt/solver/relevancy.ts +1 -2
  406. package/src/prover/smt/solver/rewriter-tpl.ts +77 -10
  407. package/src/prover/smt/solver/rewriter.ts +475 -36
  408. package/src/prover/smt/solver/rlimit.ts +38 -2
  409. package/src/prover/smt/solver/sat/asymm-branch.ts +325 -0
  410. package/src/prover/smt/solver/sat/big.ts +177 -0
  411. package/src/prover/smt/solver/sat/clause-use-list.ts +71 -0
  412. package/src/prover/smt/solver/sat/clause.ts +203 -0
  413. package/src/prover/smt/solver/sat/cleaner.ts +94 -0
  414. package/src/prover/smt/solver/sat/config.ts +122 -0
  415. package/src/prover/smt/solver/sat/consequences.ts +203 -0
  416. package/src/prover/smt/solver/sat/elim-eqs.ts +142 -0
  417. package/src/prover/smt/solver/sat/goal2sat.ts +526 -0
  418. package/src/prover/smt/solver/sat/inc-sat-solver.ts +378 -0
  419. package/src/prover/smt/solver/sat/model-converter.ts +136 -0
  420. package/src/prover/smt/solver/sat/pb-constraint.ts +261 -0
  421. package/src/prover/smt/solver/sat/pb-solver.ts +1577 -0
  422. package/src/prover/smt/solver/sat/probing.ts +170 -0
  423. package/src/prover/smt/solver/sat/sat-tactic.ts +44 -0
  424. package/src/prover/smt/solver/sat/sat2goal.ts +165 -0
  425. package/src/prover/smt/solver/sat/scc.ts +142 -0
  426. package/src/prover/smt/solver/sat/simplifier.ts +1618 -0
  427. package/src/prover/smt/solver/sat/solver.ts +2105 -0
  428. package/src/prover/smt/solver/sat/var-queue.ts +117 -0
  429. package/src/prover/smt/solver/sat/watch-list.ts +140 -0
  430. package/src/prover/smt/solver/search-tree.ts +284 -0
  431. package/src/prover/smt/solver/seq-axioms.ts +995 -0
  432. package/src/prover/smt/solver/seq-decl-plugin.ts +819 -0
  433. package/src/prover/smt/solver/seq-derive.ts +1298 -0
  434. package/src/prover/smt/solver/seq-eq-approx.ts +236 -0
  435. package/src/prover/smt/solver/seq-eq-solver.ts +439 -0
  436. package/src/prover/smt/solver/seq-factory.ts +89 -0
  437. package/src/prover/smt/solver/seq-monadic.ts +730 -0
  438. package/src/prover/smt/solver/seq-range-predicate.ts +235 -0
  439. package/src/prover/smt/solver/seq-re-rewriter.ts +1171 -0
  440. package/src/prover/smt/solver/seq-re-util.ts +758 -0
  441. package/src/prover/smt/solver/seq-regex-bisim.ts +144 -0
  442. package/src/prover/smt/solver/seq-regex-live.ts +200 -0
  443. package/src/prover/smt/solver/seq-rewriter.ts +2404 -0
  444. package/src/prover/smt/solver/seq-skolem.ts +294 -0
  445. package/src/prover/smt/solver/seq-subset.ts +165 -0
  446. package/src/prover/smt/solver/seq-view-witness.ts +353 -0
  447. package/src/prover/smt/solver/smt-consequences.ts +297 -0
  448. package/src/prover/smt/solver/smt-kernel.ts +90 -0
  449. package/src/prover/smt/solver/smt-logics.ts +66 -0
  450. package/src/prover/smt/solver/smt-setup.ts +544 -0
  451. package/src/prover/smt/solver/smt2-printer.ts +765 -0
  452. package/src/prover/smt/solver/smtlib-parser.ts +3228 -327
  453. package/src/prover/smt/solver/smtlib-script.ts +1843 -0
  454. package/src/prover/smt/solver/solve-eqs.ts +923 -0
  455. package/src/prover/smt/solver/solver.ts +113 -22
  456. package/src/prover/smt/solver/static-features.ts +314 -0
  457. package/src/prover/smt/solver/sticky-generations.ts +0 -1
  458. package/src/prover/smt/solver/tactic.ts +2012 -0
  459. package/src/prover/smt/solver/term-enumeration.ts +205 -0
  460. package/src/prover/smt/solver/theory-array.ts +1240 -0
  461. package/src/prover/smt/solver/theory-bv.ts +1200 -0
  462. package/src/prover/smt/solver/theory-char.ts +355 -0
  463. package/src/prover/smt/solver/theory-datatype.ts +598 -0
  464. package/src/prover/smt/solver/theory-finite-set.ts +30 -0
  465. package/src/prover/smt/solver/theory-fpa.ts +389 -0
  466. package/src/prover/smt/solver/theory-lra-axioms.ts +53 -2
  467. package/src/prover/smt/solver/theory-lra-bounds.ts +31 -5
  468. package/src/prover/smt/solver/theory-lra-final-check.ts +56 -71
  469. package/src/prover/smt/solver/theory-lra-internalize.ts +89 -11
  470. package/src/prover/smt/solver/theory-lra-model.ts +20 -35
  471. package/src/prover/smt/solver/theory-lra-propagate.ts +24 -28
  472. package/src/prover/smt/solver/theory-lra-state.ts +6 -22
  473. package/src/prover/smt/solver/theory-lra.ts +188 -2
  474. package/src/prover/smt/solver/theory-pb.ts +933 -0
  475. package/src/prover/smt/solver/theory-polymorphism.ts +58 -0
  476. package/src/prover/smt/solver/theory-recfun.ts +307 -0
  477. package/src/prover/smt/solver/theory-seq-regex.ts +867 -0
  478. package/src/prover/smt/solver/theory-seq-solve.ts +1373 -0
  479. package/src/prover/smt/solver/theory-seq-state.ts +852 -0
  480. package/src/prover/smt/solver/theory-seq.ts +961 -0
  481. package/src/prover/smt/solver/theory.ts +189 -0
  482. package/src/prover/smt/solver/tseitin-cnf.ts +485 -0
  483. package/src/prover/smt/solver/var-subst.ts +36 -14
  484. package/src/prover/smt/table.ts +3 -2
  485. package/src/prover/smt/types.ts +146 -0
  486. package/src/prover/tlapm/cache.ts +37 -16
  487. package/src/prover/tlapm-library.ts +3208 -0
  488. package/src/prover/verdict.ts +2 -0
  489. package/src/prover/zenon/decide.ts +10 -7
  490. package/src/prover/zenon/encode.ts +0 -2
  491. package/src/prover/zenon/eqrel.ts +0 -2
  492. package/src/prover/zenon/equality-rules.ts +24 -2
  493. package/src/prover/zenon/expr.ts +21 -2
  494. package/src/prover/zenon/index-table.ts +7 -4
  495. package/src/prover/zenon/isar-case.ts +1 -3
  496. package/src/prover/zenon/isar.ts +2 -4
  497. package/src/prover/zenon/llproof.ts +0 -2
  498. package/src/prover/zenon/mltoll.ts +0 -2
  499. package/src/prover/zenon/node.ts +20 -5
  500. package/src/prover/zenon/parse.ts +6 -2
  501. package/src/prover/zenon/phrase.ts +1 -3
  502. package/src/prover/zenon/proof.ts +0 -2
  503. package/src/prover/zenon/propositional-rules.ts +0 -2
  504. package/src/prover/zenon/rules.ts +2 -3
  505. package/src/prover/zenon/search.ts +7 -5
  506. package/src/prover/zenon/tla/functions.ts +0 -2
  507. package/src/prover/zenon/tla/llproof.ts +0 -2
  508. package/src/prover/zenon/tla/records.ts +0 -2
  509. package/src/prover/zenon/tla/rewrites.ts +0 -2
  510. package/src/prover/zenon/tla/sets.ts +7 -8
  511. package/src/prover/zenon/tla/terms.ts +0 -2
  512. package/src/prover/zenon/tla/tla.ts +0 -2
  513. package/src/resolve.ts +625 -189
  514. package/src/runtime.ts +7 -1
  515. package/src/sany/builtins.ts +10 -10
  516. package/src/sany/generation.ts +2 -13
  517. package/src/sany/generator-definitions.ts +3 -1
  518. package/src/sany/generator-expressions.ts +36 -30
  519. package/src/sany/generator-proofs.ts +5 -3
  520. package/src/sany/generator.ts +2 -1
  521. package/src/sany/levels.ts +0 -2
  522. package/src/sany/lexer.ts +3 -3
  523. package/src/sany/linter.ts +0 -2
  524. package/src/sany/modules.ts +4 -2
  525. package/src/sany/nodes.ts +1 -1
  526. package/src/sany/selectors.ts +11 -6
  527. package/src/sany/xml.ts +2 -3
  528. package/src/search.ts +209 -56
  529. package/src/simulate.ts +3 -0
  530. package/src/spec-description.ts +2 -2
  531. package/src/standard-definitions.ts +4 -0
  532. package/src/state-graph.ts +0 -2
  533. package/src/subexpressions.ts +265 -94
  534. package/src/successors.ts +2 -1
  535. package/src/symmetry.ts +3 -3
  536. package/src/tableau.ts +2 -2
  537. package/src/tlc/fingerprint.ts +81 -9
  538. package/src/tlc/jar-data.ts +10 -0
  539. package/src/tlc/messages.ts +3 -3
  540. package/src/tlc/order.ts +14 -3
  541. package/src/tlc/summary.ts +29 -14
  542. package/src/tlc/tlc-operators.ts +3 -1
  543. package/src/tlc/tlcext-operators.ts +61 -16
  544. package/src/tlc/trace-spec.ts +5 -5
  545. package/src/typed-tier.ts +6541 -0
  546. package/src/typescript/types.ts +2 -2
  547. package/src/values.ts +46 -27
  548. package/src/prover/isabelle/isar/statement.ts +0 -52
  549. package/src/prover/smt/solver/z3-license.txt +0 -10
  550. package/src/prover/tlaps-module.ts +0 -510
  551. package/src/prover/zenon/LICENSE +0 -32
@@ -1,16 +1,27 @@
1
- // Ported from Z3 (src/parsers/smt2/smt2parser.cpp), MIT license, see z3-license.txt.
2
- import { SmtParseError, SmtUnsupportedError } from "../../../errors";
1
+ import { SmtParseError, type SmtPosition, SmtUnsupportedError } from "../../../errors";
3
2
  import {
4
3
  type AstManager,
4
+ getSymbolHash,
5
5
  FAMILY_ARITH,
6
6
  FAMILY_BASIC,
7
+ KIND_APP,
7
8
  KIND_QUANTIFIER,
8
9
  KIND_VAR,
9
10
  OP_ABS,
10
11
  OP_ADD,
11
12
  OP_AND,
13
+ OP_AT_LEAST_K,
14
+ OP_AT_MOST_K,
15
+ OP_PB_EQ,
16
+ OP_PB_GE,
17
+ OP_PB_LE,
18
+ OP_ARRAY_DEFAULT,
19
+ OP_ARRAY_MAP,
20
+ OP_CONST_ARRAY,
12
21
  OP_DISTINCT,
13
22
  OP_DIV,
23
+ OP_DT_ACCESSOR,
24
+ OP_DT_CONSTRUCTOR,
14
25
  OP_EQ,
15
26
  OP_GE,
16
27
  OP_GT,
@@ -21,9 +32,30 @@ import {
21
32
  OP_LE,
22
33
  OP_LT,
23
34
  OP_MOD,
35
+ OP_REM,
24
36
  OP_MUL,
25
37
  OP_NOT,
26
38
  OP_OR,
39
+ OP_PATTERN,
40
+ OP_POWER,
41
+ OP_POWER0,
42
+ OP_SIN,
43
+ OP_COS,
44
+ OP_TAN,
45
+ OP_ASIN,
46
+ OP_ACOS,
47
+ OP_ATAN,
48
+ OP_SINH,
49
+ OP_COSH,
50
+ OP_TANH,
51
+ OP_ASINH,
52
+ OP_ACOSH,
53
+ OP_ATANH,
54
+ OP_EXP,
55
+ OP_ATAN2,
56
+ OP_LOG,
57
+ OP_SELECT,
58
+ OP_STORE,
27
59
  OP_SUB,
28
60
  OP_TO_INT,
29
61
  OP_TO_REAL,
@@ -35,243 +67,1414 @@ import {
35
67
  SORT_INT,
36
68
  SORT_REAL,
37
69
  isArithSort,
70
+ QUANTIFIER_EXISTS,
71
+ QUANTIFIER_FORALL,
72
+ QUANTIFIER_LAMBDA,
38
73
  } from "./ast";
74
+ import { getArraySignature, getMapSignature, mkAsArray } from "./array-decl-plugin";
75
+ import { BV_OP_NAMES, getBvSignature, getMismatchedArgument } from "./bv-decl-plugin";
76
+ import {
77
+ type ConstructorDef,
78
+ type DatatypeDef,
79
+ getConstructorAccessors,
80
+ getConstructorIs,
81
+ getConstructorRecognizer,
82
+ getDatatypeConstructors,
83
+ getDatatypeDef,
84
+ instantiateAccessor,
85
+ instantiateConstructor,
86
+ mkDatatypeDef,
87
+ mkDatatypeSort,
88
+ mkDatatypes,
89
+ mkUpdateField,
90
+ removeDatatype,
91
+ substituteSort,
92
+ } from "./datatype-decl-plugin";
93
+ import {
94
+ FPA_OP_NAMES,
95
+ FPA_SORT_NAMES,
96
+ getFloatSortError,
97
+ getFpaSignature,
98
+ mkFpaAppOf,
99
+ } from "./fpa-decl-plugin";
100
+ import { createLogicChecker } from "./check-logic";
101
+ import { shrink } from "./array";
102
+ import { ObjMap } from "./hashtable";
103
+ import {
104
+ CHAR_OP_NAMES,
105
+ getSeqSignature,
106
+ mkSeqAppOf,
107
+ parseZstring,
108
+ SEQ_OP_NAMES,
109
+ SEQ_SORT_NAMES,
110
+ } from "./seq-decl-plugin";
39
111
  import { Rational } from "./rational";
40
- import { replaceFreeVars } from "./var-subst";
112
+ import {
113
+ logicHasArith,
114
+ logicHasArray,
115
+ logicHasBv,
116
+ logicHasFpa,
117
+ logicHasRealsOnly,
118
+ logicHasSeq,
119
+ isSupportedLogic,
120
+ } from "./smt-logics";
121
+ import { setRecFunDefinition } from "./recfun-decl-plugin";
122
+ import { DEFAULT_PRINT_OPTIONS, printExpr } from "./smt2-printer";
123
+ import { replaceFreeVars, VarSubst } from "./var-subst";
124
+ import { UpolynomialManager } from "./nlsat/upolynomial";
125
+
126
+ export interface ParserOptions {
127
+ isIgnoringBadPatterns: boolean;
128
+ }
129
+
130
+ const DEFAULT_PARSER_OPTIONS: ParserOptions = { isIgnoringBadPatterns: true };
131
+
132
+ // Z3 counts the columns of the first line from 1 and of the others from 0.
133
+ export interface SmtToken {
134
+ kind: "(" | ")" | "symbol" | "keyword" | "string" | "numeral" | "decimal" | "bitvector";
135
+ text: string;
136
+ line: number;
137
+ column: number;
138
+ offset: number;
139
+ endOffset: number;
140
+ }
141
+
142
+ export interface SmtList {
143
+ kind: "list";
144
+ items: SExpr[];
145
+ line: number;
146
+ column: number;
147
+ offset: number;
148
+ // Z3 reports an error in making an application at its closing parenthesis.
149
+ end: SmtToken;
150
+ // The token after a root-obj or an indexed or qualified identifier, where Z3 reports an error in
151
+ // making it.
152
+ follower?: SmtToken;
153
+ // The command that a list a command reader read is part of.
154
+ root?: SmtList;
155
+ }
156
+
157
+ export type SExpr = SmtToken | SmtList;
158
+
159
+ // smt2parser's local: a term, and the number of binders around it where it was bound.
160
+ interface Local {
161
+ expr: number;
162
+ level: number;
163
+ }
164
+
165
+ interface ParsedTerm {
166
+ expr: number;
167
+ isOwned: boolean;
168
+ root: SmtList | undefined;
169
+ }
170
+
171
+ interface Macro {
172
+ domain: number[];
173
+ range: number;
174
+ body: number;
175
+ }
176
+
177
+ interface ConstantSortDecl {
178
+ kind: "sort";
179
+ sort: number;
180
+ }
181
+
182
+ interface UserSortDecl {
183
+ kind: "user";
184
+ name: string;
185
+ arity: number;
186
+ }
187
+
188
+ interface DatatypeSortDecl {
189
+ kind: "datatype";
190
+ name: string;
191
+ arity: number;
192
+ siblings: string[];
193
+ instances: Map<string, number>;
194
+ }
195
+
196
+ interface DefinedSortDecl {
197
+ kind: "definition";
198
+ parameters: string[];
199
+ body: SExpr;
200
+ }
201
+
202
+ // Z3's List datatype, which exists when no logic is set, declared here at its first use.
203
+ interface ListSortDecl {
204
+ kind: "list";
205
+ }
41
206
 
42
- type SExpr = string | SExpr[];
207
+ type SortDecl = ConstantSortDecl | UserSortDecl | DatatypeSortDecl | DefinedSortDecl | ListSortDecl;
43
208
 
44
- type Binding =
45
- | { kind: "var"; depth: number; sort: number }
46
- | { kind: "let"; depth: number; expr: number };
209
+ const NO_BINDINGS: ReadonlyMap<string, number> = new Map();
47
210
 
48
211
  interface SmtProblem {
49
212
  assertions: number[];
50
213
  hasCheckSat: boolean;
214
+ rlimit: number;
51
215
  }
52
216
 
53
- interface ApplicationFrame {
54
- name: string;
55
- list: SExpr[];
217
+ interface QualifiedHead {
218
+ head: SmtToken;
219
+ indices: number[];
220
+ build?: (args: number[]) => number;
221
+ }
222
+
223
+ interface ApplicationFrame extends QualifiedHead {
224
+ kind: "application";
225
+ list: SmtList;
226
+ isTail: boolean;
56
227
  start: number;
57
228
  next: number;
58
229
  }
59
230
 
60
- interface Operator {
61
- op: number;
62
- symbol?: string;
63
- isChainable?: boolean;
64
- arity: [min: number, max: number];
65
- domain: "join" | "branches" | "arith" | "first" | number;
66
- range: "domain" | number;
231
+ // An application whose head is a term, which selects from the array it stands for.
232
+ interface SelectionFrame {
233
+ kind: "selection";
234
+ list: SmtList;
235
+ isTail: boolean;
236
+ start: number;
237
+ next: number;
67
238
  }
68
239
 
69
- const OPERATORS: Operator[] = [
70
- { op: OP_AND, symbol: "and", arity: [0, Infinity], domain: SORT_BOOL, range: SORT_BOOL },
71
- { op: OP_OR, symbol: "or", arity: [0, Infinity], domain: SORT_BOOL, range: SORT_BOOL },
72
- { op: OP_NOT, symbol: "not", arity: [1, 1], domain: SORT_BOOL, range: SORT_BOOL },
73
- { op: OP_IMPLIES, symbol: "=>", arity: [2, 2], domain: SORT_BOOL, range: SORT_BOOL },
74
- { op: OP_XOR, symbol: "xor", arity: [2, 2], domain: SORT_BOOL, range: SORT_BOOL },
75
- { op: OP_ITE, symbol: "ite", arity: [3, 3], domain: "branches", range: "domain" },
76
- { op: OP_DISTINCT, symbol: "distinct", arity: [2, Infinity], domain: "join", range: SORT_BOOL },
77
- { op: OP_ADD, symbol: "+", arity: [1, Infinity], domain: "arith", range: "domain" },
78
- { op: OP_MUL, symbol: "*", arity: [1, Infinity], domain: "arith", range: "domain" },
79
- { op: OP_DIV, symbol: "/", arity: [2, 2], domain: SORT_REAL, range: SORT_REAL },
80
- { op: OP_IDIV, symbol: "div", arity: [2, 2], domain: SORT_INT, range: SORT_INT },
81
- { op: OP_MOD, symbol: "mod", arity: [2, 2], domain: SORT_INT, range: SORT_INT },
82
- { op: OP_ABS, symbol: "abs", arity: [1, 1], domain: "first", range: "domain" },
83
- { op: OP_TO_REAL, symbol: "to_real", arity: [1, 1], domain: "first", range: SORT_REAL },
84
- { op: OP_TO_INT, symbol: "to_int", arity: [1, 1], domain: "first", range: SORT_INT },
85
- { op: OP_IS_INT, symbol: "is_int", arity: [1, 1], domain: SORT_REAL, range: SORT_BOOL },
86
- {
87
- op: OP_EQ,
88
- symbol: "=",
89
- isChainable: true,
90
- arity: [2, Infinity],
91
- domain: "join",
92
- range: SORT_BOOL,
93
- },
94
- { op: OP_LE, symbol: "<=", isChainable: true, arity: [2, 2], domain: "arith", range: SORT_BOOL },
95
- { op: OP_GE, symbol: ">=", isChainable: true, arity: [2, 2], domain: "arith", range: SORT_BOOL },
96
- { op: OP_LT, symbol: "<", isChainable: true, arity: [2, 2], domain: "arith", range: SORT_BOOL },
97
- { op: OP_GT, symbol: ">", isChainable: true, arity: [2, 2], domain: "arith", range: SORT_BOOL },
98
- { op: OP_SUB, arity: [1, Infinity], domain: "arith", range: "domain" },
99
- { op: OP_UMINUS, arity: [1, 1], domain: "arith", range: "domain" },
100
- ];
101
-
102
- const OPERATORS_BY_OP = new Map<number, Operator>();
103
- const OPERATORS_BY_SYMBOL = new Map<string, Operator>();
104
- for (const operator of OPERATORS) {
105
- OPERATORS_BY_OP.set(operator.op, operator);
106
- if (operator.symbol !== undefined) OPERATORS_BY_SYMBOL.set(operator.symbol, operator);
240
+ interface LetFrame {
241
+ kind: "let";
242
+ list: SmtList;
243
+ bindings: SmtList;
244
+ names: string[];
245
+ isInDecls: boolean;
246
+ isTail: boolean;
247
+ start: number;
248
+ next: number;
107
249
  }
108
250
 
109
- const DECIMAL = /^([0-9]+)\.([0-9]+)$/;
110
-
111
- const tokenize = (text: string) => {
112
- const tokens: string[] = [];
113
- let position = 0;
114
- while (position < text.length) {
115
- const char = text[position];
116
- if (char === ";") {
117
- const end = text.indexOf("\n", position);
118
- position = end === -1 ? text.length : end + 1;
119
- } else if (char === "(" || char === ")") {
120
- tokens.push(char);
121
- position++;
122
- } else if (char === " " || char === "\n" || char === "\t" || char === "\r") {
123
- position++;
124
- } else if (char === "|") {
125
- const end = text.indexOf("|", position + 1);
126
- if (end === -1) throw new SmtParseError("unterminated quoted symbol");
127
- tokens.push(text.slice(position + 1, end));
128
- position = end + 1;
129
- } else if (char === '"') {
130
- let end = position + 1;
131
- while (end < text.length && (text[end] !== '"' || text[end + 1] === '"'))
132
- end += text[end] === '"' ? 2 : 1;
133
- tokens.push(text.slice(position, end + 1));
134
- position = end + 1;
135
- } else {
136
- let end = position;
137
- while (end < text.length && !' \n\t\r();|"'.includes(text[end])) end++;
138
- tokens.push(text.slice(position, end));
139
- position = end;
251
+ interface LetDeclFrame {
252
+ kind: "let-decl";
253
+ list: SmtList;
254
+ next: number;
255
+ }
256
+
257
+ interface QuantifierFrame {
258
+ kind: "quantifier";
259
+ list: SmtList;
260
+ quantifierKind: number;
261
+ names: string[];
262
+ varSorts: number[];
263
+ weight: number;
264
+ qid: string;
265
+ skid: string | undefined;
266
+ isTail: boolean;
267
+ start: number;
268
+ patternStart: number;
269
+ noPatternStart: number;
270
+ next: number;
271
+ }
272
+
273
+ interface AttributeFrame {
274
+ kind: "attribute";
275
+ list: SmtList;
276
+ quantifier: QuantifierFrame | undefined;
277
+ lastKeyword: string;
278
+ isTail: boolean;
279
+ start: number;
280
+ next: number;
281
+ }
282
+
283
+ interface PatternFrame {
284
+ kind: "pattern";
285
+ list: SmtList;
286
+ start: number;
287
+ next: number;
288
+ }
289
+
290
+ // smt2parser.cpp's expr_frame.
291
+ type TermFrame =
292
+ | ApplicationFrame
293
+ | SelectionFrame
294
+ | LetFrame
295
+ | LetDeclFrame
296
+ | QuantifierFrame
297
+ | AttributeFrame
298
+ | PatternFrame;
299
+
300
+ const QUANTIFIER_KINDS = new Map([
301
+ ["forall", QUANTIFIER_FORALL],
302
+ ["exists", QUANTIFIER_EXISTS],
303
+ ["lambda", QUANTIFIER_LAMBDA],
304
+ ]);
305
+
306
+ const LET_MESSAGE = "invalid let declaration, symbol expected";
307
+
308
+ // The attributes that consume_attributes takes only in the body of a quantifier.
309
+ const QUANTIFIER_ATTRIBUTES = new Set([":weight", ":skolemid", ":qid", ":pattern", ":no-pattern"]);
310
+
311
+ const IS_PARAMETER_MESSAGE =
312
+ "invalid parameter to datatype function arity == 1 && num_parameters == 1 && parameters[0].is_ast() && is_func_decl(parameters[0].get_ast())";
313
+
314
+ const BUILTIN_OPS = new Map<string, number>([
315
+ ["and", OP_AND],
316
+ ["-", OP_SUB],
317
+ ["or", OP_OR],
318
+ ["not", OP_NOT],
319
+ ["=>", OP_IMPLIES],
320
+ ["xor", OP_XOR],
321
+ ["ite", OP_ITE],
322
+ ["if", OP_ITE],
323
+ ["distinct", OP_DISTINCT],
324
+ ["+", OP_ADD],
325
+ ["*", OP_MUL],
326
+ ["/", OP_DIV],
327
+ ["div", OP_IDIV],
328
+ ["mod", OP_MOD],
329
+ ["rem", OP_REM],
330
+ ["abs", OP_ABS],
331
+ ["to_real", OP_TO_REAL],
332
+ ["to_int", OP_TO_INT],
333
+ ["is_int", OP_IS_INT],
334
+ ]);
335
+
336
+ // basic_decl_plugin's aliases, which Z3 knows only when the script sets no logic.
337
+ const LOGIC_FREE_ALIASES = new Map([
338
+ ["implies", "=>"],
339
+ ["iff", "="],
340
+ ["if_then_else", "ite"],
341
+ ["&&", "and"],
342
+ ["||", "or"],
343
+ ["equals", "="],
344
+ ["equiv", "="],
345
+ ]);
346
+
347
+ // Z3 declares these only without a logic, in ALL or in QF_NTA.
348
+ const TRANSCENDENTAL_OPS = new Map([
349
+ ["^", OP_POWER],
350
+ ["^0", OP_POWER0],
351
+ ["sin", OP_SIN],
352
+ ["cos", OP_COS],
353
+ ["tan", OP_TAN],
354
+ ["asin", OP_ASIN],
355
+ ["acos", OP_ACOS],
356
+ ["atan", OP_ATAN],
357
+ ["sinh", OP_SINH],
358
+ ["cosh", OP_COSH],
359
+ ["tanh", OP_TANH],
360
+ ["asinh", OP_ASINH],
361
+ ["acosh", OP_ACOSH],
362
+ ["atanh", OP_ATANH],
363
+ ["exp", OP_EXP],
364
+ ["atan2", OP_ATAN2],
365
+ ["arctan2", OP_ATAN2],
366
+ ["log", OP_LOG],
367
+ ["ln", OP_LOG],
368
+ ]);
369
+ const TRANSCENDENTALS = new Set([
370
+ ...TRANSCENDENTAL_OPS.keys(),
371
+ "pi",
372
+ "euler",
373
+ "/0",
374
+ "div0",
375
+ "mod0",
376
+ "complex.make",
377
+ "complex.real",
378
+ "complex.imag",
379
+ ]);
380
+
381
+ const hasTranscendentals = (logic: string | undefined) =>
382
+ logic === undefined || logic === "ALL" || logic === "QF_NTA";
383
+
384
+ const THEORY_SORTS = new Set([
385
+ "BitVec",
386
+ "Array",
387
+ "Set",
388
+ "Seq",
389
+ "String",
390
+ "StringSequence",
391
+ "RegEx",
392
+ "RegLan",
393
+ "Unicode",
394
+ "FloatingPoint",
395
+ "RoundingMode",
396
+ "Float16",
397
+ "Float32",
398
+ "Float64",
399
+ "Float128",
400
+ "FiniteSet",
401
+ "FiniteField",
402
+ "Complex",
403
+ ]);
404
+ const PB_OP_NAMES = new Map([
405
+ ["at-most", OP_AT_MOST_K],
406
+ ["at-least", OP_AT_LEAST_K],
407
+ ["pble", OP_PB_LE],
408
+ ["pbge", OP_PB_GE],
409
+ ["pbeq", OP_PB_EQ],
410
+ ]);
411
+ const THEORY_OPERATOR = /^(bv|fp\.|str\.|seq\.|re\.|char\.|ff\.)/;
412
+ const THEORY_OPERATORS = new Set([
413
+ "bit0",
414
+ "bit1",
415
+ "concat",
416
+ "sign_extend",
417
+ "zero_extend",
418
+ "extract",
419
+ "repeat",
420
+ "rotate_left",
421
+ "rotate_right",
422
+ "ext_rotate_left",
423
+ "ext_rotate_right",
424
+ "bit2bool",
425
+ "ubv_to_int",
426
+ "sbv_to_int",
427
+ "int_to_bv",
428
+ "int2bv",
429
+ "mkbv",
430
+ "store",
431
+ "select",
432
+ "const",
433
+ "map",
434
+ "default",
435
+ "union",
436
+ "intersection",
437
+ "setminus",
438
+ "complement",
439
+ "subset",
440
+ "as-array",
441
+ "choice",
442
+ "array-ext",
443
+ "set-has-size",
444
+ "card",
445
+ "is",
446
+ "update-field",
447
+ "int.to.str",
448
+ "char",
449
+ "fp",
450
+ "to_fp",
451
+ "to_fp_unsigned",
452
+ "to_ieee_bv",
453
+ "+oo",
454
+ "-oo",
455
+ "+zero",
456
+ "-zero",
457
+ "NaN",
458
+ "roundNearestTiesToEven",
459
+ "roundNearestTiesToAway",
460
+ "roundTowardPositive",
461
+ "roundTowardNegative",
462
+ "roundTowardZero",
463
+ "RNE",
464
+ "RNA",
465
+ "RTP",
466
+ "RTN",
467
+ "RTZ",
468
+ "at-most",
469
+ "at-least",
470
+ "pble",
471
+ "pbge",
472
+ "pbeq",
473
+ "linear-order",
474
+ "partial-order",
475
+ "piecewise-linear-order",
476
+ "tree-order",
477
+ "transitive-closure",
478
+ ]);
479
+
480
+ // func_decl_info of the builtin declarations: associative to both sides, flat, and associative to
481
+ // the left only. => alone is associative to the right only.
482
+ const ASSOCIATIVE_OPS = new Set([OP_AND, OP_OR, OP_XOR, OP_ADD, OP_MUL]);
483
+ const FLAT_OPS = new Set([OP_AND, OP_OR, OP_ADD, OP_MUL]);
484
+ const LEFT_ASSOCIATIVE_OPS = new Set([OP_SUB, OP_DIV, OP_IDIV]);
485
+
486
+ // arith_decl_plugin's use_coercion.
487
+ const COERCING_OPS = new Set([
488
+ OP_ADD,
489
+ OP_SUB,
490
+ OP_UMINUS,
491
+ OP_MUL,
492
+ OP_POWER,
493
+ OP_LE,
494
+ OP_GE,
495
+ OP_LT,
496
+ OP_GT,
497
+ ]);
498
+
499
+ const REAL_FUNCTION_OPS = new Set([
500
+ OP_SIN,
501
+ OP_COS,
502
+ OP_TAN,
503
+ OP_ASIN,
504
+ OP_ACOS,
505
+ OP_ATAN,
506
+ OP_SINH,
507
+ OP_COSH,
508
+ OP_TANH,
509
+ OP_ASINH,
510
+ OP_ACOSH,
511
+ OP_ATANH,
512
+ OP_EXP,
513
+ OP_ATAN2,
514
+ OP_LOG,
515
+ ]);
516
+
517
+ // The arity of each builtin declaration but distinct, which takes the arguments it is given.
518
+ const ARITIES = new Map<number, number>([
519
+ [OP_ITE, 3],
520
+ ...[OP_NOT, OP_UMINUS, OP_ABS, OP_TO_REAL, OP_TO_INT, OP_IS_INT, ...REAL_FUNCTION_OPS]
521
+ .filter((op) => op !== OP_ATAN2)
522
+ .map((op): [number, number] => [op, 1]),
523
+ ]);
524
+
525
+ const RANGES = new Map<number, number>([
526
+ [OP_TO_REAL, SORT_REAL],
527
+ [OP_POWER, SORT_REAL],
528
+ [OP_POWER0, SORT_REAL],
529
+ ...[...REAL_FUNCTION_OPS].map((op): [number, number] => [op, SORT_REAL]),
530
+ [OP_DIV, SORT_REAL],
531
+ [OP_TO_INT, SORT_INT],
532
+ [OP_IDIV, SORT_INT],
533
+ [OP_MOD, SORT_INT],
534
+ [OP_REM, SORT_INT],
535
+ ...[
536
+ OP_EQ,
537
+ OP_DISTINCT,
538
+ OP_AND,
539
+ OP_OR,
540
+ OP_XOR,
541
+ OP_NOT,
542
+ OP_IMPLIES,
543
+ OP_LE,
544
+ OP_GE,
545
+ OP_LT,
546
+ OP_GT,
547
+ ].map((op): [number, number] => [op, SORT_BOOL]),
548
+ [OP_IS_INT, SORT_BOOL],
549
+ ]);
550
+
551
+ const CHAINABLE_OPS = new Map<string, number>([
552
+ ["=", OP_EQ],
553
+ ["<=", OP_LE],
554
+ [">=", OP_GE],
555
+ ["<", OP_LT],
556
+ [">", OP_GT],
557
+ ]);
558
+ const CHAINABLE_DECLS = new Set(CHAINABLE_OPS.values());
559
+
560
+ const BV_EXTENSION_NAMES = new Set([
561
+ "bvumul_noovfl",
562
+ "bvsmul_noovfl",
563
+ "bvsmul_noudfl",
564
+ "bvsdiv0",
565
+ "bvudiv0",
566
+ "bvsrem0",
567
+ "bvurem0",
568
+ "bvsmod0",
569
+ "ext_rotate_left",
570
+ "ext_rotate_right",
571
+ "int2bv",
572
+ "bv2int",
573
+ "bv2nat",
574
+ "mkbv",
575
+ ]);
576
+
577
+ const BV_EXTENSION_LOGICS = new Set(["ALL", "QF_FD", "HORN"]);
578
+
579
+ const ARRAY_SORT_NAMES = new Set(["Array", "=>", "->"]);
580
+
581
+ // array_decl_plugin::get_op_names: select and store in every logic with arrays, the others only
582
+ // without a logic or in HORN and ALL.
583
+ const ARRAY_OPS = new Map([
584
+ ["select", OP_SELECT],
585
+ ["store", OP_STORE],
586
+ ]);
587
+ const ARRAY_EXTENSION_OPS = new Map([["default", OP_ARRAY_DEFAULT]]);
588
+
589
+ const isPortedTheoryOperator = (name: string) =>
590
+ BV_OP_NAMES.has(name) ||
591
+ FPA_OP_NAMES.has(name) ||
592
+ SEQ_OP_NAMES.has(name) ||
593
+ CHAR_OP_NAMES.has(name) ||
594
+ ARRAY_OPS.has(name) ||
595
+ ARRAY_EXTENSION_OPS.has(name);
596
+
597
+ const UNARY_BOOL_REFS = new Map([["not", OP_NOT]]);
598
+ const BINARY_BOOL_REFS = new Map([
599
+ ["and", OP_AND],
600
+ ["or", OP_OR],
601
+ ["=>", OP_IMPLIES],
602
+ ["xor", OP_XOR],
603
+ ]);
604
+
605
+ const REAL_RANGE_OPS = new Set([OP_DIV, OP_TO_REAL]);
606
+ const INT_RANGE_OPS = new Set([OP_IDIV, OP_MOD, OP_REM, OP_TO_INT]);
607
+ const DOMAIN_RANGE_OPS = new Set([OP_ADD, OP_SUB, OP_MUL, OP_ABS]);
608
+
609
+ // mk_func_decl of a builtin ignores the range of the reference and gives its own.
610
+ const getBuiltinRange = (op: number, domain: number[]) =>
611
+ op === OP_ITE
612
+ ? domain[1]
613
+ : REAL_RANGE_OPS.has(op)
614
+ ? SORT_REAL
615
+ : INT_RANGE_OPS.has(op)
616
+ ? SORT_INT
617
+ : DOMAIN_RANGE_OPS.has(op)
618
+ ? domain[0]
619
+ : SORT_BOOL;
620
+
621
+ interface MappedDecl {
622
+ decl: number;
623
+ domain: readonly number[];
624
+ range: number;
625
+ }
626
+ const ARRAY_EXTENSION_LOGICS = new Set(["HORN", "ALL"]);
627
+
628
+ // arith_decl_plugin::get_sort_names gives these logics no Int.
629
+ const INT_FREE_LOGICS = new Set(["NRA", "QF_NRA", "QF_NTA", "QF_UFNRA"]);
630
+
631
+ const BUILTIN_NAMES = new Set([
632
+ "true",
633
+ "false",
634
+ "~",
635
+ ...BV_OP_NAMES.keys(),
636
+ ...CHAINABLE_OPS.keys(),
637
+ ...BUILTIN_OPS.keys(),
638
+ ...LOGIC_FREE_ALIASES.keys(),
639
+ ...TRANSCENDENTALS,
640
+ ...THEORY_OPERATORS,
641
+ ...SEQ_OP_NAMES.keys(),
642
+ ...CHAR_OP_NAMES.keys(),
643
+ ]);
644
+
645
+ const FOLLOWED_HEADS = new Set(["root-obj", "_", "as"]);
646
+
647
+ const FF_LITERAL = /^#f-?[0-9]+m[0-9]+$/;
648
+ const FF_LOGICS = new Set(["QF_FF", "QF_FFA", "ALL", "HO_ALL"]);
649
+
650
+ // rational::is_unsigned of a numeral token.
651
+ export const isUnsigned = (numeral: string) =>
652
+ BigInt(numeral) >= 0n && BigInt(numeral) <= 0xffffffffn;
653
+
654
+ const SYMBOL_CHARACTER = /[A-Za-z0-9~!@$%^&*_\-+=<>.?/,]/;
655
+
656
+ const createScanner = (text: string) => {
657
+ const state = { index: 0, line: 1, lineStart: -1 };
658
+ const getColumn = () => state.index - state.lineStart - (state.line === 1 ? 0 : 1);
659
+ const advance = () => {
660
+ if (text[state.index] === "\n") {
661
+ state.line++;
662
+ state.lineStart = state.index;
140
663
  }
141
- }
142
- return tokens;
664
+ state.index++;
665
+ };
666
+ const readWhile = (pattern: RegExp) => {
667
+ while (state.index < text.length && pattern.test(text[state.index])) advance();
668
+ };
669
+ const next = (): SmtToken | undefined => {
670
+ for (;;) {
671
+ const character = text[state.index];
672
+ if (character === undefined) return undefined;
673
+ if (character === ";") {
674
+ while (state.index < text.length && text[state.index] !== "\n") advance();
675
+ continue;
676
+ }
677
+ if (character === " " || character === "\t" || character === "\r" || character === "\n") {
678
+ advance();
679
+ continue;
680
+ }
681
+ const start = state.index;
682
+ const position = { line: state.line, column: getColumn() };
683
+ const getToken = (kind: SmtToken["kind"], tokenText = text.slice(start, state.index)) => ({
684
+ kind,
685
+ text: tokenText,
686
+ ...position,
687
+ offset: start,
688
+ endOffset: state.index,
689
+ });
690
+ if (character === "(" || character === ")") {
691
+ advance();
692
+ return getToken(character);
693
+ }
694
+ if (character === "|" || character === '"') {
695
+ advance();
696
+ for (;;) {
697
+ if (state.index >= text.length)
698
+ throw new SmtParseError(
699
+ character === "|" ? "unexpected end of quoted symbol" : "unexpected end of string",
700
+ { line: state.line, column: getColumn() },
701
+ );
702
+ const current = text[state.index];
703
+ if (character === "|" && current === "\\")
704
+ throw new SmtParseError("invalid character '\\' in quoted symbol", {
705
+ line: state.line,
706
+ column: getColumn(),
707
+ });
708
+ advance();
709
+ // Z3's scanner starts the line before it reads past a newline in a quoted symbol or a
710
+ // string, so the columns of the rest of the line count one more.
711
+ if (current === "\n") state.lineStart--;
712
+ if (current !== character) continue;
713
+ if (character !== '"' || text[state.index] !== '"') break;
714
+ advance();
715
+ }
716
+ const inner = text.slice(start + 1, state.index - 1);
717
+ return character === "|"
718
+ ? getToken("symbol", inner)
719
+ : getToken("string", inner.replaceAll('""', '"'));
720
+ }
721
+ if (/[0-9]/.test(character) || (character === "-" && /[0-9]/.test(text[start + 1] ?? ""))) {
722
+ advance();
723
+ readWhile(/[0-9]/);
724
+ if (text[state.index] !== ".") return getToken("numeral");
725
+ advance();
726
+ readWhile(/[0-9]/);
727
+ return getToken("decimal");
728
+ }
729
+ if (character === "#") {
730
+ advance();
731
+ const radix = text[state.index];
732
+ if (radix === "|") {
733
+ advance();
734
+ while (state.index < text.length) {
735
+ const current = text[state.index];
736
+ advance();
737
+ if (current !== "|" || text[state.index] !== "#") continue;
738
+ advance();
739
+ break;
740
+ }
741
+ continue;
742
+ }
743
+ if (radix === "f") {
744
+ advance();
745
+ readWhile(/[0-9m-]/);
746
+ return getToken("symbol");
747
+ }
748
+ if (radix !== "x" && radix !== "b")
749
+ throw new SmtParseError("invalid bit-vector literal, expecting 'x' or 'b'", {
750
+ line: state.line,
751
+ column: getColumn(),
752
+ });
753
+ advance();
754
+ const digitsStart = state.index;
755
+ readWhile(radix === "x" ? /[0-9a-fA-F]/ : /[01]/);
756
+ if (state.index === digitsStart)
757
+ throw new SmtParseError("invalid empty bit-vector literal", {
758
+ line: state.line,
759
+ column: getColumn(),
760
+ });
761
+ return getToken("bitvector");
762
+ }
763
+ if (character === ":" || SYMBOL_CHARACTER.test(character)) {
764
+ advance();
765
+ readWhile(SYMBOL_CHARACTER);
766
+ return getToken(character === ":" ? "keyword" : "symbol");
767
+ }
768
+ advance();
769
+ throw new SmtParseError("unexpected character", position);
770
+ }
771
+ };
772
+ return { next, getPosition: () => ({ line: state.line, column: getColumn() }) };
143
773
  };
144
774
 
145
- const readSExprs = (tokens: string[]) => {
146
- const stack: SExpr[][] = [[]];
147
- for (const token of tokens) {
148
- if (token === "(") stack.push([]);
149
- else if (token === ")") {
150
- const list = stack.pop();
151
- if (list === undefined || stack.length === 0)
152
- throw new SmtParseError("unbalanced parentheses");
153
- stack[stack.length - 1].push(list);
154
- } else stack[stack.length - 1].push(token);
775
+ export const createCommandReader = (text: string) => {
776
+ const scanner = createScanner(text);
777
+ const state: { lookahead: SmtToken | undefined; depth: number } = {
778
+ lookahead: undefined,
779
+ depth: 0,
780
+ };
781
+ const take = () => {
782
+ const token = state.lookahead ?? scanner.next();
783
+ state.lookahead = undefined;
784
+ return token;
785
+ };
786
+ const readList = (open: SmtToken): SmtList => {
787
+ const stack: SmtList[] = [];
788
+ const root: SmtList = {
789
+ kind: "list",
790
+ items: [],
791
+ line: open.line,
792
+ column: open.column,
793
+ offset: open.offset,
794
+ end: open,
795
+ };
796
+ let followed: SmtList | undefined;
797
+ for (let current = root; ;) {
798
+ const token = take();
799
+ if (token === undefined)
800
+ throw new SmtParseError("unexpected end of file", scanner.getPosition());
801
+ if (followed !== undefined) followed.follower = token;
802
+ followed = undefined;
803
+ if (token.kind === "(") {
804
+ const list: SmtList = {
805
+ kind: "list",
806
+ items: [],
807
+ line: token.line,
808
+ column: token.column,
809
+ offset: token.offset,
810
+ end: token,
811
+ root,
812
+ };
813
+ current.items.push(list);
814
+ stack.push(current);
815
+ state.depth++;
816
+ current = list;
817
+ continue;
818
+ }
819
+ if (token.kind !== ")") {
820
+ current.items.push(token);
821
+ continue;
822
+ }
823
+ current.end = token;
824
+ if (isSymbol(current.items[0]) && FOLLOWED_HEADS.has(current.items[0].text))
825
+ followed = current;
826
+ state.depth--;
827
+ const parent = stack.pop();
828
+ if (parent === undefined) return root;
829
+ current = parent;
830
+ }
831
+ };
832
+ const readOpen = () => {
833
+ const token = take();
834
+ if (token === undefined) return undefined;
835
+ if (token.kind !== "(") throw new SmtParseError("invalid command, '(' expected", token);
836
+ state.depth = 1;
837
+ return token;
838
+ };
839
+ const read = () => {
840
+ const open = readOpen();
841
+ return open === undefined ? undefined : readList(open);
842
+ };
843
+ // parse_cmd checks the head of a command before it reads the rest.
844
+ const readCommand = () => {
845
+ const open = readOpen();
846
+ if (open === undefined) return undefined;
847
+ state.lookahead = take();
848
+ if (!isSymbol(state.lookahead))
849
+ throw new SmtParseError(
850
+ "invalid command, symbol expected",
851
+ state.lookahead ?? scanner.getPosition(),
852
+ );
853
+ return readList(open);
854
+ };
855
+ const skip = (report: (error: SmtParseError) => void) => {
856
+ for (;;) {
857
+ try {
858
+ const token = take();
859
+ if (token === undefined) return;
860
+ if (token.kind === "(" && state.depth === 0) {
861
+ state.lookahead = token;
862
+ return;
863
+ }
864
+ if (token.kind === "(") state.depth++;
865
+ if (token.kind === ")") state.depth = Math.max(0, state.depth - 1);
866
+ } catch (error) {
867
+ if (!(error instanceof SmtParseError)) throw error;
868
+ report(error);
869
+ }
870
+ }
871
+ };
872
+ return { read, readCommand, skip };
873
+ };
874
+
875
+ export const isSymbol = (sexpr: SExpr | undefined, text?: string): sexpr is SmtToken =>
876
+ sexpr !== undefined && sexpr.kind === "symbol" && (text === undefined || sexpr.text === text);
877
+
878
+ // The identifier Z3's scanner read last, which check_next prints after "got".
879
+ const getLastId = (sexpr: SExpr | undefined): string | undefined => {
880
+ if (sexpr === undefined) return undefined;
881
+ if (sexpr.kind !== "list")
882
+ return sexpr.kind === "symbol" || sexpr.kind === "keyword" ? sexpr.text : undefined;
883
+ return getLastIdBefore(sexpr.items, sexpr.items.length);
884
+ };
885
+
886
+ const getLastIdBefore = (items: SExpr[], end: number): string | undefined => {
887
+ for (let index = end - 1; index >= 0; index--) {
888
+ const id = getLastId(items[index]);
889
+ if (id !== undefined) return id;
155
890
  }
156
- if (stack.length !== 1) throw new SmtParseError("unbalanced parentheses");
157
- return stack[0];
891
+ return undefined;
158
892
  };
159
893
 
160
- const expectList = (sexpr: SExpr | undefined): SExpr[] => {
161
- if (!Array.isArray(sexpr)) throw new SmtParseError("expected a list");
894
+ const isSimpleIndex = (index: SExpr) =>
895
+ index.kind === "numeral" ||
896
+ index.kind === "bitvector" ||
897
+ index.kind === "decimal" ||
898
+ index.kind === "keyword";
899
+
900
+ const expectList = (sexpr: SExpr | undefined, message: string, at: SExpr): SmtList => {
901
+ if (sexpr?.kind !== "list") throw new SmtParseError(message, sexpr ?? at);
162
902
  return sexpr;
163
903
  };
164
904
 
165
- const expectSymbol = (sexpr: SExpr | undefined): string => {
166
- if (typeof sexpr !== "string") throw new SmtParseError("expected a symbol");
905
+ const expectSymbol = (sexpr: SExpr | undefined, message: string, at: SExpr): SmtToken => {
906
+ if (!isSymbol(sexpr)) throw new SmtParseError(message, sexpr ?? at);
167
907
  return sexpr;
168
908
  };
169
909
 
170
- export const parseSmtlib = (
171
- text: string,
910
+ const expectEnd = (extra: SExpr | undefined, message: string) => {
911
+ if (extra !== undefined) throw new SmtParseError(message, extra);
912
+ };
913
+
914
+ export const createSmtlibReader = (
172
915
  manager: AstManager,
173
- assertExpr: (assertion: number) => void,
174
- ): SmtProblem => {
175
- const sorts = new Map<string, number>([
176
- ["Bool", SORT_BOOL],
177
- ["Int", SORT_INT],
178
- ["Real", SORT_REAL],
916
+ logic?: string,
917
+ options: ParserOptions = DEFAULT_PARSER_OPTIONS,
918
+ ) => {
919
+ const hasArith = logic === undefined || logicHasArith(logic);
920
+ const hasBv = logic === undefined || logicHasBv(logic);
921
+ const logicChecker = createLogicChecker(manager, logic);
922
+ const sortDecls = new Map<string, SortDecl>([
923
+ ["Bool", { kind: "sort", sort: SORT_BOOL }],
924
+ ...(hasArith && !(logic !== undefined && INT_FREE_LOGICS.has(logic))
925
+ ? [["Int", { kind: "sort", sort: SORT_INT }] as const]
926
+ : []),
927
+ ...(hasArith ? [["Real", { kind: "sort", sort: SORT_REAL }] as const] : []),
928
+ ...(logic === undefined ? [["List", { kind: "list" }] as const] : []),
179
929
  ]);
180
- const funcs = new Map<string, number>();
181
- const assertions: number[] = [];
182
- const scopes: Map<string, Binding>[] = [];
183
- let depth = 0;
930
+ const funcs = new Map<string, readonly number[]>();
931
+ const macros = new Map<string, Macro>();
932
+ const lastNamed = { name: "", expr: -1 };
933
+ const notifiedSorts = new Set<number>();
934
+ const undo: (() => void)[] = [];
935
+ const scopeStarts: number[] = [];
936
+ // smt2parser's m_env, a scoped symbol table: one map, and the trail of what each scope shadowed.
937
+ const locals = new Map<string, Local>();
938
+ const shadowedNames: string[] = [];
939
+ const shadowedLocals: (Local | undefined)[] = [];
940
+ const localScopes: number[] = [];
941
+ const binders = { depth: 0 };
942
+ // smt2parser's expr_stack, pattern_stack and nopattern_stack, which hold a reference to each term.
943
+ // -1 on the first stands for a pattern that Z3 ignores.
944
+ const exprStack: number[] = [];
945
+ const patternStack: number[] = [];
946
+ const noPatternStack: number[] = [];
947
+ // The term that parseTerm returns leaves the stack before its caller takes a reference. One that
948
+ // only the stack held keeps a reference in pending until a term of another command is parsed, and
949
+ // one that nothing held, in floating or, where its command is not known, in unrooted, gets one
950
+ // there when another term is parsed while its caller may still read it.
951
+ const parsed: ParsedTerm = { expr: -1, isOwned: false, root: undefined };
952
+ const floating: number[] = [];
953
+ const unrooted: number[] = [];
954
+ const pending: number[] = [];
955
+
956
+ const declare = <Value>(names: Map<string, Value>, name: string, value: Value) => {
957
+ const previous = names.get(name);
958
+ undo.push(() => {
959
+ if (previous === undefined) names.delete(name);
960
+ else names.set(name, previous);
961
+ });
962
+ names.set(name, value);
963
+ };
964
+
965
+ const hasArrays = logic === undefined || logicHasArray(logic);
966
+ const hasFpa = logic === undefined || logicHasFpa(logic);
967
+ const hasArrayExtensions = logic === undefined || ARRAY_EXTENSION_LOGICS.has(logic);
968
+ const hasSeq = logic === undefined || logicHasSeq(logic);
969
+ const restricted = {
970
+ isNumeralAsReal: logic !== undefined && logicHasRealsOnly(logic),
971
+ hasSetSort: hasArrayExtensions,
972
+ hasFf: logic === undefined || FF_LOGICS.has(logic),
973
+ };
974
+
975
+ const getFirstFunc = (name: string) => funcs.get(name)?.[0];
976
+
977
+ // func_decls::signatures_collide: the domain, and the range unless it is -1.
978
+ const hasSignature = (decl: number, domain: readonly number[], range: number) =>
979
+ (range === -1 || manager.funcDecls[decl].range === range) &&
980
+ manager.funcDecls[decl].domain.length === domain.length &&
981
+ manager.funcDecls[decl].domain.every((sort, index) => sort === domain[index]);
982
+
983
+ const checkDecl = (decl: number, at: SExpr) => {
984
+ const error = logicChecker.checkDecl(decl);
985
+ if (error !== undefined) throw new SmtParseError(error, at);
986
+ };
987
+
988
+ const insertFunc = (decl: number, at: SExpr) => {
989
+ checkDecl(decl, at);
990
+ const funcDecl = manager.funcDecls[decl];
991
+ const name = String(funcDecl.name);
992
+ if (macros.has(name))
993
+ throw new SmtParseError(
994
+ `invalid declaration, named expression already defined with this name ${name}`,
995
+ at,
996
+ );
997
+ const existing = funcs.get(name) ?? [];
998
+ if (existing.includes(decl))
999
+ throw new SmtParseError(
1000
+ `invalid declaration, ${funcDecl.domain.length === 0 ? "constant" : "function"} '${name}' (with the given signature) already declared`,
1001
+ at,
1002
+ );
1003
+ declare(funcs, name, [...existing, decl]);
1004
+ };
1005
+
1006
+ const insertDatatypeDecls = (sort: number, at: SExpr) => {
1007
+ for (const constructor of getDatatypeConstructors(manager, sort)) {
1008
+ insertFunc(constructor, at);
1009
+ insertFunc(getConstructorRecognizer(manager, constructor), at);
1010
+ for (const accessor of getConstructorAccessors(manager, constructor))
1011
+ insertFunc(accessor, at);
1012
+ }
1013
+ };
1014
+
1015
+ const notifyDatatype = (sort: number, at: SExpr) => {
1016
+ const parameters = manager.getSortParameters(sort);
1017
+ if (parameters.length === 0 || notifiedSorts.has(sort)) return;
1018
+ if (getDatatypeDef(manager, sort) === undefined) return;
1019
+ if (parameters.every((parameter) => manager.getTypeParameterIndex(parameter) === -1))
1020
+ insertDatatypeDecls(sort, at);
1021
+ notifiedSorts.add(sort);
1022
+ undo.push(() => notifiedSorts.delete(sort));
1023
+ };
184
1024
 
185
- const parseSort = (sexpr: SExpr) => {
186
- const sort = sorts.get(expectSymbol(sexpr));
187
- if (sort === undefined) throw new SmtParseError(`unknown sort ${String(sexpr)}`);
1025
+ const getDatatypeInstance = (decl: DatatypeSortDecl, parameters: number[], at: SExpr) => {
1026
+ const key = parameters.join(",");
1027
+ const sort = decl.instances.get(key) ?? mkDatatypeSort(manager, decl.name, parameters);
1028
+ decl.instances.set(key, sort);
1029
+ notifyDatatype(sort, at);
188
1030
  return sort;
189
1031
  };
190
1032
 
191
- const lookup = (name: string) => {
192
- for (let index = scopes.length - 1; index >= 0; index--) {
193
- const binding = scopes[index].get(name);
194
- if (binding !== undefined) return binding;
1033
+ const instantiateDatatype = (decl: DatatypeSortDecl, parameters: number[], at: SExpr) => {
1034
+ const sort = getDatatypeInstance(decl, parameters, at);
1035
+ const def = getDatatypeDef(manager, sort);
1036
+ if (def === undefined || parameters.length === 0 || decl.siblings.length === 0) return sort;
1037
+ const marked = new Set([sort]);
1038
+ for (const constructor of def.constructors)
1039
+ for (const accessor of constructor.accessors) {
1040
+ const range = accessor.range;
1041
+ if (!manager.isDatatypeSort(range) || marked.has(range)) continue;
1042
+ marked.add(range);
1043
+ const sibling = sortDecls.get(manager.sortNames[range]);
1044
+ if (sibling?.kind !== "datatype" || !decl.siblings.includes(sibling.name)) continue;
1045
+ const instance = substituteSort(manager, range, def.parameters, parameters);
1046
+ getDatatypeInstance(sibling, [...manager.getSortParameters(instance)], at);
1047
+ }
1048
+ return sort;
1049
+ };
1050
+
1051
+ const getSortDeclArity = (decl: SortDecl) =>
1052
+ decl.kind === "sort"
1053
+ ? 0
1054
+ : decl.kind === "list"
1055
+ ? 1
1056
+ : decl.kind === "definition"
1057
+ ? decl.parameters.length
1058
+ : decl.arity;
1059
+
1060
+ const instantiateSort = (decl: SortDecl, parameters: number[], at: SExpr): number => {
1061
+ if (decl.kind === "sort") return decl.sort;
1062
+ if (decl.kind === "list") {
1063
+ const element = manager.mkTypeParameter(0);
1064
+ mkDatatypes(manager, [
1065
+ mkDatatypeDef(
1066
+ manager,
1067
+ "List",
1068
+ [element],
1069
+ [
1070
+ { name: "nil", recognizer: "is-nil", accessors: [] },
1071
+ {
1072
+ name: "insert",
1073
+ recognizer: "is-insert",
1074
+ accessors: [
1075
+ { name: "head", range: element },
1076
+ { name: "tail", range: -1 },
1077
+ ],
1078
+ },
1079
+ ],
1080
+ ),
1081
+ ]);
1082
+ const list: DatatypeSortDecl = {
1083
+ kind: "datatype",
1084
+ name: "List",
1085
+ arity: 1,
1086
+ siblings: [],
1087
+ instances: new Map(),
1088
+ };
1089
+ sortDecls.set("List", list);
1090
+ return instantiateSort(list, parameters, at);
195
1091
  }
196
- return undefined;
1092
+ if (decl.kind === "user") return manager.mkUninterpretedSort(decl.name, parameters);
1093
+ if (decl.kind === "datatype") return instantiateDatatype(decl, parameters, at);
1094
+ return parseSort(
1095
+ decl.body,
1096
+ "",
1097
+ new Map(decl.parameters.map((name, index) => [name, parameters[index]])),
1098
+ );
197
1099
  };
198
1100
 
199
- const getJoin = (args: number[]) => {
200
- const argSorts = args.map((arg) => manager.sorts[arg]);
201
- if (!argSorts.every(isArithSort)) return argSorts[0];
202
- return argSorts.includes(SORT_REAL) ? SORT_REAL : SORT_INT;
1101
+ const parseParametricSort = (
1102
+ sexpr: SmtList,
1103
+ context: string,
1104
+ bindings: ReadonlyMap<string, number>,
1105
+ ): number => {
1106
+ const head = sexpr.items[0];
1107
+ if (!isSymbol(head))
1108
+ throw new SmtParseError(
1109
+ `${context === "" ? "" : `${context} `}invalid sort, symbol or '_' expected`,
1110
+ head ?? sexpr.end,
1111
+ );
1112
+ const isArray =
1113
+ ARRAY_SORT_NAMES.has(head.text) || (head.text === "Set" && restricted.hasSetSort);
1114
+ if (isArray && hasArrays) {
1115
+ const parameters = sexpr.items.slice(1).map((item) => parseSort(item, context, bindings));
1116
+ if (head.text === "Set" ? parameters.length !== 1 : parameters.length < 2)
1117
+ throw new SmtParseError(
1118
+ "invalid array sort definition, invalid number of parameters",
1119
+ sexpr.end,
1120
+ );
1121
+ return manager.mkArraySort(head.text === "Set" ? [parameters[0], SORT_BOOL] : parameters);
1122
+ }
1123
+ const decl = sortDecls.get(head.text);
1124
+ if (decl === undefined && hasSeq && (head.text === "Seq" || head.text === "RegEx")) {
1125
+ const parameters = sexpr.items.slice(1).map((item) => parseSort(item, context, bindings));
1126
+ if (parameters.length !== 1)
1127
+ throw new SmtParseError(
1128
+ head.text === "Seq"
1129
+ ? "Invalid sequence sort, expecting one parameter"
1130
+ : "Invalid regex sort, expecting one parameter",
1131
+ sexpr.end,
1132
+ );
1133
+ return head.text === "Seq"
1134
+ ? manager.mkSeqSort(parameters[0])
1135
+ : manager.mkReSort(parameters[0]);
1136
+ }
1137
+ if (decl === undefined && hasFpa && FPA_SORT_NAMES.has(head.text)) {
1138
+ const parameters = sexpr.items.slice(1).map((item) => parseSort(item, context, bindings));
1139
+ if (head.text === "FloatingPoint") return mkFloatSort([], sexpr);
1140
+ if (parameters.length > 0)
1141
+ throw new SmtUnsupportedError("parameters on a floating-point sort");
1142
+ return parseSort(head, context, bindings);
1143
+ }
1144
+ if (decl === undefined) {
1145
+ if (THEORY_SORTS.has(head.text) && !isLackingSort(head.text))
1146
+ throw new SmtUnsupportedError(`the sort ${head.text}`);
1147
+ throw new SmtParseError(`unknown sort '${head.text}'`, head);
1148
+ }
1149
+ const parameters = sexpr.items.slice(1).map((item) => parseSort(item, context, bindings));
1150
+ if (parameters.length !== getSortDeclArity(decl))
1151
+ throw new SmtParseError("invalid number of parameters to sort constructor", sexpr.end);
1152
+ return instantiateSort(decl, parameters, sexpr);
1153
+ };
1154
+
1155
+ // parse_psort: Z3 makes the leaves and the indexed sorts of a sort definition, and an application
1156
+ // of a builtin sort, which takes any number of parameters, only when the definition is used.
1157
+ const checkPsort = (sexpr: SExpr, bindings: ReadonlyMap<string, number>) => {
1158
+ const head = sexpr.kind === "list" ? sexpr.items[0] : undefined;
1159
+ if (
1160
+ head === undefined ||
1161
+ !isSymbol(head) ||
1162
+ head.text === "_" ||
1163
+ sortDecls.has(head.text) ||
1164
+ !isBuiltinParametricSort(head.text)
1165
+ ) {
1166
+ parseSort(sexpr, "", bindings);
1167
+ return;
1168
+ }
1169
+ for (const item of (sexpr as SmtList).items.slice(1)) checkPsort(item, bindings);
1170
+ };
1171
+
1172
+ // Z3 does not know the sorts of a theory that the logic lacks.
1173
+ const isLackingSort = (name: string) =>
1174
+ name === "Set"
1175
+ ? !hasArrays || !restricted.hasSetSort
1176
+ : ARRAY_SORT_NAMES.has(name)
1177
+ ? !hasArrays
1178
+ : name === "BitVec"
1179
+ ? !hasBv
1180
+ : SEQ_SORT_NAMES.has(name) || name === "Unicode"
1181
+ ? !hasSeq
1182
+ : FPA_SORT_NAMES.has(name) && !hasFpa;
1183
+
1184
+ const isBuiltinParametricSort = (name: string) =>
1185
+ (hasArrays && (ARRAY_SORT_NAMES.has(name) || (name === "Set" && restricted.hasSetSort))) ||
1186
+ (hasSeq && (name === "Seq" || name === "RegEx")) ||
1187
+ (hasFpa && FPA_SORT_NAMES.has(name));
1188
+
1189
+ const mkFloatSort = (indices: SExpr[], at: SExpr) => {
1190
+ const ebitsIndex = indices[0];
1191
+ const sbitsIndex = indices[1];
1192
+ if (indices.length !== 2 || ebitsIndex.kind !== "numeral" || sbitsIndex.kind !== "numeral")
1193
+ throw new SmtParseError(
1194
+ "expecting two integer parameters to floating point sort (ebits, sbits)",
1195
+ at.kind === "list" ? at.end : at,
1196
+ );
1197
+ const ebits = Number(ebitsIndex.text);
1198
+ const sbits = Number(sbitsIndex.text);
1199
+ const error = getFloatSortError(ebits, sbits);
1200
+ if (error !== undefined) throw new SmtParseError(error, at.kind === "list" ? at.end : at);
1201
+ return manager.mkFpSort(ebits, sbits);
1202
+ };
1203
+
1204
+ const parseSort = (
1205
+ sexpr: SExpr,
1206
+ context: string,
1207
+ bindings: ReadonlyMap<string, number> = NO_BINDINGS,
1208
+ ): number => {
1209
+ if (sexpr.kind === ")")
1210
+ throw new SmtParseError(`${context} invalid sort, unexpected ')'`, sexpr);
1211
+ if (sexpr.kind === "list") {
1212
+ if (!isSymbol(sexpr.items[0], "_")) return parseParametricSort(sexpr, context, bindings);
1213
+ // parse_indexed_sort.
1214
+ const name = sexpr.items[1];
1215
+ if (!isSymbol(name))
1216
+ throw new SmtParseError("invalid indexed sort, symbol expected", name ?? sexpr.end);
1217
+ if (hasFpa && name.text === "FloatingPoint") return mkFloatSort(sexpr.items.slice(2), sexpr);
1218
+ const indices = sexpr.items.slice(2);
1219
+ if (isLackingSort(name.text) || !(THEORY_SORTS.has(name.text) || sortDecls.has(name.text)))
1220
+ throw new SmtParseError(`unknown sort '${name.text}'`, indices[0] ?? sexpr.end);
1221
+ if (name.text !== "BitVec") throw new SmtUnsupportedError("indexed sorts");
1222
+ for (const index of indices) {
1223
+ if (index.kind !== "numeral")
1224
+ throw new SmtParseError("invalid indexed sort, integer or ')' expected", index);
1225
+ if (!isUnsigned(index.text))
1226
+ throw new SmtParseError(
1227
+ "invalid indexed identifier, index is too big to fit in an unsigned machine integer",
1228
+ index,
1229
+ );
1230
+ }
1231
+ const width = indices[0];
1232
+ if (indices.length !== 1 || width.kind !== "numeral")
1233
+ throw new SmtParseError("expecting one integer parameter to bit-vector sort", sexpr.end);
1234
+ if (BigInt(width.text) === 0n)
1235
+ throw new SmtParseError("bit-vector size must be greater than zero", sexpr.end);
1236
+ return manager.mkBvSort(Number(width.text));
1237
+ }
1238
+ const decl = sortDecls.get(sexpr.text);
1239
+ if (decl !== undefined) {
1240
+ if (getSortDeclArity(decl) !== 0)
1241
+ throw new SmtParseError("sort constructor expects parameters", sexpr);
1242
+ return instantiateSort(decl, [], sexpr);
1243
+ }
1244
+ const bound = bindings.get(sexpr.text);
1245
+ if (bound !== undefined) return bound;
1246
+ if (hasSeq && (SEQ_SORT_NAMES.has(sexpr.text) || sexpr.text === "Unicode")) {
1247
+ if (sexpr.text === "String" || sexpr.text === "StringSequence") return manager.mkStringSort();
1248
+ if (sexpr.text === "RegLan") return manager.mkReSort(manager.mkStringSort());
1249
+ if (sexpr.text === "Unicode") return manager.mkCharSort();
1250
+ throw new SmtParseError(
1251
+ sexpr.text === "Seq"
1252
+ ? "Invalid sequence sort, expecting one parameter"
1253
+ : "Invalid regex sort, expecting one parameter",
1254
+ sexpr,
1255
+ );
1256
+ }
1257
+ if (hasFpa && FPA_SORT_NAMES.has(sexpr.text)) {
1258
+ if (sexpr.text === "RoundingMode") return manager.mkRmSort();
1259
+ const bits = FPA_SORT_NAMES.get(sexpr.text);
1260
+ return bits === undefined ? mkFloatSort([], sexpr) : manager.mkFpSort(bits[0], bits[1]);
1261
+ }
1262
+ if (THEORY_SORTS.has(sexpr.text) && !isLackingSort(sexpr.text))
1263
+ throw new SmtUnsupportedError(`the sort ${sexpr.text}`);
1264
+ throw new SmtParseError(
1265
+ `${context === "" ? "" : `${context}: `}unknown sort '${sexpr.text}'`,
1266
+ sexpr,
1267
+ );
1268
+ };
1269
+
1270
+ const beginScope = () => localScopes.push(shadowedNames.length);
1271
+
1272
+ const insertLocal = (name: string, expr: number) => {
1273
+ shadowedNames.push(name);
1274
+ shadowedLocals.push(locals.get(name));
1275
+ locals.set(name, { expr, level: binders.depth });
1276
+ };
1277
+
1278
+ const endScope = () => {
1279
+ const start = localScopes.pop() ?? 0;
1280
+ for (let index = shadowedNames.length - 1; index >= start; index--) {
1281
+ const shadowed = shadowedLocals[index];
1282
+ if (shadowed === undefined) locals.delete(shadowedNames[index]);
1283
+ else locals.set(shadowedNames[index], shadowed);
1284
+ }
1285
+ shrink(shadowedNames, start);
1286
+ shrink(shadowedLocals, start);
1287
+ };
1288
+
1289
+ const pushRef = (stack: number[], expr: number) => {
1290
+ if (expr !== -1) manager.incRef(expr);
1291
+ stack.push(expr);
203
1292
  };
204
1293
 
205
- const getDomainSort = (operator: Operator, args: number[]) => {
206
- if (operator.domain === "branches") return getJoin(args.slice(1));
207
- if (operator.domain === "join") return getJoin(args);
208
- if (operator.domain === "arith") return getJoin(args) === SORT_REAL ? SORT_REAL : SORT_INT;
209
- return operator.domain === "first" ? manager.sorts[args[0]] : operator.domain;
1294
+ // ref_vector::shrink, which releases from the new end on.
1295
+ const shrinkRefs = (stack: number[], size: number) => {
1296
+ for (let index = size; index < stack.length; index++)
1297
+ if (stack[index] !== -1) manager.decRef(stack[index]);
1298
+ shrink(stack, size);
210
1299
  };
211
1300
 
1301
+ const releasePending = () => {
1302
+ for (const expr of pending) manager.decRef(expr);
1303
+ shrink(pending, 0);
1304
+ };
1305
+
1306
+ const protect = (exprs: number[]) => {
1307
+ for (const expr of exprs)
1308
+ if (manager.ids[expr] !== -1 && manager.getRefCount(expr) === 0) pushRef(pending, expr);
1309
+ shrink(exprs, 0);
1310
+ };
1311
+
1312
+ // push_local: var_shifter moves the free variables of a term that was bound under fewer binders.
1313
+ // Its cache holds the terms it makes, which replaceFreeVars rebuilds.
1314
+ const getLocalTerm = (local: Local) => {
1315
+ if (local.level === binders.depth) return local.expr;
1316
+ if (manager.kinds[local.expr] === KIND_VAR)
1317
+ return manager.mkVar(
1318
+ manager.values[local.expr] + binders.depth - local.level,
1319
+ manager.sorts[local.expr],
1320
+ );
1321
+ return replaceFreeVars(manager, local.expr, (variable, index, shift) =>
1322
+ manager.mkVar(index + shift + binders.depth - local.level, manager.sorts[variable]),
1323
+ );
1324
+ };
1325
+
1326
+ // basic_decl_plugin::join.
1327
+ const getJoin = (left: number, right: number, at: SExpr) => {
1328
+ if (left === right) return left;
1329
+ if (isArithSort(left) && isArithSort(right)) return left === SORT_REAL ? left : right;
1330
+ if (left === SORT_BOOL && isArithSort(right)) return right;
1331
+ if (right === SORT_BOOL && isArithSort(left)) return left;
1332
+ throw new SmtParseError(
1333
+ `Sorts ${manager.getSortName(left)} and ${manager.getSortName(right)} are incompatible`,
1334
+ at,
1335
+ );
1336
+ };
1337
+
1338
+ const getJoinOfArgs = (args: number[], at: SExpr) =>
1339
+ args.reduce((join, arg) => getJoin(join, manager.sorts[arg], at), manager.sorts[args[0]]);
1340
+
1341
+ // basic_decl_plugin::mk_func_decl and arith_decl_plugin::mk_func_decl: the sort of the arguments
1342
+ // that the declaration takes, the condition of ite aside, or -1 where the plugin makes none.
1343
+ const getDomainSort = (op: number, args: number[], at: SExpr) => {
1344
+ if (op === OP_ITE)
1345
+ return args.length === 3 ? getJoin(manager.sorts[args[1]], manager.sorts[args[2]], at) : -1;
1346
+ if (op === OP_EQ) return args.length >= 2 ? getJoinOfArgs(args, at) : -1;
1347
+ if (op === OP_DISTINCT) return args.length === 0 ? SORT_BOOL : getJoinOfArgs(args, at);
1348
+ if (manager.funcDecls[op].family === FAMILY_BASIC) return SORT_BOOL;
1349
+ if (COERCING_OPS.has(op))
1350
+ return args.some((arg) => manager.sorts[arg] === SORT_REAL) ? SORT_REAL : SORT_INT;
1351
+ if (op === OP_DIV || op === OP_IS_INT || REAL_FUNCTION_OPS.has(op)) return SORT_REAL;
1352
+ if (op === OP_IDIV || op === OP_MOD || op === OP_REM) return SORT_INT;
1353
+ return manager.sorts[args[0]] === SORT_REAL ? SORT_REAL : SORT_INT;
1354
+ };
1355
+
1356
+ // ast_manager::coerce_to.
212
1357
  const coerce = (arg: number, sort: number) => {
213
1358
  const argSort = manager.sorts[arg];
214
- if (argSort === sort || !isArithSort(argSort) || !isArithSort(sort)) return arg;
215
- return sort === SORT_REAL
216
- ? manager.mkApp(OP_TO_REAL, [arg], SORT_REAL)
217
- : manager.mkApp(OP_TO_INT, [arg], SORT_INT);
1359
+ if (argSort === sort || !isArithSort(sort)) return arg;
1360
+ if (isArithSort(argSort))
1361
+ return sort === SORT_REAL
1362
+ ? manager.mkApp(OP_TO_REAL, [arg], SORT_REAL)
1363
+ : manager.mkApp(OP_TO_INT, [arg], SORT_INT);
1364
+ if (argSort !== SORT_BOOL) return arg;
1365
+ const one = manager.mkNumeralOfSort(Rational.of(1n), sort);
1366
+ return manager.mkApp(OP_ITE, [arg, one, manager.mkNumeralOfSort(Rational.of(0n), sort)], sort);
218
1367
  };
219
1368
 
220
- const mkApp = (decl: number, inputArgs: number[], domainSort?: number) => {
221
- const funcDecl = manager.funcDecls[decl];
222
- const operator = OPERATORS_BY_OP.get(funcDecl.op);
223
- const builtinSort =
224
- operator === undefined ? -1 : (domainSort ?? getDomainSort(operator, inputArgs));
225
- const getExpected = (index: number) =>
226
- operator === undefined
227
- ? funcDecl.domain[index]
228
- : operator.op === OP_ITE && index === 0
229
- ? SORT_BOOL
230
- : builtinSort;
231
- const args = inputArgs.map((arg, index) =>
232
- getExpected(index) === undefined ? arg : coerce(arg, getExpected(index)),
1369
+ // A declaration of the script has its own domain, and a builtin one takes domainSort.
1370
+ const getArity = (decl: number, numArgs: number, domainSort: number) =>
1371
+ domainSort === -1
1372
+ ? manager.funcDecls[decl].domain.length
1373
+ : decl === OP_DISTINCT
1374
+ ? numArgs
1375
+ : (ARITIES.get(decl) ?? 2);
1376
+
1377
+ const getExpectedSort = (decl: number, index: number, domainSort: number) =>
1378
+ domainSort === -1
1379
+ ? manager.funcDecls[decl].domain[index]
1380
+ : decl === OP_ITE && index === 0
1381
+ ? SORT_BOOL
1382
+ : domainSort;
1383
+
1384
+ const formatDecl = (decl: number, numArgs: number, domainSort: number) => {
1385
+ const domain = Array.from({ length: getArity(decl, numArgs, domainSort) }, (_unused, index) =>
1386
+ manager.getSortName(getExpectedSort(decl, index, domainSort)),
233
1387
  );
234
- const isArityOk =
235
- operator === undefined
236
- ? args.length === funcDecl.domain.length
237
- : args.length >= operator.arity[0] && args.length <= operator.arity[1];
238
- const isWellSorted =
239
- isArityOk &&
240
- (funcDecl.family !== FAMILY_ARITH || isArithSort(builtinSort)) &&
241
- args.every((arg, index) => manager.sorts[arg] === getExpected(index));
242
- if (!isWellSorted) throw new SmtParseError(`ill-sorted application of ${funcDecl.name}`);
1388
+ const range =
1389
+ domainSort === -1 ? manager.funcDecls[decl].range : (RANGES.get(decl) ?? domainSort);
1390
+ return `(declare-fun ${String(manager.funcDecls[decl].name)} (${domain.join(" ")}) ${manager.getSortName(range)})`;
1391
+ };
1392
+
1393
+ // ast_manager::mk_app_core: coercion_needed, coerce_to and check_args.
1394
+ const mkAppCore = (decl: number, args: number[], at: SExpr, domainSort: number) => {
1395
+ const isAssociative = domainSort !== -1 && ASSOCIATIVE_OPS.has(decl);
1396
+ const isCoercing =
1397
+ (isAssociative || getArity(decl, args.length, domainSort) === args.length) &&
1398
+ args.some((arg, index) => {
1399
+ const expected = getExpectedSort(decl, index, domainSort);
1400
+ return isArithSort(expected) && expected !== manager.sorts[arg];
1401
+ });
1402
+ const coerced = isCoercing
1403
+ ? args.map((arg, index) => coerce(arg, getExpectedSort(decl, index, domainSort)))
1404
+ : args;
1405
+ for (let index = 0; index < coerced.length; index++) {
1406
+ const sort = manager.sorts[coerced[index]];
1407
+ if (sort !== getExpectedSort(decl, index, domainSort))
1408
+ throw new SmtParseError(
1409
+ `Sort mismatch at argument #${index + 1} for function ${formatDecl(decl, args.length, domainSort)} supplied sort is ${manager.getSortName(sort)}`,
1410
+ at,
1411
+ );
1412
+ }
1413
+ // Z3 keeps xor, / and div of fewer than two arguments until its rewriters make false or the
1414
+ // argument of them, which those of this port do not.
1415
+ if (
1416
+ coerced.length < 2 &&
1417
+ domainSort !== -1 &&
1418
+ (decl === OP_XOR || LEFT_ASSOCIATIVE_OPS.has(decl))
1419
+ )
1420
+ return coerced[0] ?? manager.falseExpr;
243
1421
  return manager.mkApp(
244
1422
  decl,
245
- args,
246
- operator === undefined
247
- ? funcDecl.range
248
- : operator.range === "domain"
249
- ? builtinSort
250
- : operator.range,
1423
+ coerced,
1424
+ domainSort === -1 ? manager.funcDecls[decl].range : (RANGES.get(decl) ?? domainSort),
251
1425
  );
252
1426
  };
253
1427
 
254
- const mkChain = (operator: Operator, args: number[]) => {
255
- const domainSort = getDomainSort(operator, args);
1428
+ // ast_manager::mk_app.
1429
+ const mkApp = (decl: number, args: number[], at: SExpr, domainSort = -1): number => {
1430
+ const isBuiltin = domainSort !== -1;
1431
+ const isAssociative = isBuiltin && ASSOCIATIVE_OPS.has(decl);
1432
+ const isLeftAssociative = isAssociative || (isBuiltin && LEFT_ASSOCIATIVE_OPS.has(decl));
1433
+ const isRightAssociative = isAssociative || (isBuiltin && decl === OP_IMPLIES);
1434
+ const isChainable = isBuiltin && CHAINABLE_DECLS.has(decl);
1435
+ if (
1436
+ getArity(decl, args.length, domainSort) !== args.length &&
1437
+ ((!isLeftAssociative && !isRightAssociative && !isChainable) ||
1438
+ (args.length < 2 && manager.funcDecls[decl].family === FAMILY_BASIC && !isAssociative))
1439
+ ) {
1440
+ const environment = { options: DEFAULT_PRINT_OPTIONS, isUsed, isClashing };
1441
+ // Z3 prints an error without the newlines that end it.
1442
+ throw new SmtParseError(
1443
+ `Wrong number of arguments (${args.length}) passed to function ${formatDecl(decl, args.length, domainSort)} ${args
1444
+ .map((arg) => `\narg: ${printExpr(manager, environment, arg)}\n`)
1445
+ .join("")}`.replace(/\n+$/, ""),
1446
+ at,
1447
+ );
1448
+ }
1449
+ if (args.length === 1 && isChainable) return manager.trueExpr;
1450
+ if (args.length <= 2 || (isBuiltin && FLAT_OPS.has(decl)))
1451
+ return mkAppCore(decl, args, at, domainSort);
1452
+ if (isRightAssociative)
1453
+ return args
1454
+ .slice(0, -2)
1455
+ .reduceRight(
1456
+ (right, left) => mkAppCore(decl, [left, right], at, domainSort),
1457
+ mkAppCore(decl, args.slice(-2), at, domainSort),
1458
+ );
1459
+ if (isLeftAssociative)
1460
+ return args
1461
+ .slice(2)
1462
+ .reduce(
1463
+ (left, right) => mkAppCore(decl, [left, right], at, domainSort),
1464
+ mkAppCore(decl, args.slice(0, 2), at, domainSort),
1465
+ );
1466
+ if (!isChainable) return mkAppCore(decl, args, at, domainSort);
256
1467
  const pairs: number[] = [];
257
- for (let index = 0; index + 1 < args.length; index++)
258
- pairs.push(mkApp(operator.op, [args[index], args[index + 1]], domainSort));
259
- return pairs.length === 1 ? pairs[0] : mkApp(OP_AND, pairs);
1468
+ for (let index = 1; index < args.length; index++)
1469
+ pairs.push(mkAppCore(decl, [args[index - 1], args[index]], at, domainSort));
1470
+ return mkApp(OP_AND, pairs, at, SORT_BOOL);
260
1471
  };
261
1472
 
262
- const expectBool = (expr: number) => {
263
- if (manager.sorts[expr] !== SORT_BOOL) throw new SmtParseError("expected a formula");
264
- return expr;
265
- };
266
-
267
- const parsePattern = (sexpr: SExpr) => {
268
- if (!Array.isArray(sexpr) || sexpr.length === 0) return undefined;
269
- const head = sexpr[0];
270
- if (Array.isArray(head)) return manager.mkPattern(sexpr.map(parseTerm));
271
- const decl = head === "true" || head === "false" ? -1 : funcs.get(head);
272
- if (decl === -1 || (decl !== undefined && manager.funcDecls[decl].domain.length === 0))
273
- return undefined;
274
- return manager.mkPattern([parseTerm(sexpr)]);
1473
+ // ast_manager::mk_pattern.
1474
+ const mkPattern = (terms: number[], at: SExpr) => {
1475
+ if (terms.some((term) => manager.kinds[term] !== KIND_APP))
1476
+ throw new SmtParseError("patterns cannot be variables or quantifiers", at);
1477
+ return manager.mkPattern(terms);
275
1478
  };
276
1479
 
277
1480
  const isValidPattern = (pattern: number, numDecls: number) => {
@@ -296,180 +1499,1878 @@ export const parseSmtlib = (
296
1499
  return manager.everyArg(pattern, isValid) && found.size === numDecls;
297
1500
  };
298
1501
 
299
- const parseQuantifier = (list: SExpr[], isForall: boolean) => {
300
- const declarations = expectList(list[1]);
301
- const scope = new Map<string, Binding>();
302
- const names = declarations.map((declaration) => expectSymbol(expectList(declaration)[0]));
303
- const varSorts = declarations.map((declaration, index) => {
304
- const sort = parseSort(expectList(declaration)[1]);
305
- scope.set(names[index], { kind: "var", depth: depth + index, sort });
306
- return sort;
307
- });
308
- scopes.push(scope);
309
- depth += varSorts.length;
310
- const boundVars = varSorts.map((sort, index) =>
311
- manager.mkVar(varSorts.length - 1 - index, sort),
312
- );
313
- for (const boundVar of boundVars) manager.incRef(boundVar);
314
- const bodySExpr = list[2];
315
- const isAnnotated = Array.isArray(bodySExpr) && bodySExpr[0] === "!";
316
- const body = expectBool(parseTerm(isAnnotated ? bodySExpr[1] : bodySExpr));
317
- const patterns: number[] = [];
318
- let weight = 1;
319
- let qid = "";
320
- if (isAnnotated)
321
- for (let index = 2; index < bodySExpr.length; index += 2) {
322
- const keyword = bodySExpr[index];
323
- const value = bodySExpr[index + 1];
324
- if (keyword === ":pattern") {
325
- const pattern = parsePattern(value);
326
- if (pattern !== undefined) {
327
- manager.incRef(pattern);
328
- patterns.push(pattern);
329
- }
330
- } else if (keyword === ":weight") weight = Number(value);
331
- else if (keyword === ":qid") qid = expectSymbol(value);
332
- }
333
- scopes.pop();
334
- depth -= varSorts.length;
335
- let numKept = 0;
336
- for (const pattern of patterns) {
337
- if (!isValidPattern(pattern, varSorts.length)) continue;
1502
+ // parse_sorted_vars: the variables are created the first declared with the largest index, and
1503
+ // the stack holds them. previousId is the identifier before the list.
1504
+ const bindSortedVars = (sexpr: SExpr | undefined, at: SExpr, previousId: string) => {
1505
+ if (sexpr?.kind !== "list")
1506
+ throw new SmtParseError(
1507
+ `invalid list of sorted variables, '(' expected got ${getLastId(sexpr) ?? previousId}`,
1508
+ sexpr ?? at,
1509
+ );
1510
+ const names: string[] = [];
1511
+ const varSorts: number[] = [];
1512
+ for (const [index, declaration] of sexpr.items.entries()) {
1513
+ if (declaration.kind !== "list")
1514
+ throw new SmtParseError(
1515
+ `invalid sorted variable, '(' expected got ${getLastId(declaration) ?? getLastIdBefore(sexpr.items, index) ?? previousId}`,
1516
+ declaration,
1517
+ );
1518
+ const name = declaration.items[0];
1519
+ if (!isSymbol(name))
1520
+ throw new SmtParseError(
1521
+ "invalid sorted variable, symbol expected",
1522
+ name ?? declaration.end,
1523
+ );
1524
+ names.push(name.text);
1525
+ varSorts.push(parseSort(declaration.items[1] ?? declaration.end, "invalid sorted variables"));
1526
+ const extra = declaration.items[2];
1527
+ if (extra !== undefined)
1528
+ throw new SmtParseError(
1529
+ `invalid sorted variable, ')' expected got ${getLastId(extra) ?? getLastId(declaration.items[1]) ?? name.text}`,
1530
+ extra,
1531
+ );
1532
+ }
1533
+ beginScope();
1534
+ binders.depth += varSorts.length;
1535
+ for (const [index, sort] of varSorts.entries()) {
1536
+ const boundVar = manager.mkVar(varSorts.length - 1 - index, sort);
1537
+ pushRef(exprStack, boundVar);
1538
+ insertLocal(names[index], boundVar);
1539
+ }
1540
+ return { names, varSorts };
1541
+ };
1542
+
1543
+ const unbindSortedVars = (count: number) => {
1544
+ endScope();
1545
+ binders.depth -= count;
1546
+ };
1547
+
1548
+ // pop_quant_frame, up to the quantifier.
1549
+ const mkParsedQuantifier = (frame: QuantifierFrame) => {
1550
+ const list = frame.list;
1551
+ const numDecls = frame.varSorts.length;
1552
+ if (exprStack.length - frame.start !== numDecls + 1)
1553
+ throw new SmtParseError(
1554
+ "invalid quantified expression, syntax error: (forall|exists ((<symbol> <sort>)*) <expr>) expected",
1555
+ list.end,
1556
+ );
1557
+ let numKept = frame.patternStart;
1558
+ for (let index = frame.patternStart; index < patternStack.length; index++) {
1559
+ const pattern = patternStack[index];
1560
+ if (!isValidPattern(pattern, numDecls)) {
1561
+ if (!options.isIgnoringBadPatterns) throw new SmtParseError("invalid pattern", list.end);
1562
+ continue;
1563
+ }
338
1564
  manager.incRef(pattern);
339
- manager.decRef(patterns[numKept]);
340
- patterns[numKept] = pattern;
1565
+ manager.decRef(patternStack[numKept]);
1566
+ patternStack[numKept] = pattern;
341
1567
  numKept++;
342
1568
  }
343
- for (const removed of patterns.splice(numKept)) manager.decRef(removed);
344
- const quantifier = manager.mkQuantifier({
345
- isForall,
346
- sorts: varSorts,
347
- names,
1569
+ shrinkRefs(patternStack, numKept);
1570
+ const body = exprStack[exprStack.length - 1];
1571
+ if (frame.quantifierKind !== QUANTIFIER_LAMBDA && manager.sorts[body] !== SORT_BOOL)
1572
+ throw new SmtParseError("quantifier body must be a Boolean expression", list.end);
1573
+ if (patternStack.length > frame.patternStart && noPatternStack.length > frame.noPatternStart)
1574
+ throw new SmtParseError("simultaneous patterns and no-patterns not supported", list.end);
1575
+ return manager.mkQuantifier({
1576
+ kind: frame.quantifierKind,
1577
+ sorts: frame.varSorts,
1578
+ names: frame.names,
348
1579
  body,
349
- patterns,
350
- weight,
351
- qid,
1580
+ patterns: patternStack.slice(frame.patternStart),
1581
+ noPatterns: noPatternStack.slice(frame.noPatternStart),
1582
+ weight: frame.weight,
1583
+ qid: frame.qid,
1584
+ ...(frame.skid === undefined ? {} : { skid: frame.skid }),
352
1585
  });
353
- for (const pattern of patterns) manager.decRef(pattern);
354
- for (const boundVar of boundVars) manager.decRef(boundVar);
355
- return quantifier;
356
1586
  };
357
1587
 
358
- const parseLet = (list: SExpr[]) => {
359
- const scope = new Map<string, Binding>();
360
- for (const binding of expectList(list[1])) {
361
- const pair = expectList(binding);
362
- const expr = parseTerm(pair[1]);
363
- scope.set(expectSymbol(pair[0]), { kind: "let", depth, expr });
1588
+ const expandMacro = (macro: Macro, args: number[]) =>
1589
+ replaceFreeVars(manager, macro.body, (_variable, index, shift) => {
1590
+ const arg = args[args.length - 1 - index];
1591
+ return shift === 0
1592
+ ? arg
1593
+ : replaceFreeVars(manager, arg, (inner, innerIndex, innerShift) =>
1594
+ manager.mkVar(innerIndex + innerShift + shift, manager.sorts[inner]),
1595
+ );
1596
+ });
1597
+
1598
+ const isBvOpName = (name: string) =>
1599
+ hasBv &&
1600
+ BV_OP_NAMES.has(name) &&
1601
+ (!BV_EXTENSION_NAMES.has(name) || logic === undefined || BV_EXTENSION_LOGICS.has(logic));
1602
+
1603
+ const mkBvApp = (name: string, args: number[], indices: number[], at: SExpr) => {
1604
+ const op = BV_OP_NAMES.get(name) ?? -1;
1605
+ const argSorts = args.map((arg) => manager.sorts[arg]);
1606
+ const signature = getBvSignature(manager, op, argSorts, indices);
1607
+ if (typeof signature === "string") throw new SmtParseError(signature, at);
1608
+ const mismatched = getMismatchedArgument(signature, argSorts);
1609
+ if (mismatched !== -1)
1610
+ throw new SmtParseError(
1611
+ `Argument ${printExpr(manager, { options: DEFAULT_PRINT_OPTIONS, isUsed, isClashing }, args[mismatched])} at position ${mismatched} has sort ${manager.getSortName(argSorts[mismatched])} it does not match declaration (declare-fun ${signature.name} (${signature.domain.map((sort) => manager.getSortName(sort)).join(" ")}) ${manager.getSortName(signature.range)})`,
1612
+ at,
1613
+ );
1614
+ const decl = manager.mkBvDecl(op, signature.name, indices, signature.domain, signature.range);
1615
+ return manager.mkApp(decl, args, signature.range);
1616
+ };
1617
+
1618
+ const isFpaOpName = (name: string) => hasFpa && FPA_OP_NAMES.has(name);
1619
+
1620
+ // pb_decl_plugin::get_op_names and mk_func_decl.
1621
+ const isPbOpName = (name: string) =>
1622
+ PB_OP_NAMES.has(name) &&
1623
+ (logic === undefined || logic === "QF_FD" || logic === "ALL" || logic === "HORN");
1624
+
1625
+ const mkPbTerm = (name: string, args: number[], parameters: Rational[], at: SExpr) => {
1626
+ const op = PB_OP_NAMES.get(name) ?? -1;
1627
+ if (args.some((arg) => manager.sorts[arg] !== SORT_BOOL))
1628
+ throw new SmtParseError("invalid non-Boolean sort applied to Pseudo-Boolean relation", at);
1629
+ const isCardinality = op === OP_AT_MOST_K || op === OP_AT_LEAST_K;
1630
+ if (isCardinality && parameters.length !== 1)
1631
+ throw new SmtParseError("function expects one non-negative integer parameter", at);
1632
+ if (!isCardinality && parameters.length !== 1 + args.length)
1633
+ throw new SmtParseError("function expects arity+1 rational parameters", at);
1634
+ const decl = manager.mkPbDecl(
1635
+ op,
1636
+ parameters,
1637
+ args.map(() => SORT_BOOL),
1638
+ );
1639
+ return manager.mkApp(decl, args, SORT_BOOL);
1640
+ };
1641
+
1642
+ const mkFpaTerm = (name: string, args: number[], indices: number[], at: SExpr) => {
1643
+ const op = FPA_OP_NAMES.get(name) ?? -1;
1644
+ const getSignature = (innerArgs: number[]) => {
1645
+ const signature = getFpaSignature(
1646
+ manager,
1647
+ op,
1648
+ indices,
1649
+ innerArgs.map((arg) => manager.sorts[arg]),
1650
+ );
1651
+ if (typeof signature === "string") throw new SmtParseError(signature, at);
1652
+ return signature;
1653
+ };
1654
+ const signature = getSignature(args);
1655
+ if (signature.domain.length === args.length) return mkFpaAppOf(manager, signature, args);
1656
+ const pairs: number[] = [];
1657
+ for (let index = 0; index + 1 < args.length; index++) {
1658
+ const pair = [args[index], args[index + 1]];
1659
+ pairs.push(mkFpaAppOf(manager, getSignature(pair), pair));
364
1660
  }
365
- scopes.push(scope);
366
- const body = parseTerm(list[2]);
367
- scopes.pop();
368
- return body;
1661
+ return mkApp(OP_AND, pairs, at, SORT_BOOL);
369
1662
  };
370
1663
 
371
- const parseApp = (name: string, args: number[]) => {
372
- if (name === "-") return mkApp(args.length === 1 ? OP_UMINUS : OP_SUB, args);
373
- if (name === "/" && args.length > 2)
374
- return args
375
- .slice(1)
376
- .reduce((dividend, divisor) => mkApp(OP_DIV, [dividend, divisor]), args[0]);
377
- const operator = OPERATORS_BY_SYMBOL.get(name);
378
- if (operator?.isChainable) return mkChain(operator, args);
379
- if (operator !== undefined) return mkApp(operator.op, args);
380
- const decl = funcs.get(name);
381
- if (decl === undefined) throw new SmtParseError(`unknown function ${name}`);
382
- return mkApp(decl, args);
383
- };
384
-
385
- const parseLeaf = (sexpr: SExpr): number => {
386
- if (typeof sexpr === "string") {
387
- if (/^[0-9]+$/.test(sexpr)) return manager.mkNumeral(BigInt(sexpr));
388
- const decimal = DECIMAL.exec(sexpr);
389
- if (decimal !== null)
390
- return manager.mkRealNumeral(
391
- Rational.of(BigInt(decimal[1] + decimal[2]), 10n ** BigInt(decimal[2].length)),
1664
+ const isSeqOpName = (name: string) =>
1665
+ hasSeq && (SEQ_OP_NAMES.has(name) || CHAR_OP_NAMES.has(name));
1666
+
1667
+ const mkSeqTerm = (
1668
+ name: string,
1669
+ args: number[],
1670
+ indices: number[],
1671
+ at: SExpr,
1672
+ range?: number,
1673
+ ) => {
1674
+ const signature = getSeqSignature(
1675
+ manager,
1676
+ SEQ_OP_NAMES.get(name) ?? CHAR_OP_NAMES.get(name) ?? -1,
1677
+ indices,
1678
+ args.map((arg) => manager.sorts[arg]),
1679
+ range,
1680
+ );
1681
+ if (typeof signature === "string") throw new SmtParseError(signature, at);
1682
+ return mkSeqAppOf(manager, signature, args);
1683
+ };
1684
+
1685
+ const upolynomials = new UpolynomialManager(manager.limit);
1686
+
1687
+ const parseUpolynomial = (sexpr: SExpr): bigint[] => {
1688
+ if (sexpr.kind === "numeral") return upolynomials.set([BigInt(sexpr.text)]);
1689
+ if (sexpr.kind === "decimal") {
1690
+ const parts = sexpr.text.split(".");
1691
+ const value = Rational.of(BigInt(parts[0] + parts[1]), 10n ** BigInt(parts[1].length));
1692
+ if (!value.isInt())
1693
+ throw new SmtParseError(
1694
+ "invalid univariate polynomial, integer coefficient expected",
1695
+ sexpr,
392
1696
  );
393
- if (sexpr === "true") return manager.trueExpr;
394
- if (sexpr === "false") return manager.falseExpr;
395
- const binding = lookup(sexpr);
396
- if (binding?.kind === "var") return manager.mkVar(depth - 1 - binding.depth, binding.sort);
397
- if (binding !== undefined)
398
- return depth === binding.depth
399
- ? binding.expr
400
- : replaceFreeVars(manager, binding.expr, (variable, index, shift) =>
401
- manager.mkVar(index + shift + depth - binding.depth, manager.sorts[variable]),
402
- );
403
- return parseApp(sexpr, []);
1697
+ return upolynomials.set([value.num]);
1698
+ }
1699
+ if (sexpr.kind === "symbol") {
1700
+ if (sexpr.text !== "x")
1701
+ throw new SmtParseError("invalid univariate polynomial, variable 'x' expected", sexpr);
1702
+ return [0n, 1n];
404
1703
  }
405
- const head = sexpr[0];
406
- if (head === "forall" || head === "exists") return parseQuantifier(sexpr, head === "forall");
407
- if (head === "let") return parseLet(sexpr);
408
- const named = parseTerm(sexpr[1]);
409
- const nameIndex = sexpr.indexOf(":named");
410
- if (nameIndex !== -1) {
411
- manager.incRef(named);
412
- manager.mkMacro(expectSymbol(sexpr[nameIndex + 1]), named);
1704
+ if (sexpr.kind !== "list")
1705
+ throw new SmtParseError("invalid univariate polynomial, unexpected ", sexpr);
1706
+ const head = sexpr.items[0];
1707
+ if (!isSymbol(head))
1708
+ throw new SmtParseError("invalid univariate polynomial, symbol expected", sexpr);
1709
+ const operands = sexpr.items.slice(1);
1710
+ if (head.text === "^") {
1711
+ if (operands.length !== 2)
1712
+ throw new SmtParseError(
1713
+ "invalid univariate polynomial, '^' operator expects two arguments",
1714
+ sexpr,
1715
+ );
1716
+ const exponent = operands[1];
1717
+ if (exponent.kind !== "numeral" || BigInt(exponent.text) > 0xffffffffn)
1718
+ throw new SmtParseError(
1719
+ "invalid univariate polynomial, exponent must be an unsigned integer",
1720
+ exponent,
1721
+ );
1722
+ return upolynomials.pw(parseUpolynomial(operands[0]), Number(exponent.text));
413
1723
  }
414
- return named;
1724
+ const combine =
1725
+ head.text === "+"
1726
+ ? upolynomials.add
1727
+ : head.text === "-"
1728
+ ? upolynomials.sub
1729
+ : head.text === "*"
1730
+ ? upolynomials.mul
1731
+ : undefined;
1732
+ if (combine === undefined)
1733
+ throw new SmtParseError(
1734
+ "invalid univariate polynomial, '+', '-', '^' or '*' expected",
1735
+ sexpr,
1736
+ );
1737
+ if (operands.length === 0)
1738
+ throw new SmtParseError(
1739
+ `invalid univariate polynomial, '${head.text}' operator expects at least one argument`,
1740
+ sexpr,
1741
+ );
1742
+ const first = parseUpolynomial(operands[0]);
1743
+ if (head.text === "-" && operands.length === 1) return upolynomials.neg(first);
1744
+ return operands
1745
+ .slice(1)
1746
+ .reduce(
1747
+ (result, operand) => combine.call(upolynomials, result, parseUpolynomial(operand)),
1748
+ first,
1749
+ );
1750
+ };
1751
+
1752
+ const parseRootObj = (list: SmtList) => {
1753
+ const polynomial = list.items[1] ?? list.end;
1754
+ const index = list.items[2] ?? list.end;
1755
+ if (index.kind !== "numeral")
1756
+ throw new SmtParseError("invalid root-obj, (unsigned) integer expected", index);
1757
+ if (BigInt(index.text) > 0xffffffffn)
1758
+ throw new SmtParseError(
1759
+ "invalid root-obj, index must fit in an unsigned machine integer",
1760
+ index,
1761
+ );
1762
+ if (BigInt(index.text) === 0n)
1763
+ throw new SmtParseError("invalid root-obj, index must be >= 1", index);
1764
+ if (list.items.length > 3)
1765
+ throw new SmtParseError("invalid root-obj, ')' expected", list.items[3]);
1766
+ const coeffs = parseUpolynomial(polynomial);
1767
+ const follower = list.follower ?? list.end;
1768
+ if (coeffs.length === 0)
1769
+ throw new SmtParseError(
1770
+ "invalid root object, polynomial must not be the zero polynomial",
1771
+ follower,
1772
+ );
1773
+ const roots = manager.am.isolateUnivariateRoots(coeffs);
1774
+ const root = roots[Number(index.text) - 1];
1775
+ if (root === undefined)
1776
+ throw new SmtParseError(
1777
+ "invalid root object, polynomial does have sufficient roots",
1778
+ follower,
1779
+ );
1780
+ return manager.mkAlgebraicNumeral(root);
415
1781
  };
416
1782
 
417
- const parseTerm = (sexpr: SExpr): number => {
418
- const frames: ApplicationFrame[] = [];
419
- const results: number[] = [];
420
- const enter = (current: SExpr) => {
421
- const head = Array.isArray(current) ? current[0] : undefined;
1783
+ const isKnownOperator = (name: string) => BUILTIN_NAMES.has(name) || THEORY_OPERATOR.test(name);
1784
+
1785
+ // parse_indexed_identifier_core.
1786
+ const getIndexedName = (list: SmtList) => {
1787
+ const name = list.items[1];
1788
+ if (!isSymbol(name))
1789
+ throw new SmtParseError("invalid indexed identifier, symbol expected", name ?? list.end);
1790
+ for (const index of list.items.slice(2)) {
1791
+ if (index.kind === "string")
1792
+ throw new SmtParseError(
1793
+ "invalid indexed identifier, integer, identifier or '(' expected",
1794
+ index,
1795
+ );
1796
+ // parse_func_decl_ref of an index that is a symbol.
422
1797
  if (
423
- !Array.isArray(current) ||
424
- head === "forall" ||
425
- head === "exists" ||
426
- head === "let" ||
427
- head === "!"
1798
+ index.kind === "symbol" &&
1799
+ name.text !== "is" &&
1800
+ !isUsed(index.text) &&
1801
+ !macros.has(index.text)
1802
+ )
1803
+ throw new SmtParseError(
1804
+ `invalid function declaration reference, unknown function ${index.text}`,
1805
+ index,
1806
+ );
1807
+ }
1808
+ return name;
1809
+ };
1810
+
1811
+ // parse_qualified_identifier_core on (as <identifier> <sort>), up to the sort.
1812
+ const parseQualifierSort = (list: SmtList) => {
1813
+ const target = list.items[1];
1814
+ if (target === undefined || (target.kind !== "symbol" && target.kind !== "list"))
1815
+ throw new SmtParseError(
1816
+ `invalid (indexed) identifier, '(_' or symbol expected got ${getLastId(target) ?? "as"}`,
1817
+ target ?? list.end,
1818
+ );
1819
+ if (target.kind === "list") {
1820
+ if (!isSymbol(target.items[0], "_"))
1821
+ throw new SmtParseError(
1822
+ "invalid indexed identifier, '_' expected",
1823
+ target.items[0] ?? target.end,
1824
+ );
1825
+ getIndexedName(target);
1826
+ }
1827
+ const sort = parseSort(list.items[2] ?? list.end, "Invalid qualified identifier");
1828
+ const extra = list.items[3];
1829
+ if (extra !== undefined)
1830
+ throw new SmtParseError(
1831
+ `invalid qualified identifier, ')' expected got ${getLastId(extra) ?? getLastIdBefore(list.items, 3) ?? "as"}`,
1832
+ extra,
1833
+ );
1834
+ return sort;
1835
+ };
1836
+
1837
+ // parse_qualified_name on (_ <symbol> <index>*). Z3 makes the term once it has read past the
1838
+ // closing parenthesis, where at is.
1839
+ const parseIndexedTerm = (list: SmtList, at: SExpr, range?: number) => {
1840
+ const name = getIndexedName(list);
1841
+ const indices = list.items.slice(2);
1842
+ const local = locals.get(name.text);
1843
+ if (local !== undefined) {
1844
+ if (indices.length > 0)
1845
+ throw new SmtParseError("invalid indexed identifier, symbol is a local declaration", at);
1846
+ return getLocalTerm(local);
1847
+ }
1848
+ const value = /^bv([0-9]+)$/.exec(name.text);
1849
+ if (value !== null) {
1850
+ const width = indices[0];
1851
+ const digits =
1852
+ indices.length !== 1
1853
+ ? "-1"
1854
+ : width.kind === "bitvector"
1855
+ ? `0${width.text.slice(1)}`
1856
+ : width.kind === "numeral"
1857
+ ? width.text
1858
+ : "-1";
1859
+ if (!isUnsigned(digits))
1860
+ throw new SmtParseError("invalid bit-vector constant, index expected", at);
1861
+ if (BigInt(digits) === 0n)
1862
+ throw new SmtParseError("bit-vector size must be greater than zero", at);
1863
+ return manager.mkBvNumeral(BigInt(value[1]), Number(BigInt(digits)));
1864
+ }
1865
+ const isNumbered = indices.every((index) => index.kind === "numeral");
1866
+ if (isNumbered && isSeqOpName(name.text))
1867
+ return mkSeqTerm(
1868
+ name.text,
1869
+ [],
1870
+ indices.map((index) => (index.kind === "list" ? 0 : Number(index.text))),
1871
+ at,
1872
+ );
1873
+ if (isNumbered && isFpaOpName(name.text)) {
1874
+ const signature = getFpaSignature(
1875
+ manager,
1876
+ FPA_OP_NAMES.get(name.text) ?? -1,
1877
+ indices.map((index) => (index.kind === "list" ? 0 : Number(index.text))),
1878
+ [],
1879
+ );
1880
+ if (typeof signature === "string") throw new SmtParseError(signature, at);
1881
+ return mkFpaAppOf(manager, signature, []);
1882
+ }
1883
+ if (isKnownOperator(name.text) || !indices.every(isSimpleIndex))
1884
+ throw new SmtUnsupportedError("indexed identifiers");
1885
+ return parseApp(name, [], at, [], range);
1886
+ };
1887
+
1888
+ // parse_qualified_name.
1889
+ const parseQualifiedName = (list: SmtList) => {
1890
+ const at = list.follower ?? list.end;
1891
+ if (isSymbol(list.items[0], "_")) return parseIndexedTerm(list, at);
1892
+ const sort = parseQualifierSort(list);
1893
+ const target = list.items[1];
1894
+ const local = isSymbol(target) ? locals.get(target.text) : undefined;
1895
+ if (isSymbol(target) && local === undefined && hasArrays && target.text === "const")
1896
+ return mkArrayTerm(OP_CONST_ARRAY, [], [sort], at);
1897
+ // A macro takes no range, so check_qualifier catches the sort of the term it stands for.
1898
+ const term =
1899
+ local !== undefined
1900
+ ? getLocalTerm(local)
1901
+ : isSymbol(target)
1902
+ ? parseApp(target, [], at, [], sort)
1903
+ : parseIndexedTerm(
1904
+ expectList(target, "invalid indexed identifier, '_' expected", list),
1905
+ at,
1906
+ sort,
1907
+ );
1908
+ if (manager.sorts[term] !== sort)
1909
+ throw new SmtParseError(
1910
+ `sort mismatch in qualified identifier, expected: ${manager.getSortName(sort)}, got: ${manager.getSortName(manager.sorts[term])}`,
1911
+ at,
1912
+ );
1913
+ return term;
1914
+ };
1915
+
1916
+ const mkArrayTerm = (op: number, inputArgs: number[], parameters: number[], at: SExpr) => {
1917
+ const signature = getArraySignature(
1918
+ manager,
1919
+ op,
1920
+ inputArgs.map((arg) => manager.sorts[arg]),
1921
+ parameters,
1922
+ );
1923
+ if (typeof signature === "string") throw new SmtParseError(signature, at);
1924
+ const args = inputArgs.map((arg, index) => coerce(arg, signature.domain[index]));
1925
+ const decl = manager.mkArrayDecl(
1926
+ op,
1927
+ signature.name,
1928
+ parameters,
1929
+ signature.domain,
1930
+ signature.range,
1931
+ );
1932
+ return manager.mkApp(decl, args, signature.range);
1933
+ };
1934
+
1935
+ const findFuncDecl = (sexpr: SmtToken) => {
1936
+ const decls = funcs.get(sexpr.text);
1937
+ if (decls !== undefined && decls.length > 1)
1938
+ throw new SmtParseError(
1939
+ `ambiguous function declaration reference, provide full signature to disambiguate (<symbol> (<sort>*) <sort>) ${sexpr.text}`,
1940
+ sexpr,
1941
+ );
1942
+ return decls?.[0];
1943
+ };
1944
+
1945
+ const throwAmbiguousConstant = (name: string, at: SExpr) => {
1946
+ throw new SmtParseError(
1947
+ `ambiguous constant reference, more than one constant with the same sort, use a qualified expression (as <symbol> <sort>) to disambiguate ${name}`,
1948
+ at,
1949
+ );
1950
+ };
1951
+
1952
+ // An exact signature wins, else the last one that matches once Int and Real coerce.
1953
+ const mkDeclaredApp = (
1954
+ name: string,
1955
+ decls: readonly number[],
1956
+ args: number[],
1957
+ range: number | undefined,
1958
+ at: SExpr,
1959
+ ) => {
1960
+ if (args.length === 0 && range === undefined) {
1961
+ if (decls.length > 1) throwAmbiguousConstant(name, at);
1962
+ return manager.funcDecls[decls[0]].domain.length > 0
1963
+ ? mkAsArray(manager, decls[0])
1964
+ : mkApp(decls[0], args, at);
1965
+ }
1966
+ const argSorts = args.map((arg) => manager.sorts[arg]);
1967
+ const candidates = decls.filter(
1968
+ (decl) =>
1969
+ (range === undefined || manager.funcDecls[decl].range === range) &&
1970
+ manager.funcDecls[decl].domain.length === args.length &&
1971
+ manager.funcDecls[decl].domain.every(
1972
+ (sort, index) =>
1973
+ sort === argSorts[index] || (isArithSort(sort) && isArithSort(argSorts[index])),
1974
+ ),
1975
+ );
1976
+ const found = candidates.find((decl) => hasSignature(decl, argSorts, -1)) ?? candidates.at(-1);
1977
+ if (found !== undefined) return mkApp(found, args, at);
1978
+ if (args.length === 0 || range !== undefined) return undefined;
1979
+ if (decls.length > 1) throwAmbiguousConstant(name, at);
1980
+ const array = manager.funcDecls[decls[0]];
1981
+ if (array.domain.length > 0 || !manager.isArraySort(array.range)) return undefined;
1982
+ const parameters = manager.getSortParameters(array.range);
1983
+ if (
1984
+ parameters.length !== args.length + 1 ||
1985
+ argSorts.some((sort, index) => sort !== parameters[index])
1986
+ )
1987
+ return undefined;
1988
+ return mkArrayTerm(OP_SELECT, [mkApp(decls[0], [], at), ...args], [], at);
1989
+ };
1990
+
1991
+ const mkDatatypeInstanceApp = (name: string, args: number[], at: SExpr) => {
1992
+ const argSorts = args.map((arg) => manager.sorts[arg]);
1993
+ for (const def of manager.datatypeDefs.values())
1994
+ for (const [index, constructor] of def.constructors.entries()) {
1995
+ if (constructor.name !== name || constructor.accessors.length !== args.length) continue;
1996
+ const binding: number[] = [];
1997
+ const isMatch = constructor.accessors.every((accessor, position) => {
1998
+ if (accessor.range === argSorts[position]) return true;
1999
+ const parameter = manager.getTypeParameterIndex(accessor.range);
2000
+ if (parameter === -1) return false;
2001
+ if (binding[parameter] !== undefined && binding[parameter] !== argSorts[position])
2002
+ return false;
2003
+ binding[parameter] = argSorts[position];
2004
+ return true;
2005
+ });
2006
+ if (
2007
+ !isMatch ||
2008
+ binding.length !== def.parameters.length ||
2009
+ !def.parameters.every((_parameter, parameter) => binding[parameter] !== undefined)
2010
+ )
2011
+ continue;
2012
+ return mkApp(instantiateConstructor(manager, def, index, binding), args, at);
2013
+ }
2014
+ if (args.length !== 1 || !manager.isDatatypeSort(argSorts[0])) return undefined;
2015
+ for (const def of manager.datatypeDefs.values())
2016
+ for (const [index, constructor] of def.constructors.entries()) {
2017
+ const position = constructor.accessors.findIndex((accessor) => accessor.name === name);
2018
+ if (position === -1) continue;
2019
+ const sort = mkDatatypeSort(manager, def.name, [...manager.getSortParameters(argSorts[0])]);
2020
+ return mkApp(instantiateAccessor(manager, sort, index, position), args, at);
2021
+ }
2022
+ return undefined;
2023
+ };
2024
+
2025
+ const mkIsApp = (constructorName: SmtToken, args: number[], at: SExpr) => {
2026
+ const declared = findFuncDecl(constructorName);
2027
+ // datatype::decl::plugin::mk_is.
2028
+ if (declared !== undefined) {
2029
+ if (args.length !== 1) throw new SmtParseError(IS_PARAMETER_MESSAGE, at);
2030
+ if (!manager.isDatatypeSort(manager.sorts[args[0]]))
2031
+ throw new SmtParseError(
2032
+ "invalid parameter to datatype function u().is_datatype(domain[0])",
2033
+ at,
2034
+ );
2035
+ if (manager.sorts[args[0]] !== manager.funcDecls[declared].range)
2036
+ throw new SmtParseError("invalid sort argument passed to recognizer", at);
2037
+ if (manager.funcDecls[declared].op !== OP_DT_CONSTRUCTOR)
2038
+ throw new SmtParseError("expecting constructor argument to recognizer", at);
2039
+ return manager.mkApp(getConstructorIs(manager, declared), args, SORT_BOOL);
2040
+ }
2041
+ const argSort = args.length === 1 ? manager.sorts[args[0]] : -1;
2042
+ if (argSort === -1 || !manager.isDatatypeSort(argSort))
2043
+ throw new SmtParseError(IS_PARAMETER_MESSAGE, at);
2044
+ const constructor = getDatatypeConstructors(manager, argSort).find(
2045
+ (decl) => manager.funcDecls[decl].name === constructorName.text,
2046
+ );
2047
+ if (constructor === undefined)
2048
+ throw new SmtParseError(
2049
+ `invalid datatype recognizer, unknown constructor ${constructorName.text}`,
2050
+ at,
2051
+ );
2052
+ return mkApp(getConstructorIs(manager, constructor), args, at);
2053
+ };
2054
+
2055
+ const mkUpdateFieldApp = (accessorName: SmtToken, args: number[], at: SExpr) => {
2056
+ const accessor = findFuncDecl(accessorName);
2057
+ if (accessor === undefined)
2058
+ throw new SmtParseError(
2059
+ `invalid function declaration reference, unknown function ${accessorName.text}`,
2060
+ accessorName,
2061
+ );
2062
+ // datatype::decl::plugin::mk_update_field.
2063
+ if (args.length !== 2)
2064
+ throw new SmtParseError("invalid number of arguments for datatype field update", at);
2065
+ const funcDecl = manager.funcDecls[accessor];
2066
+ if (funcDecl.op !== OP_DT_ACCESSOR)
2067
+ throw new SmtParseError(
2068
+ "datatype field update requires a datatype accessor as the second argument",
2069
+ at,
2070
+ );
2071
+ if (funcDecl.domain[0] !== manager.sorts[args[0]])
2072
+ throw new SmtParseError("first argument to field update should be a data-type", at);
2073
+ if (funcDecl.range !== manager.sorts[args[1]])
2074
+ throw new SmtParseError(
2075
+ `second argument to field update should be ${manager.getSortName(funcDecl.range)} instead of ${manager.getSortName(manager.sorts[args[1]])}`,
2076
+ at,
2077
+ );
2078
+ return manager.mkApp(mkUpdateField(manager, accessor), args, funcDecl.domain[0]);
2079
+ };
2080
+
2081
+ const getUnknownConstantMessage = (name: string, args: number[], range: number | undefined) => {
2082
+ const argSorts =
2083
+ args.length === 0
2084
+ ? ""
2085
+ : ` (${args.map((arg) => manager.getSortName(manager.sorts[arg])).join(" ")}) `;
2086
+ const declared = (funcs.get(name) ?? []).map((decl) => {
2087
+ const domain = manager.funcDecls[decl].domain.map((sort) => manager.getSortName(sort));
2088
+ return `\ndeclared: (declare-fun ${name} (${domain.join(" ")}) ${manager.getSortName(manager.funcDecls[decl].range)}) `;
2089
+ });
2090
+ return `unknown constant ${name}${argSorts}${range === undefined ? "" : `${manager.getSortName(range)} `}${declared.join("")}`;
2091
+ };
2092
+
2093
+ const parseFuncDeclRef = (sexpr: SExpr): MappedDecl => {
2094
+ if (sexpr.kind === "symbol") {
2095
+ const decl = findFuncDecl(sexpr);
2096
+ if (decl !== undefined) return { decl, ...manager.funcDecls[decl] };
2097
+ const unary = UNARY_BOOL_REFS.get(sexpr.text);
2098
+ if (unary !== undefined) return { decl: unary, domain: [SORT_BOOL], range: SORT_BOOL };
2099
+ const binary = BINARY_BOOL_REFS.get(sexpr.text);
2100
+ if (binary !== undefined)
2101
+ return { decl: binary, domain: [SORT_BOOL, SORT_BOOL], range: SORT_BOOL };
2102
+ throw new SmtUnsupportedError(`the declaration reference ${sexpr.text}`);
2103
+ }
2104
+ const name = sexpr.kind === "list" ? sexpr.items[0] : undefined;
2105
+ const domainList = sexpr.kind === "list" ? sexpr.items[1] : undefined;
2106
+ const rangeSort = sexpr.kind === "list" ? sexpr.items[2] : undefined;
2107
+ if (!isSymbol(name) || domainList?.kind !== "list" || rangeSort === undefined)
2108
+ throw new SmtUnsupportedError("the declaration reference");
2109
+ const domain = domainList.items.map((item) => parseSort(item, "Invalid function name"));
2110
+ const range = parseSort(rangeSort, "Invalid function name");
2111
+ const declared = funcs.get(name.text)?.find((decl) => hasSignature(decl, domain, range));
2112
+ if (declared !== undefined) return { decl: declared, domain, range };
2113
+ const builtin = CHAINABLE_OPS.get(name.text) ?? BUILTIN_OPS.get(name.text);
2114
+ if (builtin === undefined)
2115
+ throw new SmtUnsupportedError(`the declaration reference ${name.text}`);
2116
+ return { decl: builtin, domain, range: getBuiltinRange(builtin, domain) };
2117
+ };
2118
+
2119
+ const mkMapTerm = (mapped: MappedDecl, args: number[], at: SExpr) => {
2120
+ const signature = getMapSignature(
2121
+ manager,
2122
+ mapped,
2123
+ args.map((arg) => manager.sorts[arg]),
2124
+ );
2125
+ if (typeof signature === "string") throw new SmtParseError(signature, at);
2126
+ const decl = manager.mkArrayDecl(
2127
+ OP_ARRAY_MAP,
2128
+ signature.name,
2129
+ [mapped.decl],
2130
+ signature.domain,
2131
+ signature.range,
2132
+ );
2133
+ return manager.mkApp(decl, args, signature.range);
2134
+ };
2135
+
2136
+ const getArrayOp = (name: string) =>
2137
+ hasArrays
2138
+ ? (ARRAY_OPS.get(name) ?? (hasArrayExtensions ? ARRAY_EXTENSION_OPS.get(name) : undefined))
2139
+ : undefined;
2140
+
2141
+ const parseApp = (
2142
+ head: SmtToken,
2143
+ args: number[],
2144
+ at: SExpr,
2145
+ indices: number[] = [],
2146
+ range?: number,
2147
+ ) => {
2148
+ const name = head.text;
2149
+ // A bound variable applied to arguments selects from the array it stands for, one at a time.
2150
+ const local = locals.get(name);
2151
+ if (args.length > 0 && local !== undefined)
2152
+ return args.reduce(
2153
+ (array, arg) => mkArrayTerm(OP_SELECT, [array, arg], [], at),
2154
+ getLocalTerm(local),
2155
+ );
2156
+ if (indices.length > 0)
2157
+ return isFpaOpName(name)
2158
+ ? mkFpaTerm(name, args, indices, at)
2159
+ : isSeqOpName(name)
2160
+ ? mkSeqTerm(name, args, indices, at)
2161
+ : mkBvApp(name, args, indices, at);
2162
+ const macro = macros.get(name);
2163
+ // macros_find: a macro takes its own sorts, and Int for Real or Real for Int. Any other
2164
+ // application leaves the name to a declaration.
2165
+ if (
2166
+ macro !== undefined &&
2167
+ macro.domain.length === args.length &&
2168
+ args.every(
2169
+ (arg, index) =>
2170
+ manager.sorts[arg] === macro.domain[index] ||
2171
+ (isArithSort(manager.sorts[arg]) && isArithSort(macro.domain[index])),
428
2172
  )
429
- results.push(parseLeaf(current));
430
- else frames.push({ name: expectSymbol(head), list: current, start: results.length, next: 1 });
2173
+ )
2174
+ return expandMacro(
2175
+ macro,
2176
+ args.map((arg, index) => coerce(arg, macro.domain[index])),
2177
+ );
2178
+ const decls = funcs.get(name);
2179
+ const declared = decls === undefined ? undefined : mkDeclaredApp(name, decls, args, range, at);
2180
+ if (declared !== undefined) return declared;
2181
+ // cmd_context::mk_app: a constant that starts with #f is a finite-field literal.
2182
+ if (args.length === 0 && name.startsWith("#f")) {
2183
+ if (!FF_LITERAL.test(name))
2184
+ throw new SmtParseError("invalid finite-field literal, expected #f<integer>m<prime>", at);
2185
+ if (!restricted.hasFf) throw new SmtParseError("logic does not support finite fields", at);
2186
+ throw new SmtUnsupportedError("finite-field literals");
2187
+ }
2188
+ if (isSeqOpName(name)) return mkSeqTerm(name, args, indices, at, range);
2189
+ if (range !== undefined)
2190
+ throw new SmtParseError(getUnknownConstantMessage(name, args, range), at);
2191
+ if (isBvOpName(name)) return mkBvApp(name, args, indices, at);
2192
+ if (isFpaOpName(name)) return mkFpaTerm(name, args, indices, at);
2193
+ const arrayOp = getArrayOp(name);
2194
+ if (arrayOp !== undefined) return mkArrayTerm(arrayOp, args, [], at);
2195
+ const builtin = (logic === undefined ? LOGIC_FREE_ALIASES.get(name) : undefined) ?? name;
2196
+ const isTranscendental = TRANSCENDENTALS.has(builtin) && hasTranscendentals(logic);
2197
+ if (isTranscendental && args.length === 0 && builtin === "pi") return manager.piExpr;
2198
+ if (isTranscendental && args.length === 0 && builtin === "euler") return manager.eulerExpr;
2199
+ const transcendentalOp = isTranscendental ? TRANSCENDENTAL_OPS.get(builtin) : undefined;
2200
+ if (isTranscendental && transcendentalOp === undefined)
2201
+ throw new SmtUnsupportedError(`the operator ${name}`);
2202
+ const builtinOp =
2203
+ builtin === "~"
2204
+ ? OP_UMINUS
2205
+ : (CHAINABLE_OPS.get(builtin) ?? BUILTIN_OPS.get(builtin) ?? transcendentalOp);
2206
+ // load_plugin registers the operators of arithmetic only for a logic that has it.
2207
+ const named =
2208
+ builtinOp !== undefined && manager.funcDecls[builtinOp].family === FAMILY_ARITH && !hasArith
2209
+ ? undefined
2210
+ : builtinOp;
2211
+ if (
2212
+ args.length === 0 &&
2213
+ named !== undefined &&
2214
+ manager.funcDecls[named].family === FAMILY_ARITH
2215
+ )
2216
+ throw new SmtParseError("no arguments supplied to arithmetical operator", head);
2217
+ // arith_decl_plugin::fix_kind.
2218
+ const op = named === OP_SUB && args.length === 1 ? OP_UMINUS : named;
2219
+ const domainSort = op === undefined ? -1 : getDomainSort(op, args, at);
2220
+ if (op !== undefined && domainSort !== -1) return mkApp(op, args, at, domainSort);
2221
+ if (
2222
+ op === undefined &&
2223
+ !isPortedTheoryOperator(name) &&
2224
+ ((THEORY_OPERATOR.test(name) &&
2225
+ (name.startsWith("bv")
2226
+ ? hasBv
2227
+ : name.startsWith("fp.")
2228
+ ? hasFpa
2229
+ : name.startsWith("ff.") || hasSeq)) ||
2230
+ THEORY_OPERATORS.has(name))
2231
+ )
2232
+ throw new SmtUnsupportedError(`the operator ${name}`);
2233
+ const instance = mkDatatypeInstanceApp(name, args, at);
2234
+ if (instance !== undefined) return instance;
2235
+ throw new SmtParseError(getUnknownConstantMessage(name, args, undefined), at);
2236
+ };
2237
+
2238
+ const parseLeaf = (sexpr: SmtToken): number => {
2239
+ if (sexpr.kind === "numeral")
2240
+ return restricted.isNumeralAsReal
2241
+ ? manager.mkRealNumeral(Rational.of(BigInt(sexpr.text), 1n))
2242
+ : manager.mkNumeral(BigInt(sexpr.text));
2243
+ if (sexpr.kind === "decimal") {
2244
+ const parts = sexpr.text.split(".");
2245
+ return manager.mkRealNumeral(
2246
+ Rational.of(BigInt(parts[0] + parts[1]), 10n ** BigInt(parts[1].length)),
2247
+ );
2248
+ }
2249
+ if (sexpr.kind === "bitvector") {
2250
+ const isBinary = sexpr.text[1] === "b";
2251
+ const digits = sexpr.text.slice(2);
2252
+ return manager.mkBvNumeral(
2253
+ BigInt(`0${isBinary ? "b" : "x"}${digits}`),
2254
+ digits.length * (isBinary ? 1 : 4),
2255
+ );
2256
+ }
2257
+ if (sexpr.kind === "string") return manager.mkString(parseZstring(sexpr.text, manager.maxChar));
2258
+ if (sexpr.kind === "symbol") {
2259
+ const local = locals.get(sexpr.text);
2260
+ if (local !== undefined) return getLocalTerm(local);
2261
+ if (sexpr.text === "true") return manager.trueExpr;
2262
+ if (sexpr.text === "false") return manager.falseExpr;
2263
+ return parseApp(sexpr, [], sexpr);
2264
+ }
2265
+ throw new SmtParseError(
2266
+ sexpr.kind === "keyword"
2267
+ ? "invalid expression, unexpected keyword"
2268
+ : "invalid expression, unexpected ')'",
2269
+ sexpr,
2270
+ );
2271
+ };
2272
+
2273
+ // name_expr and cmd_context::insert of a named term. Z3 reports an error at the token after the
2274
+ // name.
2275
+ const nameExpr = (expr: number, name: string, at: SExpr) => {
2276
+ if (manager.freeVarBounds[expr] > 0)
2277
+ throw new SmtParseError("invalid named expression, expression contains free variables", at);
2278
+ if (macros.get(name)?.domain.length === 0)
2279
+ throw new SmtParseError("named expression already defined", at);
2280
+ if ((funcs.get(name) ?? []).some((decl) => hasSignature(decl, [], manager.sorts[expr])))
2281
+ throw new SmtParseError(
2282
+ `invalid named expression, declaration already defined with this name ${name}`,
2283
+ at,
2284
+ );
2285
+ manager.incRef(expr);
2286
+ lastNamed.name = name;
2287
+ lastNamed.expr = expr;
2288
+ declare(funcs, name, [...(funcs.get(name) ?? []), manager.mkMacro(name, expr)]);
2289
+ declare(macros, name, { domain: [], range: manager.sorts[expr], body: expr });
2290
+ };
2291
+
2292
+ // push_app_frame's parse_qualified_identifier_core, on a head that is (_ <symbol> <index>*) or
2293
+ // (as <identifier> <sort>).
2294
+ const parseQualifiedHead = (list: SmtList, head: SmtList): QualifiedHead => {
2295
+ if (isSymbol(head.items[0], "as")) {
2296
+ const range = parseQualifierSort(head);
2297
+ const target = head.items[1];
2298
+ if (!isSymbol(target)) throw new SmtUnsupportedError("indexed and qualified identifiers");
2299
+ return {
2300
+ head: target,
2301
+ indices: [],
2302
+ build:
2303
+ hasArrays && target.text === "const"
2304
+ ? (args) => mkArrayTerm(OP_CONST_ARRAY, args, [range], list.end)
2305
+ : (args) => parseApp(target, args, list.end, [], range),
2306
+ };
2307
+ }
2308
+ const name = getIndexedName(head);
2309
+ const indices = head.items.slice(2);
2310
+ const indexed = indices[0];
2311
+ if (hasArrays && hasArrayExtensions && name.text === "map" && indices.length === 1) {
2312
+ const mapped = parseFuncDeclRef(indexed);
2313
+ return { head: name, indices: [], build: (args) => mkMapTerm(mapped, args, list.end) };
2314
+ }
2315
+ if ((name.text === "is" || name.text === "update-field") && indices.length === 1) {
2316
+ if (!isSymbol(indexed)) throw new SmtUnsupportedError("indexed and qualified identifiers");
2317
+ return {
2318
+ head: name,
2319
+ indices: [],
2320
+ build: (args) =>
2321
+ name.text === "is"
2322
+ ? mkIsApp(indexed, args, list.end)
2323
+ : mkUpdateFieldApp(indexed, args, list.end),
2324
+ };
2325
+ }
2326
+ const isNumbered = indices.every((index) => index.kind === "numeral");
2327
+ if (isNumbered && isPbOpName(name.text)) {
2328
+ const parameters = indices.map((index) =>
2329
+ Rational.of(BigInt(index.kind === "list" ? 0 : index.text)),
2330
+ );
2331
+ return {
2332
+ head: name,
2333
+ indices: [],
2334
+ build: (args) => mkPbTerm(name.text, args, parameters, list.end),
2335
+ };
2336
+ }
2337
+ if (isNumbered && (isBvOpName(name.text) || isFpaOpName(name.text) || isSeqOpName(name.text)))
2338
+ return {
2339
+ head: name,
2340
+ indices: indices.map((index) => (index.kind === "list" ? 0 : Number(index.text))),
2341
+ };
2342
+ // cmd_context::mk_app finds a name that no theory knows among the declarations, whatever its
2343
+ // indices are.
2344
+ if (isKnownOperator(name.text) || !indices.every(isSimpleIndex))
2345
+ throw new SmtUnsupportedError("indexed and qualified identifiers");
2346
+ return { head: name, indices: [] };
2347
+ };
2348
+
2349
+ // parse_expr. Z3 leaves the term on its stack until the command ends. A tail term is one whose
2350
+ // value is the value of the whole: it stays off the stack, in parsed, so that the caller of
2351
+ // parseTerm can have a term that nothing else holds without a reference of the parser's.
2352
+ const runTerm = (sexpr: SExpr, isRootTail: boolean) => {
2353
+ const root = sexpr.kind === "list" ? sexpr.root : undefined;
2354
+ if (root === undefined || root === parsed.root) protect(floating);
2355
+ else {
2356
+ releasePending();
2357
+ shrink(floating, 0);
2358
+ parsed.root = root;
2359
+ }
2360
+ protect(unrooted);
2361
+ const frames: TermFrame[] = [];
2362
+ // The value of a frame replaces what the frame left on the stack. Z3 holds it in an expr_ref
2363
+ // meanwhile.
2364
+ const deliver = (expr: number, isTail: boolean, start: number) => {
2365
+ const isOwned = !isTail || manager.getRefCount(expr) > 0;
2366
+ if (isOwned) manager.incRef(expr);
2367
+ shrinkRefs(exprStack, start);
2368
+ if (!isTail) {
2369
+ exprStack.push(expr);
2370
+ return;
2371
+ }
2372
+ parsed.expr = expr;
2373
+ parsed.isOwned = isOwned;
2374
+ };
2375
+ // push_pattern_frame.
2376
+ const enterPattern = (value: SExpr, frame: AttributeFrame) => {
2377
+ if (value.kind !== "list") {
2378
+ if (!options.isIgnoringBadPatterns)
2379
+ throw new SmtParseError("invalid pattern, '(' expected", value);
2380
+ // Z3 skips a bad pattern as an s-expression, which cannot start with ')'.
2381
+ if (value.kind === ")")
2382
+ throw new SmtParseError("invalid s-expression, unexpected ')'", value);
2383
+ frame.next++;
2384
+ exprStack.push(-1);
2385
+ return;
2386
+ }
2387
+ frame.next++;
2388
+ const first = value.items[0];
2389
+ if (first === undefined) {
2390
+ exprStack.push(-1);
2391
+ return;
2392
+ }
2393
+ if (first.kind === "list") {
2394
+ frames.push({ kind: "pattern", list: value, start: exprStack.length, next: 0 });
2395
+ return;
2396
+ }
2397
+ const decl = first.text === "true" || first.text === "false" ? -1 : getFirstFunc(first.text);
2398
+ if (decl === -1 || (decl !== undefined && manager.funcDecls[decl].domain.length === 0)) {
2399
+ if (!options.isIgnoringBadPatterns)
2400
+ throw new SmtParseError("invalid constant pattern", first);
2401
+ exprStack.push(-1);
2402
+ return;
2403
+ }
2404
+ if (first.kind !== "symbol")
2405
+ throw new SmtParseError("invalid pattern, '(' or identifier expected", first);
2406
+ frames.push({
2407
+ kind: "application",
2408
+ list: value,
2409
+ head: first,
2410
+ indices: [],
2411
+ isTail: false,
2412
+ start: exprStack.length,
2413
+ next: 1,
2414
+ });
2415
+ };
2416
+ const enter = (current: SExpr, isTail: boolean) => {
2417
+ if (current.kind !== "list") {
2418
+ deliver(parseLeaf(current), isTail, exprStack.length);
2419
+ return;
2420
+ }
2421
+ const head = current.items[0];
2422
+ if (head === undefined || (head.kind !== "symbol" && head.kind !== "list"))
2423
+ throw new SmtParseError("invalid expression, '(' or symbol expected", head ?? current.end);
2424
+ if (head.kind === "list") {
2425
+ // push_app_frame: Z3 reads a head that is neither indexed nor qualified as a term.
2426
+ if (isSymbol(head.items[0], "lambda"))
2427
+ throw new SmtUnsupportedError("indexed and qualified identifiers");
2428
+ frames.push(
2429
+ isSymbol(head.items[0], "_") || isSymbol(head.items[0], "as")
2430
+ ? {
2431
+ kind: "application",
2432
+ list: current,
2433
+ ...parseQualifiedHead(current, head),
2434
+ isTail,
2435
+ start: exprStack.length,
2436
+ next: 1,
2437
+ }
2438
+ : { kind: "selection", list: current, isTail, start: exprStack.length, next: 0 },
2439
+ );
2440
+ return;
2441
+ }
2442
+ if (head.text === "_" || head.text === "as") {
2443
+ deliver(parseQualifiedName(current), isTail, exprStack.length);
2444
+ return;
2445
+ }
2446
+ if (head.text === "root-obj") {
2447
+ deliver(parseRootObj(current), isTail, exprStack.length);
2448
+ return;
2449
+ }
2450
+ if (head.text === "match") throw new SmtUnsupportedError("the expression match");
2451
+ if (head.text === "let") {
2452
+ const bindings = current.items[1];
2453
+ if (bindings?.kind !== "list")
2454
+ throw new SmtParseError(
2455
+ `invalid let declaration, '(' expected got ${getLastId(bindings) ?? "let"}`,
2456
+ bindings ?? current.end,
2457
+ );
2458
+ frames.push({
2459
+ kind: "let",
2460
+ list: current,
2461
+ bindings,
2462
+ names: [],
2463
+ isInDecls: true,
2464
+ isTail,
2465
+ start: exprStack.length,
2466
+ next: 0,
2467
+ });
2468
+ return;
2469
+ }
2470
+ if (head.text === "!") {
2471
+ const parent = frames[frames.length - 1];
2472
+ frames.push({
2473
+ kind: "attribute",
2474
+ list: current,
2475
+ quantifier: parent?.kind === "quantifier" ? parent : undefined,
2476
+ lastKeyword: "",
2477
+ isTail,
2478
+ start: exprStack.length,
2479
+ next: 1,
2480
+ });
2481
+ return;
2482
+ }
2483
+ const quantifierKind = QUANTIFIER_KINDS.get(head.text);
2484
+ if (quantifierKind === undefined) {
2485
+ frames.push({
2486
+ kind: "application",
2487
+ list: current,
2488
+ head,
2489
+ indices: [],
2490
+ isTail,
2491
+ start: exprStack.length,
2492
+ next: 1,
2493
+ });
2494
+ return;
2495
+ }
2496
+ // push_quant_frame.
2497
+ const start = exprStack.length;
2498
+ const bound = bindSortedVars(current.items[1], current.end, head.text);
2499
+ if (bound.varSorts.length === 0)
2500
+ throw new SmtParseError(
2501
+ "invalid quantifier, list of sorted variables is empty",
2502
+ current.items[2] ?? current.end,
2503
+ );
2504
+ frames.push({
2505
+ kind: "quantifier",
2506
+ list: current,
2507
+ quantifierKind,
2508
+ names: bound.names,
2509
+ varSorts: bound.varSorts,
2510
+ weight: 1,
2511
+ qid: "",
2512
+ skid: undefined,
2513
+ isTail,
2514
+ start,
2515
+ patternStart: patternStack.length,
2516
+ noPatternStart: noPatternStack.length,
2517
+ next: 2,
2518
+ });
431
2519
  };
432
- enter(sexpr);
2520
+ enter(sexpr, isRootTail);
433
2521
  while (frames.length > 0) {
434
2522
  const frame = frames[frames.length - 1];
435
- if (frame.next < frame.list.length) {
436
- enter(frame.list[frame.next++]);
2523
+ if (frame.kind === "let") {
2524
+ if (frame.isInDecls) {
2525
+ const declaration = frame.bindings.items[frame.next];
2526
+ if (declaration !== undefined) {
2527
+ // push_let_decl_frame.
2528
+ if (declaration.kind !== "list")
2529
+ throw new SmtParseError(
2530
+ `invalid let declaration, '(' expected got ${getLastId(declaration) ?? getLastIdBefore(frame.bindings.items, frame.next) ?? "let"}`,
2531
+ declaration,
2532
+ );
2533
+ const name = declaration.items[0];
2534
+ if (!isSymbol(name)) throw new SmtParseError(LET_MESSAGE, name ?? declaration.end);
2535
+ frame.names.push(name.text);
2536
+ frame.next++;
2537
+ frames.push({ kind: "let-decl", list: declaration, next: 1 });
2538
+ continue;
2539
+ }
2540
+ // pop_let_frame at the end of the declarations.
2541
+ if (frame.names.length !== exprStack.length - frame.start)
2542
+ throw new SmtParseError("malformed let expression", frame.bindings.end);
2543
+ beginScope();
2544
+ for (const [index, name] of frame.names.entries())
2545
+ insertLocal(name, exprStack[frame.start + index]);
2546
+ frame.isInDecls = false;
2547
+ frame.next = 2;
2548
+ continue;
2549
+ }
2550
+ const body = frame.list.items[frame.next];
2551
+ if (body !== undefined) {
2552
+ frame.next++;
2553
+ enter(body, frame.isTail && frame.next === frame.list.items.length);
2554
+ continue;
2555
+ }
2556
+ frames.pop();
2557
+ // Z3 takes the last expression on its stack, so a let without a body is its last binding.
2558
+ if (frame.isTail && frame.list.items.length > 2) shrinkRefs(exprStack, frame.start);
2559
+ else if (exprStack.length === frame.start)
2560
+ throw new SmtParseError("invalid let expression", frame.list.end);
2561
+ else deliver(exprStack[exprStack.length - 1], frame.isTail, frame.start);
2562
+ endScope();
2563
+ continue;
2564
+ }
2565
+ const items = frame.list.items;
2566
+ if (frame.kind === "attribute") {
2567
+ // consume_attributes.
2568
+ if (exprStack.length === frame.start) {
2569
+ if (frame.next >= items.length)
2570
+ throw new SmtParseError("invalid expression", frame.list.end);
2571
+ enter(items[frame.next++], false);
2572
+ continue;
2573
+ }
2574
+ // process_last_symbol.
2575
+ const last = exprStack[exprStack.length - 1];
2576
+ if (frame.lastKeyword === ":pattern") {
2577
+ const at = items[frame.next] ?? frame.list.end;
2578
+ if (last === -1 && !options.isIgnoringBadPatterns)
2579
+ throw new SmtParseError("invalid empty pattern", at);
2580
+ if (last !== -1)
2581
+ pushRef(
2582
+ patternStack,
2583
+ manager.kinds[last] === KIND_APP && manager.decls[last] === OP_PATTERN
2584
+ ? last
2585
+ : mkPattern([last], at),
2586
+ );
2587
+ shrinkRefs(exprStack, exprStack.length - 1);
2588
+ } else if (frame.lastKeyword === ":no-pattern") {
2589
+ pushRef(noPatternStack, last);
2590
+ shrinkRefs(exprStack, exprStack.length - 1);
2591
+ }
2592
+ frame.lastKeyword = "";
2593
+ if (frame.next >= items.length) {
2594
+ frames.pop();
2595
+ if (frame.isTail) deliver(exprStack[exprStack.length - 1], true, frame.start);
2596
+ continue;
2597
+ }
2598
+ while (frame.next < items.length && frame.lastKeyword === "") {
2599
+ const keyword = items[frame.next];
2600
+ if (keyword.kind !== "keyword")
2601
+ throw new SmtParseError("invalid attributed expression, keyword expected", keyword);
2602
+ const value = items[frame.next + 1] ?? frame.list.end;
2603
+ const annotated = exprStack[exprStack.length - 1];
2604
+ const quantifier = frame.quantifier;
2605
+ if (keyword.text === ":named") {
2606
+ if (!isSymbol(value))
2607
+ throw new SmtParseError("invalid attribute value, symbol expected", value);
2608
+ nameExpr(annotated, value.text, items[frame.next + 2] ?? frame.list.end);
2609
+ frame.next += 2;
2610
+ } else if (keyword.text === ":lblpos" || keyword.text === ":lblneg") {
2611
+ if (!isSymbol(value))
2612
+ throw new SmtParseError("invalid attribute value, symbol expected", value);
2613
+ if (manager.sorts[annotated] !== SORT_BOOL)
2614
+ throw new SmtParseError(
2615
+ "invalid labeled expression, expression must have Bool sort",
2616
+ value,
2617
+ );
2618
+ deliver(
2619
+ manager.mkLabel(keyword.text === ":lblpos", [value.text], annotated),
2620
+ false,
2621
+ exprStack.length - 1,
2622
+ );
2623
+ frame.next += 2;
2624
+ } else if (!QUANTIFIER_ATTRIBUTES.has(keyword.text)) {
2625
+ // Z3 warns of an unknown attribute and skips its value as an s-expression.
2626
+ if (value.kind === ")")
2627
+ throw new SmtParseError("invalid s-expression, unexpected ')'", value);
2628
+ frame.next += 2;
2629
+ } else if (quantifier === undefined)
2630
+ throw new SmtParseError("invalid attribute, not in the scope of a quantifier", keyword);
2631
+ else if (keyword.text === ":weight") {
2632
+ // check_int, and curr_unsigned.
2633
+ if (value.kind !== "numeral")
2634
+ throw new SmtParseError("invalid weight attribute, integer expected", value);
2635
+ if (!isUnsigned(value.text))
2636
+ throw new SmtParseError(
2637
+ "invalid indexed identifier, index is too big to fit in an unsigned machine integer",
2638
+ value,
2639
+ );
2640
+ quantifier.weight = Number(value.text);
2641
+ frame.next += 2;
2642
+ } else if (keyword.text === ":skolemid" || keyword.text === ":qid") {
2643
+ if (!isSymbol(value))
2644
+ throw new SmtParseError("invalid attribute value, symbol expected", value);
2645
+ if (keyword.text === ":qid") quantifier.qid = value.text;
2646
+ else quantifier.skid = value.text;
2647
+ frame.next += 2;
2648
+ } else {
2649
+ frame.lastKeyword = keyword.text;
2650
+ frame.next++;
2651
+ if (keyword.text === ":pattern") enterPattern(value, frame);
2652
+ else if (value.kind === ")")
2653
+ throw new SmtParseError("invalid expression, unexpected input", value);
2654
+ else enter(items[frame.next++], false);
2655
+ }
2656
+ }
2657
+ continue;
2658
+ }
2659
+ if (frame.next < items.length) {
2660
+ enter(items[frame.next++], false);
437
2661
  continue;
438
2662
  }
439
2663
  frames.pop();
440
- results.push(parseApp(frame.name, results.splice(frame.start)));
2664
+ if (frame.kind === "let-decl") continue;
2665
+ if (frame.kind === "pattern") {
2666
+ deliver(mkPattern(exprStack.slice(frame.start), frame.list.end), false, frame.start);
2667
+ continue;
2668
+ }
2669
+ if (frame.kind === "quantifier") {
2670
+ // pop_quant_frame.
2671
+ deliver(mkParsedQuantifier(frame), frame.isTail, frame.start);
2672
+ shrinkRefs(patternStack, frame.patternStart);
2673
+ shrinkRefs(noPatternStack, frame.noPatternStart);
2674
+ unbindSortedVars(frame.varSorts.length);
2675
+ continue;
2676
+ }
2677
+ // pop_app_frame.
2678
+ const args = exprStack.slice(frame.start);
2679
+ if (args.length < (frame.kind === "selection" ? 2 : 1))
2680
+ throw new SmtParseError("invalid function application, arguments missing", frame.list.end);
2681
+ deliver(
2682
+ frame.kind === "selection"
2683
+ ? args
2684
+ .slice(1)
2685
+ .reduce(
2686
+ (array, arg) => mkArrayTerm(OP_SELECT, [array, arg], [], frame.list.end),
2687
+ args[0],
2688
+ )
2689
+ : (frame.build?.(args) ?? parseApp(frame.head, args, frame.list.end, frame.indices)),
2690
+ frame.isTail,
2691
+ frame.start,
2692
+ );
2693
+ }
2694
+ };
2695
+
2696
+ const parseTerm = (sexpr: SExpr) => {
2697
+ runTerm(sexpr, true);
2698
+ const expr = parsed.expr;
2699
+ parsed.expr = -1;
2700
+ if (!parsed.isOwned)
2701
+ (sexpr.kind === "list" && sexpr.root !== undefined ? floating : unrooted).push(expr);
2702
+ else if (manager.getRefCount(expr) > 1) manager.decRef(expr);
2703
+ else pending.push(expr);
2704
+ return expr;
2705
+ };
2706
+
2707
+ const parseDomain = (sexpr: SExpr | undefined, at: SExpr) => {
2708
+ const context = "Parsing function declaration. Expecting sort list '('";
2709
+ return expectList(sexpr, context, at).items.map((item) => parseSort(item, context));
2710
+ };
2711
+
2712
+ const parseSortParameters = (sexpr: SExpr | undefined, message: string, at: SExpr) =>
2713
+ expectList(sexpr, "invalid sort declaration, parameters missing", at).items.map(
2714
+ (item) => expectSymbol(item, message, item).text,
2715
+ );
2716
+
2717
+ const bindTypeParameters = (names: string[]) =>
2718
+ new Map(names.map((name, index) => [name, manager.mkTypeParameter(index)]));
2719
+
2720
+ const parseAccessorSort = (
2721
+ sexpr: SExpr,
2722
+ bindings: ReadonlyMap<string, number>,
2723
+ datatypeIndexes: ReadonlyMap<string, number>,
2724
+ missing: string[],
2725
+ ) => {
2726
+ if (sexpr.kind === "list") return parseSort(sexpr, "", bindings);
2727
+ if (sexpr.kind !== "symbol")
2728
+ throw new SmtParseError("invalid sort, symbol, '_' or '(' expected", sexpr);
2729
+ if (sortDecls.has(sexpr.text) || bindings.has(sexpr.text))
2730
+ return parseSort(sexpr, "", bindings);
2731
+ const index = datatypeIndexes.get(sexpr.text);
2732
+ if (index !== undefined) return -1 - index;
2733
+ missing.push(sexpr.text);
2734
+ return SORT_BOOL;
2735
+ };
2736
+
2737
+ const parseConstructors = (
2738
+ items: SExpr[],
2739
+ bindings: ReadonlyMap<string, number>,
2740
+ datatypeIndexes: ReadonlyMap<string, number>,
2741
+ missing: string[],
2742
+ at: SExpr,
2743
+ ): ConstructorDef[] => {
2744
+ if (items.length === 0)
2745
+ throw new SmtParseError(
2746
+ "invalid datatype declaration, datatype does not have any constructors",
2747
+ at,
2748
+ );
2749
+ return items.map((item) => {
2750
+ if (isSymbol(item)) return { name: item.text, recognizer: `is-${item.text}`, accessors: [] };
2751
+ const constructor = expectList(
2752
+ item,
2753
+ "invalid datatype declaration, '(' or ')' expected",
2754
+ item,
2755
+ );
2756
+ const name = expectSymbol(
2757
+ constructor.items[0],
2758
+ "invalid constructor declaration, symbol (constructor name) expected",
2759
+ constructor,
2760
+ ).text;
2761
+ const accessors = constructor.items.slice(1).map((accessorItem) => {
2762
+ const accessor = expectList(
2763
+ accessorItem,
2764
+ "invalid datatype declaration, '(' or ')' expected",
2765
+ accessorItem,
2766
+ );
2767
+ const accessorName = expectSymbol(
2768
+ accessor.items[0],
2769
+ "invalid accessor declaration, symbol (accessor name) expected",
2770
+ accessor,
2771
+ ).text;
2772
+ const range = parseAccessorSort(
2773
+ accessor.items[1] ?? accessor.end,
2774
+ bindings,
2775
+ datatypeIndexes,
2776
+ missing,
2777
+ );
2778
+ if (accessor.items.length > 2)
2779
+ throw new SmtParseError("invalid accessor declaration, ')' expected", accessor.items[2]);
2780
+ return { name: accessorName, range };
2781
+ });
2782
+ return { name, recognizer: `is-${name}`, accessors };
2783
+ });
2784
+ };
2785
+
2786
+ const parseDatatypeBody = (
2787
+ sexpr: SExpr | undefined,
2788
+ datatypeIndexes: ReadonlyMap<string, number>,
2789
+ missing: string[],
2790
+ at: SExpr,
2791
+ ) => {
2792
+ const body = expectList(sexpr, "invalid datatype declaration, '(' expected", at);
2793
+ if (!isSymbol(body.items[0], "par"))
2794
+ return {
2795
+ parameters: [],
2796
+ constructors: parseConstructors(body.items, NO_BINDINGS, datatypeIndexes, missing, body),
2797
+ };
2798
+ const parameters = parseSortParameters(
2799
+ body.items[1],
2800
+ "invalid sort parameter, symbol or ')' expected",
2801
+ body,
2802
+ );
2803
+ const constructors = expectList(
2804
+ body.items[2],
2805
+ "invalid constructor declaration after par, '(' expected",
2806
+ body,
2807
+ );
2808
+ return {
2809
+ parameters: parameters.map((_name, index) => manager.mkTypeParameter(index)),
2810
+ constructors: parseConstructors(
2811
+ constructors.items,
2812
+ bindTypeParameters(parameters),
2813
+ datatypeIndexes,
2814
+ missing,
2815
+ constructors,
2816
+ ),
2817
+ };
2818
+ };
2819
+
2820
+ const commitDatatypes = (defs: DatatypeDef[], missing: string[], at: SExpr, end: SExpr) => {
2821
+ if (missing.length > 0)
2822
+ throw new SmtParseError(`invalid datatype declaration, unknown sort '${missing[0]}'`, at);
2823
+ const sorts = mkDatatypes(manager, defs);
2824
+ if (typeof sorts === "string") throw new SmtParseError(sorts, end);
2825
+ for (const def of defs) undo.push(() => removeDatatype(manager, def.name));
2826
+ defs.forEach((def, index) => {
2827
+ if (def.parameters.length === 0) insertDatatypeDecls(sorts[index], end);
2828
+ });
2829
+ for (const def of defs) {
2830
+ const names = def.constructors.flatMap((constructor) =>
2831
+ constructor.accessors.map((accessor) => accessor.name),
2832
+ );
2833
+ const duplicated = names.find((name, index) => names.indexOf(name) !== index);
2834
+ if (duplicated !== undefined)
2835
+ throw new SmtParseError(
2836
+ `invalid datatype declaration, repeated accessor identifier '${duplicated}'`,
2837
+ at,
2838
+ );
2839
+ }
2840
+ };
2841
+
2842
+ const declareSortDecl = (name: string, decl: SortDecl, at: SExpr) => {
2843
+ if (sortDecls.has(name)) throw new SmtParseError(`sort already defined ${name}`, at);
2844
+ declare(sortDecls, name, decl);
2845
+ };
2846
+
2847
+ const declareDatatypes = (list: SmtList) => {
2848
+ const declaration = expectList(
2849
+ list.items[1],
2850
+ "invalid sort declaration, parameters missing",
2851
+ list,
2852
+ );
2853
+ const isSmt26 = declaration.items[0]?.kind === "list";
2854
+ const datatypeIndexes = new Map<string, number>();
2855
+ const names: string[] = [];
2856
+ const arities: number[] = [];
2857
+ const parameterNames: string[] = [];
2858
+ declaration.items.forEach((item, index) => {
2859
+ if (!isSmt26) {
2860
+ parameterNames.push(
2861
+ expectSymbol(item, "invalid sort parameter, symbol or ')' expected", item).text,
2862
+ );
2863
+ return;
2864
+ }
2865
+ const sortDeclaration = expectList(item, "invalid sort declaration, '(' expected", item);
2866
+ const name = expectSymbol(
2867
+ sortDeclaration.items[0],
2868
+ "invalid sort name, identified expected",
2869
+ sortDeclaration,
2870
+ ).text;
2871
+ const arity = sortDeclaration.items[1];
2872
+ if (arity?.kind !== "numeral")
2873
+ throw new SmtParseError(
2874
+ "invalid sort declaration, arity expected",
2875
+ arity ?? sortDeclaration.end,
2876
+ );
2877
+ if (sortDeclaration.items.length > 2)
2878
+ throw new SmtParseError("invalid sort declaration, ')' expected", sortDeclaration.items[2]);
2879
+ datatypeIndexes.set(name, index);
2880
+ names.push(name);
2881
+ arities.push(Number(arity.text));
2882
+ declareSortDecl(
2883
+ name,
2884
+ { kind: "datatype", name, arity: Number(arity.text), siblings: [], instances: new Map() },
2885
+ sortDeclaration,
2886
+ );
2887
+ });
2888
+ const bodies = expectList(list.items[2], "invalid datatype declaration, '(' expected", list);
2889
+ // A datatype of the older syntax may refer to any datatype of its declaration.
2890
+ if (!isSmt26)
2891
+ bodies.items.forEach((item, index) => {
2892
+ const datatype = expectList(
2893
+ item,
2894
+ "invalid datatype declaration, '(' or ')' expected",
2895
+ item,
2896
+ );
2897
+ const name = expectSymbol(
2898
+ datatype.items[0],
2899
+ "invalid datatype declaration, symbol (datatype name) expected",
2900
+ datatype,
2901
+ ).text;
2902
+ datatypeIndexes.set(name, index);
2903
+ names.push(name);
2904
+ });
2905
+ const missing: string[] = [];
2906
+ const typeParameters = parameterNames.map((_name, index) => manager.mkTypeParameter(index));
2907
+ const bindings = bindTypeParameters(parameterNames);
2908
+ const defs = bodies.items.map((item, index) => {
2909
+ if (isSmt26) {
2910
+ if (index >= names.length)
2911
+ throw new SmtParseError(
2912
+ "invalid datatype declaration, too many data-type bodies defined",
2913
+ item,
2914
+ );
2915
+ return mkDatatypeDef(
2916
+ manager,
2917
+ names[index],
2918
+ Array.from({ length: arities[index] }, (_unused, parameter) =>
2919
+ manager.mkTypeParameter(parameter),
2920
+ ),
2921
+ parseDatatypeBody(item, datatypeIndexes, missing, list).constructors,
2922
+ );
2923
+ }
2924
+ const datatype = expectList(item, "invalid datatype declaration, '(' or ')' expected", item);
2925
+ return mkDatatypeDef(
2926
+ manager,
2927
+ names[index],
2928
+ typeParameters,
2929
+ parseConstructors(datatype.items.slice(1), bindings, datatypeIndexes, missing, datatype),
2930
+ );
2931
+ });
2932
+ if (defs.length < arities.length)
2933
+ throw new SmtParseError(
2934
+ "invalid datatype declaration, too few datatype definitions compared to declared sorts",
2935
+ bodies.end,
2936
+ );
2937
+ if (list.items.length > 3)
2938
+ throw new SmtParseError("invalid datatype declaration", list.items[3]);
2939
+ if (defs.length === 0) return;
2940
+ commitDatatypes(defs, missing, declaration, list.end);
2941
+ if (isSmt26) return;
2942
+ for (const def of defs)
2943
+ declareSortDecl(
2944
+ def.name,
2945
+ {
2946
+ kind: "datatype",
2947
+ name: def.name,
2948
+ arity: def.parameters.length,
2949
+ siblings: defs.length > 1 ? names : [],
2950
+ instances: new Map(),
2951
+ },
2952
+ list.end,
2953
+ );
2954
+ };
2955
+
2956
+ const declareDatatype = (list: SmtList) => {
2957
+ const name = expectSymbol(list.items[1], "unexpected token used as datatype name", list);
2958
+ const missing: string[] = [];
2959
+ const bodyList = list.items[2];
2960
+ const arity =
2961
+ bodyList?.kind === "list" &&
2962
+ isSymbol(bodyList.items[0], "par") &&
2963
+ bodyList.items[1]?.kind === "list"
2964
+ ? bodyList.items[1].items.length
2965
+ : 0;
2966
+ declareSortDecl(
2967
+ name.text,
2968
+ { kind: "datatype", name: name.text, arity, siblings: [], instances: new Map() },
2969
+ name,
2970
+ );
2971
+ const body = parseDatatypeBody(bodyList, new Map([[name.text, 0]]), missing, list);
2972
+ commitDatatypes(
2973
+ [mkDatatypeDef(manager, name.text, body.parameters, body.constructors)],
2974
+ missing,
2975
+ name,
2976
+ list.items[3] ?? list.end,
2977
+ );
2978
+ expectEnd(list.items[3], "invalid end of datatype declaration, ')' expected");
2979
+ };
2980
+
2981
+ // parse_rec_fun_decl: the variables are bound only while the range is parsed, and Z3 holds them
2982
+ // until the command ends, as the stack does here.
2983
+ const declareRecFun = (items: SExpr[], at: SExpr) => {
2984
+ const symbol = expectSymbol(
2985
+ items[0],
2986
+ "invalid function/constant definition, symbol expected",
2987
+ at,
2988
+ );
2989
+ const bound = bindSortedVars(items[1], at, symbol.text);
2990
+ const range = parseSort(items[2] ?? at, "Invalid recursive function definition");
2991
+ unbindSortedVars(bound.varSorts.length);
2992
+ return manager.mkRecFuncDecl(symbol.text, bound.varSorts, range);
2993
+ };
2994
+
2995
+ // parse_rec_fun_body: Z3 reports a body of another sort at the token after it.
2996
+ const defineRecFun = (decl: number, variables: SExpr, body: SExpr, next: SExpr) => {
2997
+ const start = exprStack.length;
2998
+ const bound = bindSortedVars(variables, body, "");
2999
+ runTerm(body, false);
3000
+ const parsedBody = exprStack[exprStack.length - 1];
3001
+ unbindSortedVars(bound.varSorts.length);
3002
+ const range = manager.funcDecls[decl].range;
3003
+ if (manager.sorts[parsedBody] !== range)
3004
+ throw new SmtParseError(
3005
+ `invalid function definition, sort mismatch. Expcected ${manager.getSortName(range)} but function body has sort ${manager.getSortName(manager.sorts[parsedBody])}`,
3006
+ next,
3007
+ );
3008
+ setRecFunDefinition(manager, manager.recFunDefs.get(decl)!, false, parsedBody);
3009
+ shrinkRefs(exprStack, start);
3010
+ };
3011
+
3012
+ // parse_define and insert_macro: Z3 declares a macro as a recursive function with one case, which
3013
+ // a reference without arguments takes as an array. The reference that the body with its variables
3014
+ // reversed keeps stands for Z3's macro_decls, and those of the variables for the definition's.
3015
+ const defineMacroFunc = (name: string, domain: number[], body: number) => {
3016
+ const count = domain.length;
3017
+ if (count > 1) {
3018
+ const subst = new VarSubst(manager, true);
3019
+ subst.apply(
3020
+ body,
3021
+ domain.map((sort, index) => manager.mkVar(index, sort)),
3022
+ );
3023
+ subst.release();
441
3024
  }
442
- return results[0];
3025
+ for (const [index, sort] of domain.entries()) manager.incRef(manager.mkVar(index, sort));
3026
+ const reversedVars = domain.map((_value, index) =>
3027
+ manager.mkVar(index, domain[count - index - 1]),
3028
+ );
3029
+ for (const reversedVar of reversedVars) manager.incRef(reversedVar);
3030
+ const decl = manager.mkRecFuncDecl(name, domain, manager.sorts[body]);
3031
+ for (const reversedVar of reversedVars) manager.decRef(reversedVar);
3032
+ setRecFunDefinition(manager, manager.recFunDefs.get(decl)!, true, body);
3033
+ declare(funcs, name, [...(funcs.get(name) ?? []), decl]);
443
3034
  };
444
3035
 
445
- let hasCheckSat = false;
446
- for (const command of readSExprs(tokenize(text))) {
447
- const list = expectList(command);
448
- const name = expectSymbol(list[0]);
3036
+ const declareCommand = (list: SmtList) => {
3037
+ releasePending();
3038
+ const name = list.items[0].kind === "list" ? "" : list.items[0].text;
3039
+ if (name === "define-fun-rec") {
3040
+ const decl = declareRecFun(list.items.slice(1), list.end);
3041
+ insertFunc(decl, list.items[4] ?? list.end);
3042
+ defineRecFun(decl, list.items[2], list.items[4] ?? list.end, list.items[5] ?? list.end);
3043
+ expectEnd(list.items[5], "invalid function/constant definition, ')' expected");
3044
+ shrinkRefs(exprStack, 0);
3045
+ return;
3046
+ }
3047
+ if (name === "define-funs-rec") {
3048
+ const message = "invalid recursive function definition, '(' expected";
3049
+ const signatures = expectList(list.items[1], message, list.end).items.map((signature) => {
3050
+ const declaration = expectList(signature, message, signature);
3051
+ const items = declaration.items;
3052
+ if (items.length > 3)
3053
+ throw new SmtParseError("invalid recursive function definition, ')' expected", items[3]);
3054
+ return { items, decl: declareRecFun(items, declaration.end) };
3055
+ });
3056
+ for (const signature of signatures) insertFunc(signature.decl, list.items[2] ?? list.end);
3057
+ const bodies = expectList(list.items[2], message, list.end);
3058
+ signatures.forEach((signature, index) => {
3059
+ const body = bodies.items[index];
3060
+ if (body === undefined)
3061
+ throw new SmtParseError(
3062
+ "the number of declarations does not match number of supplied definitions",
3063
+ bodies.end,
3064
+ );
3065
+ defineRecFun(
3066
+ signature.decl,
3067
+ signature.items[1],
3068
+ body,
3069
+ bodies.items[index + 1] ?? bodies.end,
3070
+ );
3071
+ });
3072
+ expectEnd(
3073
+ bodies.items[signatures.length],
3074
+ "invalid recursive function definition, ')' expected",
3075
+ );
3076
+ expectEnd(list.items[3], "invalid function/constant definition, ')' expected");
3077
+ shrinkRefs(exprStack, 0);
3078
+ return;
3079
+ }
3080
+ if (name === "declare-datatypes") {
3081
+ declareDatatypes(list);
3082
+ return;
3083
+ }
3084
+ if (name === "declare-datatype") {
3085
+ declareDatatype(list);
3086
+ return;
3087
+ }
3088
+ const symbol = expectSymbol(list.items[1], "invalid declaration, symbol expected", list);
449
3089
  if (name === "declare-sort") {
450
- if (list[2] !== undefined && list[2] !== "0")
451
- throw new SmtUnsupportedError("parametric sorts are not supported");
452
- sorts.set(expectSymbol(list[1]), manager.mkSort(expectSymbol(list[1])));
453
- } else if (name === "declare-fun" || name === "declare-const") {
454
- const domain = name === "declare-fun" ? expectList(list[2]).map(parseSort) : [];
455
- const range = parseSort(name === "declare-fun" ? list[3] : list[2]);
456
- // Z3's builtin_signature_collides and is_transcendental_shadow_decl each make and release fresh variables of the domain.
457
- for (let round = 0; round < 2; round++) {
458
- const vars = domain.map((sort, index) => manager.mkVar(index, sort));
459
- for (const domainVar of vars) manager.incRef(domainVar);
460
- for (const domainVar of vars) manager.decRef(domainVar);
461
- }
462
- funcs.set(expectSymbol(list[1]), manager.mkFuncDecl(expectSymbol(list[1]), domain, range));
3090
+ if (sortDecls.has(symbol.text))
3091
+ throw new SmtParseError("invalid sort declaration, sort already declared/defined", symbol);
3092
+ const arity = list.items[2];
3093
+ if (arity !== undefined && arity.kind !== "numeral")
3094
+ throw new SmtParseError(
3095
+ "invalid sort declaration, arity (<numeral>) or ')' expected",
3096
+ arity,
3097
+ );
3098
+ declare(
3099
+ sortDecls,
3100
+ symbol.text,
3101
+ arity === undefined || arity.text === "0"
3102
+ ? { kind: "sort", sort: manager.mkSort(symbol.text) }
3103
+ : { kind: "user", name: symbol.text, arity: Number(arity.text) },
3104
+ );
3105
+ expectEnd(list.items[3], "invalid sort declaration, ')' expected");
3106
+ return;
3107
+ }
3108
+ if (name === "define-sort") {
3109
+ if (sortDecls.has(symbol.text))
3110
+ throw new SmtParseError("invalid sort definition, sort already declared/defined", symbol);
3111
+ const parameters = parseSortParameters(
3112
+ list.items[2],
3113
+ "invalid sort parameter, symbol or ')' expected",
3114
+ list,
3115
+ );
3116
+ const body = list.items[3] ?? list.end;
3117
+ checkPsort(body, bindTypeParameters(parameters));
3118
+ declare(sortDecls, symbol.text, { kind: "definition", parameters, body });
3119
+ expectEnd(list.items[4], "invalid sort definition, ')' expected");
3120
+ return;
3121
+ }
3122
+ if (name === "define-fun" || name === "define-const") {
3123
+ const isConst = name === "define-const";
3124
+ const bound = isConst
3125
+ ? { names: [], varSorts: [] }
3126
+ : bindSortedVars(list.items[2], list.end, symbol.text);
3127
+ const range = parseSort(
3128
+ list.items[isConst ? 2 : 3] ?? list.end,
3129
+ isConst ? "Invalid constant definition" : "Invalid function definition",
3130
+ );
3131
+ runTerm(list.items[isConst ? 3 : 4] ?? list.end, false);
3132
+ const body = exprStack[exprStack.length - 1];
3133
+ if (!isConst) unbindSortedVars(bound.varSorts.length);
3134
+ const extra = list.items[isConst ? 4 : 5];
3135
+ if (manager.sorts[body] !== range)
3136
+ throw new SmtParseError(
3137
+ isConst
3138
+ ? "invalid constant definition, sort mismatch"
3139
+ : "invalid function/constant definition, sort mismatch",
3140
+ extra ?? list.end,
3141
+ );
3142
+ manager.incRef(body);
3143
+ declare(macros, symbol.text, { domain: bound.varSorts, range, body });
3144
+ defineMacroFunc(symbol.text, bound.varSorts, body);
3145
+ expectEnd(
3146
+ extra,
3147
+ isConst
3148
+ ? "invalid constant definition, ')' expected"
3149
+ : "invalid function/constant definition, ')' expected",
3150
+ );
3151
+ shrinkRefs(exprStack, 0);
3152
+ return;
3153
+ }
3154
+ const domain = name === "declare-fun" ? parseDomain(list.items[2], list) : [];
3155
+ const range = parseSort(
3156
+ list.items[name === "declare-fun" ? 3 : 2] ?? list.end,
3157
+ name === "declare-fun" ? "Invalid function declaration" : "Invalid constant declaration",
3158
+ );
3159
+ // Z3's builtin_signature_collides and is_transcendental_shadow_decl each make and release fresh variables of the domain.
3160
+ for (let round = 0; round < 2; round++) {
3161
+ const vars = domain.map((sort, index) => manager.mkVar(index, sort));
3162
+ for (const domainVar of vars) manager.incRef(domainVar);
3163
+ for (const domainVar of vars) manager.decRef(domainVar);
3164
+ }
3165
+ const decl = manager.mkFuncDecl(symbol.text, domain, range);
3166
+ const extra = list.items[name === "declare-fun" ? 4 : 3];
3167
+ checkDecl(decl, extra ?? list.end);
3168
+ if (macros.has(symbol.text))
3169
+ throw new SmtUnsupportedError(`the overloaded symbol ${symbol.text}`);
3170
+ const existing = funcs.get(symbol.text) ?? [];
3171
+ if (existing.some((other) => hasSignature(other, domain, range)))
3172
+ throw new SmtParseError(
3173
+ `invalid declaration, ${domain.length === 0 ? "constant" : "function"} '${symbol.text}' (with the given signature) already declared`,
3174
+ extra ?? list.end,
3175
+ );
3176
+ declare(funcs, symbol.text, [...existing, decl]);
3177
+ expectEnd(
3178
+ extra,
3179
+ name === "declare-fun"
3180
+ ? "invalid function declaration, ')' expected"
3181
+ : "invalid constant declaration, ')' expected",
3182
+ );
3183
+ };
3184
+
3185
+ // The caller takes the stack's reference. Z3 reports a non-Boolean term at the token after it.
3186
+ const parseFormula = (
3187
+ sexpr: SExpr,
3188
+ follower: SmtPosition,
3189
+ message = "invalid assert command, term is not Boolean",
3190
+ ) => {
3191
+ runTerm(sexpr, false);
3192
+ const assertion = exprStack[exprStack.length - 1];
3193
+ if (manager.sorts[assertion] !== SORT_BOOL) throw new SmtParseError(message, follower);
3194
+ exprStack.pop();
3195
+ return assertion;
3196
+ };
3197
+
3198
+ // An assertion is named when the last name of its term is its own.
3199
+ const parseAssertion = (sexpr: SExpr, follower: SmtPosition) => {
3200
+ releasePending();
3201
+ lastNamed.expr = -1;
3202
+ const formula = parseFormula(sexpr, follower);
3203
+ return { formula, name: lastNamed.expr === formula ? lastNamed.name : undefined };
3204
+ };
3205
+
3206
+ const push = () => {
3207
+ releasePending();
3208
+ scopeStarts.push(undo.length);
3209
+ };
3210
+
3211
+ const pop = () => {
3212
+ releasePending();
3213
+ const start = scopeStarts.pop() ?? 0;
3214
+ for (const restore of undo.splice(start).reverse()) restore();
3215
+ };
3216
+
3217
+ // parser::reset, after an error: Z3 frees its stacks, and with them the terms that only the
3218
+ // command that failed held.
3219
+ const reset = () => {
3220
+ protect(floating);
3221
+ protect(unrooted);
3222
+ releasePending();
3223
+ shrinkRefs(exprStack, 0);
3224
+ if (parsed.expr !== -1) {
3225
+ if (!parsed.isOwned) manager.incRef(parsed.expr);
3226
+ manager.decRef(parsed.expr);
3227
+ parsed.expr = -1;
3228
+ }
3229
+ shrinkRefs(patternStack, 0);
3230
+ shrinkRefs(noPatternStack, 0);
3231
+ locals.clear();
3232
+ shrink(shadowedNames, 0);
3233
+ shrink(shadowedLocals, 0);
3234
+ shrink(localScopes, 0);
3235
+ binders.depth = 0;
3236
+ };
3237
+
3238
+ // cmd_context::set_logic on a manager that is in use: restrict_builtin_sorts takes the sorts the
3239
+ // logic lacks, and the declarations and the operators stay.
3240
+ const restrictSorts = (name: string) => {
3241
+ releasePending();
3242
+ if (logicHasRealsOnly(name)) restricted.isNumeralAsReal = true;
3243
+ if (!ARRAY_EXTENSION_LOGICS.has(name)) restricted.hasSetSort = false;
3244
+ if (INT_FREE_LOGICS.has(name)) sortDecls.delete("Int");
3245
+ restricted.hasFf = FF_LOGICS.has(name);
3246
+ };
3247
+
3248
+ const isUsed = (name: string) => funcs.has(name) || BUILTIN_NAMES.has(name);
3249
+
3250
+ const isClashing = (decl: number) => {
3251
+ const domain = manager.funcDecls[decl].domain;
3252
+ const decls = funcs.get(String(manager.funcDecls[decl].name)) ?? [];
3253
+ return (
3254
+ decls.includes(decl) &&
3255
+ decls.some((other) => other !== decl && hasSignature(other, domain, -1))
3256
+ );
3257
+ };
3258
+
3259
+ // The first declaration of each name, in the slot order of cmd_context's dictionary.
3260
+ const getDeclaredFuncs = () => {
3261
+ const table = new ObjMap<true>((decl) => getSymbolHash(manager.funcDecls[decl].name));
3262
+ for (const decls of funcs.values()) table.set(decls[0], true);
3263
+ return [...table.keys()];
3264
+ };
3265
+
3266
+ // Z3 registers each named term and defined function as a recursive function definition.
3267
+ const hasDefinitions = () =>
3268
+ macros.size > 0 ||
3269
+ [...funcs.values()].some((decls) => decls.some((decl) => manager.recFunDefs.has(decl)));
3270
+
3271
+ return {
3272
+ declareCommand,
3273
+ insertFunc,
3274
+ getFuncs: (name: string) => funcs.get(name) ?? [],
3275
+ hasDefinitions,
3276
+ parseTerm,
3277
+ parseSort: (sexpr: SExpr) => parseSort(sexpr, ""),
3278
+ parseFormula,
3279
+ parseAssertion,
3280
+ getLogicError: logicChecker.checkExpr,
3281
+ push,
3282
+ pop,
3283
+ reset,
3284
+ restrictSorts,
3285
+ isUsed,
3286
+ isClashing,
3287
+ getDeclaredFuncs,
3288
+ };
3289
+ };
3290
+
3291
+ export type SmtlibReader = ReturnType<typeof createSmtlibReader>;
3292
+
3293
+ export const DECLARATIONS = new Set([
3294
+ "declare-sort",
3295
+ "declare-datatypes",
3296
+ "declare-datatype",
3297
+ "declare-fun",
3298
+ "declare-const",
3299
+ "define-fun",
3300
+ "define-const",
3301
+ "define-sort",
3302
+ "define-fun-rec",
3303
+ "define-funs-rec",
3304
+ ]);
3305
+
3306
+ // Z3 reports an error in a command, skips the command and goes on.
3307
+ export const parseSmtlib = (
3308
+ text: string,
3309
+ manager: AstManager,
3310
+ assertExpr: (assertion: number) => void,
3311
+ report: (error: SmtParseError) => void,
3312
+ ): SmtProblem => {
3313
+ const commands = createCommandReader(text);
3314
+ const state = { reader: createSmtlibReader(manager), logic: "", rlimit: 0, isInUse: false };
3315
+ const assertions: number[] = [];
3316
+ const runCommand = (list: SmtList) => {
3317
+ const name = expectSymbol(list.items[0], "invalid command, symbol expected", list).text;
3318
+ const option = list.items[1];
3319
+ const value = list.items[2];
3320
+ if (
3321
+ name === "set-option" &&
3322
+ option?.kind === "keyword" &&
3323
+ option.text === ":rlimit" &&
3324
+ value?.kind === "numeral"
3325
+ )
3326
+ state.rlimit = Number(value.text);
3327
+ if (name === "set-logic") {
3328
+ if (option === undefined)
3329
+ throw new SmtParseError("invalid command, argument(s) missing", list.end);
3330
+ if (!isSymbol(option))
3331
+ throw new SmtParseError("invalid command argument, symbol expected", option);
3332
+ if (value !== undefined)
3333
+ throw new SmtParseError("invalid command, too many arguments", value);
3334
+ if (state.logic !== "") throw new SmtParseError("the logic has already been set", option);
3335
+ if (assertions.length > 0)
3336
+ throw new SmtParseError("logic must be set before initialization", option);
3337
+ if (!isSupportedLogic(option.text)) return;
3338
+ state.logic = option.text;
3339
+ if (state.isInUse) state.reader.restrictSorts(option.text);
3340
+ else state.reader = createSmtlibReader(manager, option.text);
3341
+ } else if (DECLARATIONS.has(name)) {
3342
+ state.isInUse = true;
3343
+ if (name.startsWith("define-"))
3344
+ throw new SmtUnsupportedError(`the command ${name} is not supported`);
3345
+ state.reader.declareCommand(list);
463
3346
  } else if (name === "assert") {
464
- const assertion = expectBool(parseTerm(list[1]));
465
- manager.incRef(assertion);
3347
+ state.isInUse = true;
3348
+ const assertion = state.reader.parseFormula(
3349
+ list.items[1] ?? list.end,
3350
+ list.items[2] ?? list.end,
3351
+ );
3352
+ const logicError = state.reader.getLogicError(assertion);
3353
+ if (logicError !== undefined) {
3354
+ manager.decRef(assertion);
3355
+ throw new SmtParseError(logicError, list.end);
3356
+ }
466
3357
  assertions.push(assertion);
467
3358
  assertExpr(assertion);
468
- } else if (name === "check-sat") {
469
- hasCheckSat = true;
470
- break;
471
- } else if (name === "push" || name === "pop" || name === "define-fun" || name === "define-sort")
3359
+ } else if (name === "push" || name === "pop")
472
3360
  throw new SmtUnsupportedError(`the command ${name} is not supported`);
3361
+ };
3362
+ for (;;) {
3363
+ try {
3364
+ const list = commands.readCommand();
3365
+ if (list === undefined) return { assertions, hasCheckSat: false, rlimit: state.rlimit };
3366
+ if (isSymbol(list.items[0], "check-sat"))
3367
+ return { assertions, hasCheckSat: true, rlimit: state.rlimit };
3368
+ runCommand(list);
3369
+ } catch (error) {
3370
+ if (!(error instanceof SmtParseError)) throw error;
3371
+ report(error);
3372
+ state.reader.reset();
3373
+ commands.skip(report);
3374
+ }
473
3375
  }
474
- return { assertions, hasCheckSat };
475
3376
  };