hsmt (empty) → 0.1.0.0
raw patch · 120 files changed
+19509/−0 lines, 120 filesdep +QuickCheckdep +basedep +containers
Dependencies added: QuickCheck, base, containers, directory, filepath, hsmt, mtl, process, tasty, tasty-hunit, tasty-quickcheck, text, vector
Files
- CHANGELOG.md +86/−0
- LICENSE +29/−0
- README.md +343/−0
- app/Main.hs +100/−0
- bench/Main.hs +114/−0
- bench/smtlib/QF_ABV/memory_copy.smt2 +14/−0
- bench/smtlib/QF_ALIA/storecomm10_unsat.smt2 +29/−0
- bench/smtlib/QF_ALIA/storecomm6_sat.smt2 +21/−0
- bench/smtlib/QF_ALIA/storecomm6_unsat.smt2 +21/−0
- bench/smtlib/QF_ALIA/swap.smt2 +11/−0
- bench/smtlib/QF_AUF/extensionality.smt2 +13/−0
- bench/smtlib/QF_BV/factor_143.smt2 +15/−0
- bench/smtlib/QF_BV/factor_32bit.smt2 +12/−0
- bench/smtlib/QF_BV/factor_prime_251.smt2 +13/−0
- bench/smtlib/QF_BV/hd_add_decomposition.smt2 +10/−0
- bench/smtlib/QF_BV/hd_average.smt2 +12/−0
- bench/smtlib/QF_BV/hd_average32.smt2 +11/−0
- bench/smtlib/QF_BV/hd_lowest_bit.smt2 +10/−0
- bench/smtlib/QF_BV/hd_xor_or_and.smt2 +10/−0
- bench/smtlib/QF_BV/inverse_mod_2_16.smt2 +9/−0
- bench/smtlib/QF_BV/let_sum.smt2 +11/−0
- bench/smtlib/QF_BV/mul_commutes16.smt2 +9/−0
- bench/smtlib/QF_BV/rotations.smt2 +12/−0
- bench/smtlib/QF_BV/signed_division.smt2 +12/−0
- bench/smtlib/QF_BVFP/int_conversion.smt2 +12/−0
- bench/smtlib/QF_DT/points.smt2 +13/−0
- bench/smtlib/QF_FP/non_associative.smt2 +11/−0
- bench/smtlib/QF_FP/point_one.smt2 +10/−0
- bench/smtlib/QF_FP/square_nonnegative.smt2 +8/−0
- bench/smtlib/QF_FP/x_plus_one.smt2 +9/−0
- bench/smtlib/QF_LIA/diophantine.smt2 +12/−0
- bench/smtlib/QF_LIA/div_mod.smt2 +15/−0
- bench/smtlib/QF_LIA/magic_square3.smt2 +33/−0
- bench/smtlib/QF_LIA/magic_square3_wrong_sum.smt2 +33/−0
- bench/smtlib/QF_LIA/parity.smt2 +10/−0
- bench/smtlib/QF_LIA/queens8.smt2 +79/−0
- bench/smtlib/QF_LIA/schedule6_short.smt2 +35/−0
- bench/smtlib/QF_LIA/schedule6_tight.smt2 +35/−0
- bench/smtlib/QF_S/conjugate_words.smt2 +10/−0
- bench/smtlib/QF_S/no_conjugate.smt2 +8/−0
- bench/smtlib/QF_S/replace_contains.smt2 +11/−0
- bench/smtlib/QF_SLIA/digits.smt2 +12/−0
- bench/smtlib/QF_SLIA/from_int_roundtrip.smt2 +9/−0
- bench/smtlib/QF_SLIA/regex_dates.smt2 +25/−0
- bench/smtlib/QF_SLIA/regex_even_length.smt2 +11/−0
- bench/smtlib/QF_SLIA/regex_last_char.smt2 +10/−0
- bench/smtlib/QF_SLIA/regex_password.smt2 +16/−0
- bench/smtlib/QF_SLIA/split_email.smt2 +19/−0
- bench/smtlib/QF_UF/congruence_chain.smt2 +18/−0
- bench/smtlib/QF_UF/eq_diamond10.smt2 +49/−0
- bench/smtlib/QF_UF/eq_diamond100.smt2 +409/−0
- bench/smtlib/QF_UF/eq_diamond30.smt2 +129/−0
- bench/smtlib/QF_UF/latin_square_bool4.smt2 +377/−0
- bench/smtlib/QF_UF/pigeonhole_bool7.smt2 +266/−0
- bench/smtlib/QF_UF/pigeonhole_bool8.smt2 +375/−0
- bench/smtlib/QF_UF/pigeonhole_uf5.smt2 +42/−0
- bench/smtlib/QF_UFLIA/array_like.smt2 +12/−0
- bench/smtlib/QF_UFLIA/monotone.smt2 +13/−0
- bench/smtlib/incremental/bounded_counter.smt2 +26/−0
- bench/smtlib/incremental/bv_sessions.smt2 +26/−0
- bench/smtlib/incremental/scoped_declarations.smt2 +30/−0
- hsmt.cabal +166/−0
- src/HSMT.hs +70/−0
- src/HSMT/API/Expr.hs +873/−0
- src/HSMT/API/Model.hs +46/−0
- src/HSMT/API/Monad.hs +250/−0
- src/HSMT/API/Sort.hs +261/−0
- src/HSMT/Backend.hs +52/−0
- src/HSMT/Backend/External.hs +770/−0
- src/HSMT/Core/Eval.hs +376/−0
- src/HSMT/Core/Expr.hs +37/−0
- src/HSMT/Core/Float.hs +467/−0
- src/HSMT/Core/Op.hs +295/−0
- src/HSMT/Core/Regex.hs +445/−0
- src/HSMT/Core/Sort.hs +68/−0
- src/HSMT/Core/Term.hs +117/−0
- src/HSMT/Core/Typing.hs +259/−0
- src/HSMT/Core/Value.hs +198/−0
- src/HSMT/SAT/Dimacs.hs +56/−0
- src/HSMT/SAT/Solver.hs +919/−0
- src/HSMT/SAT/Types.hs +133/−0
- src/HSMT/SMT/Engine.hs +2260/−0
- src/HSMT/SMTLib/Parser.hs +565/−0
- src/HSMT/SMTLib/Printer.hs +394/−0
- src/HSMT/SMTLib/Run.hs +281/−0
- src/HSMT/SMTLib/Syntax.hs +81/−0
- src/HSMT/Theory/Arith.hs +341/−0
- src/HSMT/Theory/Arith/Simplex.hs +366/−0
- src/HSMT/Theory/BitBlast.hs +401/−0
- src/HSMT/Theory/EUF.hs +570/−0
- src/HSMT/Theory/FloatBlast.hs +732/−0
- src/HSMT/Tutorial.hs +336/−0
- src/HSMT/Util/GrowVec.hs +181/−0
- test-common/HSMT/Benchmarks.hs +64/−0
- test-common/HSMT/Gen/Expr.hs +625/−0
- test-diff/Differential/Oracle.hs +516/−0
- test-diff/Differential/Z3.hs +56/−0
- test-diff/Main.hs +159/−0
- test/HSMT/APISpec.hs +205/−0
- test/HSMT/ArraySpec.hs +107/−0
- test/HSMT/BVSpec.hs +97/−0
- test/HSMT/EUFSpec.hs +325/−0
- test/HSMT/EvalSpec.hs +143/−0
- test/HSMT/FloatSpec.hs +182/−0
- test/HSMT/IncrementalSpec.hs +229/−0
- test/HSMT/LIASpec.hs +159/−0
- test/HSMT/RecordSpec.hs +104/−0
- test/HSMT/RegexSpec.hs +177/−0
- test/HSMT/RegressionSpec.hs +93/−0
- test/HSMT/SATSpec.hs +167/−0
- test/HSMT/SMTLibSpec.hs +189/−0
- test/HSMT/StringSpec.hs +95/−0
- test/HSMT/TutorialSpec.hs +167/−0
- test/Main.hs +60/−0
- test/regressions/euf-pigeonhole-bv1.smt2 +13/−0
- test/regressions/incremental-constant-bool-record.smt2 +14/−0
- test/regressions/incremental-constant-bool-store-bv.smt2 +9/−0
- test/regressions/incremental-constant-bool-store-uf.smt2 +13/−0
- test/regressions/z3-finite-index-array-eq.smt2 +18/−0
- test/regressions/z3-finite-record-index-array-eq.smt2 +12/−0
+ CHANGELOG.md view
@@ -0,0 +1,86 @@+# Revision history for hsmt++## 0.1.0.0 -- unreleased++* Core term language: sorts, operators, dynamic sort checking, hash-consing.+* Reference evaluator implementing SMT-LIB semantics for integers,+ bit-vectors, arrays, strings and records.+* Type-safe API (`HSMT`): type-level sorts, records with labels,+ uninterpreted functions, typed models, push/pop.+* CDCL SAT solver with DPLL(T) hooks, assumptions and failed-assumption cores.+* DPLL(T) engine with Tseitin encoding and model validation.+* EUF theory: congruence closure with explanations and transitivity lemmas.+* SMT-LIB 2 printer, parser and script runner; the `hsmt` executable+ accepts `.smt2` files.+* Differential test suite against Z3 (`hsmt-diff`): results, models,+ incremental sequences and ground-term semantics; divergences are saved as+ `.smt2` regressions replayed by `hsmt-test`.+* Linear integer arithmetic: general simplex with backtrackable bounds,+ branch-and-bound and Gomory cuts; division and remainder by literals,+ `abs`, and division by zero as an uninterpreted function.+* Model-based combination of EUF and LIA.+* Bit-vectors by bit-blasting, with SMT-LIB semantics for division by zero,+ and model-based combination with EUF.+* Arrays: read-over-write and constant-array axioms instantiated on demand,+ extensionality with fresh indices, default values for infinite index sorts+ and full expansion of small finite index sorts; nested arrays, arrays as+ arguments of uninterpreted functions, and array models.+* Simplex only inspects basic variables whose value or bounds changed; EUF+ checks disequalities only when one of their sides changes class.+* Records as single-constructor datatypes in congruence closure: selection+ axioms, eta axioms (`r = mk(get_f1 r, ...)`) and functional update; record+ fields of every supported sort, nested records, records in arrays and as+ array indices, records as arguments and results of uninterpreted functions.+* Strings (without regular expressions): bounded encoding with an integer+ length and 18-bit characters per string term; constraints are valid for+ strings of any length, so refutations that do not use the length bound are+ proofs, and the bound grows from 8 up to 32 characters before answering+ `unknown`. All SMT-LIB string operators of the core: concatenation,+ `len`, `at`, `substr`, `contains`, `prefixof`, `suffixof`, `indexof`,+ `replace`, `to_int`, `from_int`, `<` and `<=`; ground string terms are+ evaluated.+* Incremental solving: each solver instance keeps one engine session across+ checks (terms, clauses, learnt clauses and theory lemmas are reused);+ formulas are SAT assumptions, so `push`/`pop` only change which formulas+ are assumed.+* Unsatisfiable cores (`Unsat (Core ctx)`, `coreAssertions`,+ `coreAssumptions`), optionally minimal (`cfgMinimizeCores`), and+ `checkSatAssuming`.+* Resource limits per check: `cfgTimeout` (milliseconds) and+ `cfgConflictLimit`.+* SMT-LIB: named assertions, `check-sat-assuming`, `get-unsat-core`, and the+ options `:timeout` and `:smt.core.minimize`.+* Floating point (SMT-LIB `FloatingPoint` theory) by bit-blasting: every+ format, the five rounding modes, arithmetic, `fma`, `sqrt`, `rem`,+ `roundToIntegral`, `min`/`max`, comparisons, classification, `fp`, and+ conversions between formats and to and from bit-vectors; unspecified+ results are functions of their arguments. Exact reference semantics in+ `HSMT.Core.Float`; typed API with `'FPS eb sb`, `'RoundingModeS`,+ `Float16S`/`Float32S`/`Float64S` and `FloatingPoint` values.+* SMT-LIB front end: `let`, `define-sort`, `define-const`, scoped+ declarations (`pop` removes them), `reset`, `reset-assertions`,+ `get-model`, `get-value`, `get-assertions`, `get-info`, `get-option`,+ `:print-success`, and `bvnand`, `bvnor`, `bvxnor`, `bvcomp`, `rotate_left`,+ `rotate_right` and `repeat`. Scripts run command by command+ (`runScriptWith`): an error answers `(error ...)` and the script goes on.+* The `hsmt` executable reads the standard input and accepts `--timeout`,+ `--minimize-cores`, `--validate`, `--help` and `--version`.+* Benchmarks in `bench/smtlib` with `:status` annotations, checked by the+ test suite; `cabal bench` compares answers and times with Z3.+* Haddock for every module and a tutorial (`HSMT.Tutorial`) whose examples+ are tested.+* Regular expressions (SMT-LIB `RegLan`): `str.to_re`, `str.in_re`, `re.none`,+ `re.all`, `re.allchar`, `re.++`, `re.union`, `re.inter`, `re.*`, `re.+`,+ `re.opt`, `re.range`, `re.comp`, `re.diff`, `re.loop` and `re.^`, for+ ground expressions. Reference semantics by Brzozowski derivatives+ (`HSMT.Core.Regex`); membership is encoded by running the automaton of the+ expression over the bounded string encoding, with length lemmas and+ lemmas from the relations between the languages of atoms on the same+ string. Typed API: `'RegLanS`, `toRe`, `inRe`, `reConcat`, `reUnion`...+* External backend (`HSMT.Backend`, `HSMT.Backend.External`): `cfgBackend`+ selects the Haskell engine or an external solver process (`z3Backend`,+ or any `ExternalSolver`) behind the same API and SMT-LIB runner; answers,+ cores and models (read from `get-model` and `get-value`) come back as+ with the engine. The executable takes `--solver=CMD`. The API,+ incremental and SMT-LIB file tests also run with Z3, and `hsmt-diff`+ compares both backends through the API.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, rodrigogribeiro+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,343 @@+# hsmt++hsmt is an SMT solver written in Haskell. You can use it as a library, with+a type-safe embedded API, or as a command-line tool that reads SMT-LIB 2.6+scripts.++An SMT (Satisfiability Modulo Theories) solver decides whether a formula+over theories such as integers, bit-vectors, arrays or strings has a+solution, and gives one when it does. With hsmt, formulas are ordinary+Haskell values. Expressions carry their sort in their type, so ill-sorted+formulas do not compile. Examples are comparing an integer with a string,+adding bit-vectors of different widths, or reading a field that a record+does not have.++Highlights:++- A CDCL SAT solver with theory hooks (DPLL(T)), entirely in Haskell+- Decision procedures for uninterpreted functions, linear integer+ arithmetic, bit-vectors, arrays, records, strings, regular expressions+ and IEEE 754 floating point+- Incremental solving: `push`/`pop`, checks under assumptions, and+ unsatisfiable cores (optionally minimal)+- Models that evaluate any expression, validated by an independent+ evaluator+- The same API can drive an external solver (such as Z3) instead of the+ built-in engine+- An `hsmt` executable for SMT-LIB 2.6 scripts and DIMACS CNF files++## Installation++Add `hsmt` to the `build-depends` of your package:++```cabal+build-depends: hsmt+```++To install the command-line tool:++```+cabal install hsmt+```++## Quick start++```haskell+{-# LANGUAGE DataKinds, LambdaCase, TypeApplications #-}+import HSMT++main :: IO ()+main = do+ r <- runSMT defaultConfig $ do+ x <- declare @IntS "x"+ y <- declare @IntS "y"+ assert (x + y .== 10)+ assert (x - y .== 4)+ checkSat >>= \case+ Sat m -> pure (Just (eval m x, eval m y))+ _ -> pure Nothing+ print r -- Just (7,3)+```++Every program follows the same steps:++1. `runSMT` starts a solver instance with a `Config`.+ `defaultConfig` is a good starting point.+2. `declare` introduces a constant of a sort. You choose the sort with a+ type application (`@IntS`, `@BoolS`, `@(BVS 8)`, ...).+3. `assert` adds a Boolean expression to the assertions.+4. `checkSat` returns one of three results:+ - `Sat` with a model+ - `Unsat` with an unsatisfiable core+ - `Unknown` with the reason the solver gave up+5. `eval` evaluates any expression under a model and returns a Haskell+ value (`Integer`, `Bool`, `Text`, `BitVector n`, ...).++Like `ST`, `runSMT` is rank 2. Expressions and models therefore cannot+escape their solver instance or be mixed between instances.++## Examples++The examples below use these extensions and imports:++```haskell+{-# LANGUAGE DataKinds, LambdaCase, OverloadedLabels, OverloadedStrings, TypeApplications #-}+import Data.Text (Text)+import HSMT+```++### Booleans++```haskell+-- p or q, and not p: q must be true.+booleans :: IO (Maybe Bool)+booleans = runSMT defaultConfig $ do+ p <- declare @BoolS "p"+ q <- declare @BoolS "q"+ assert (p .|| q)+ assert (notB p)+ checkSat >>= \case+ Sat m -> pure (Just (eval m q))+ _ -> pure Nothing+-- Just True+```++### Proving a property (unsatisfiability)++To prove that a property always holds, assert its negation and check that+the result is `Unsat`:++```haskell+-- Swapping two elements of an array twice gives the array back.+swapTwice :: IO Bool+swapTwice = runSMT defaultConfig $ do+ a <- declare @(ArrayS IntS IntS) "a"+ i <- declare @IntS "i"+ j <- declare @IntS "j"+ let swap b = store (store b i (select b j)) j (select b i)+ assert (swap (swap a) ./= a)+ checkSat >>= \case+ Unsat _ -> pure True+ _ -> pure False+-- True+```++### Bit-vectors++```haskell+-- x & (x - 1) is zero only for powers of two (and zero).+-- Find a power of two between 1000 and 2000.+powerOfTwo :: IO (Maybe (BitVector 16))+powerOfTwo = runSMT defaultConfig $ do+ x <- declare @(BVS 16) "x"+ assert (bvAnd x (x - 1) .== 0)+ assert (bvUGt x 1000)+ assert (bvULt x 2000)+ checkSat >>= \case+ Sat m -> pure (Just (eval m x))+ _ -> pure Nothing+-- Just (BitVector 1024)+```++### Strings and regular expressions++```haskell+-- An identifier of 3 to 5 characters that contains a 9 and is not a keyword.+identifier :: IO (Maybe Text)+identifier = runSMT defaultConfig $ do+ s <- declare @StringS "s"+ let letter = reUnion [reRange 'a' 'z', reRange 'A' 'Z']+ ident = reConcat [letter, reStar (reUnion [letter, reRange '0' '9'])]+ assert (inRe s (reInter [ident, reLoop 3 5 reAllChar]))+ assert (notB (inRe s (reUnion ["else", "then"])))+ assert (contains s "9")+ checkSat >>= \case+ Sat m -> pure (Just (eval m s))+ _ -> pure Nothing+-- for example, Just "a9b"+```++### Uninterpreted functions++```haskell+-- f(f(f(a))) = a and f(f(f(f(f(a))))) = a imply f(a) = a.+congruence :: IO Bool+congruence = runSMT defaultConfig $ do+ f <- declareFun @'[UninterpS "U"] @(UninterpS "U") "f"+ a <- declare @(UninterpS "U") "a"+ assert (f (f (f a)) .== a)+ assert (f (f (f (f (f a)))) .== a)+ assert (f a ./= a)+ checkSat >>= \case+ Unsat _ -> pure True+ _ -> pure False+-- True+```++### Records++```haskell+type Point = RecordS '[ '("x", IntS), '("y", IntS)]++reflection :: IO (Maybe (Integer, Integer))+reflection = runSMT defaultConfig $ do+ p <- declare @Point "p"+ let q = record (#x := p ! #y :& #y := p ! #x :& FNil)+ assert (q .== setField #x 3 p)+ assert (p ! #x .> 0)+ checkSat >>= \case+ Sat m -> pure (Just (field #x (eval m p), field #y (eval m p)))+ _ -> pure Nothing+-- Just (3,3)+```++### Floating point++```haskell+-- A float that is not equal to itself must be NaN.+notReflexive :: IO (Maybe Bool)+notReflexive = runSMT defaultConfig $ do+ x <- declare @Float32S "x"+ assert (notB (fpEq x x))+ checkSat >>= \case+ Sat m -> pure (Just (isNaN (toFloat (eval m x))))+ _ -> pure Nothing+-- Just True+```++### Incremental solving++`push` opens a scope of assertions and `pop` discards it. `scoped` does+both around an action. `checkSatAssuming` checks the assertions together+with formulas that hold only for that check. With `cfgMinimizeCores`, the+unsatisfiable core is minimal:++```haskell+-- Which constraints conflict?+conflicting :: IO [Int]+conflicting = runSMT defaultConfig {cfgMinimizeCores = True} $ do+ x <- declare @IntS "x"+ labels <- mapM (\i -> declare @BoolS ("c" <> T.pack (show i))) [0 .. 3 :: Int]+ let constraints = [x .> 10, x .< 20, x .== 5, x .> 0]+ sequence_ [assert (l .=> c) | (l, c) <- zip labels constraints]+ checkSatAssuming labels >>= \case+ Unsat core -> pure [i | (i, l) <- zip [0 ..] labels, l `elem` coreAssumptions core]+ _ -> pure []+-- [0,2]: x > 10 and x = 5 conflict+```++This example also needs `import qualified Data.Text as T`.++You can bound hard problems with `cfgTimeout` (milliseconds per check) and+`cfgConflictLimit`. A check that reaches a limit answers `Unknown`, and the+instance stays usable.++## Theories++- Booleans, uninterpreted functions and sorts (congruence closure)+- Linear integer arithmetic (simplex, branch and bound, cuts)+- Bit-vectors (bit-blasting)+- Arrays (lazy axiom instantiation, extensionality)+- Records (single-constructor datatypes)+- Strings (bounded encoding), with ground regular expressions (automata)+- Floating point, IEEE 754 in every format and rounding mode (bit-blasting)++## External solvers++The same API can drive an external SMT solver over SMT-LIB instead of the+Haskell engine. hsmt reads models back, so `eval` works unchanged:++```haskell+viaZ3 :: IO (Maybe (Integer, Integer))+viaZ3 = runSMT defaultConfig {cfgBackend = External z3Backend} $ do+ x <- declare @IntS "x"+ y <- declare @IntS "y"+ assert (x * y .== 12 .&& x .> y .&& y .> 1) -- nonlinear: needs Z3+ checkSat >>= \case+ Sat m -> pure (Just (eval m x, eval m y))+ _ -> pure Nothing+-- Just (6,2) or Just (4,3)+```++hsmt finds Z3 through the `HSMT_Z3` environment variable or the `PATH`.+To use another solver, describe it with an `ExternalSolver` (executable,+arguments, dialect and logic).++## Command line++The `hsmt` executable reads SMT-LIB 2.6 scripts. Given `example.smt2`:++```smt2+(set-logic QF_LIA)+(declare-const x Int)+(declare-const y Int)+(assert (= (+ x y) 10))+(assert (= (- x y) 4))+(check-sat)+(get-value (x y))+```++```+$ hsmt example.smt2+sat+((x 7)+ (y 3))+```++Other ways to run it:++```+$ hsmt --timeout=5000 < problem.smt2+$ hsmt problem.cnf # DIMACS CNF+$ hsmt --solver=z3 problem.smt2 # checks decided by Z3+```++Supported SMT-LIB features:++- Declarations and definitions, including `define-sort`, `define-const`+ and single-constructor datatypes+- `let` and named assertions+- `push`, `pop` and `reset`+- `check-sat-assuming`+- `get-model`, `get-value`, `get-assertions`, `get-unsat-core`,+ `get-info` and `get-option`+- `:print-success`++Errors answer `(error ...)` and the script goes on. With `--solver`, the+external solver decides the checks and hsmt answers the other commands.++## Documentation++The module `HSMT.Tutorial` is a tutorial. It covers every theory, models,+incremental solving, external solvers and the SMT-LIB front end. All its+examples are part of the test suite.++## Testing++```+cabal test hsmt-test # unit tests, properties, regressions, benchmarks+cabal test hsmt-diff # differential tests against Z3 (skipped without z3)+cabal bench # bench/smtlib with hsmt and Z3: answers and times+```++`hsmt-diff` generates random problems and incremental sequences for every+theory. It compares answers, models and unsatisfiable cores with Z3, and it+runs sequences through the API with both backends. Each property passed+10,000 cases without divergences. When Z3 is available, `hsmt-test` also+runs the API, incremental and SMT-LIB file tests with the Z3 backend.++## Limitations++- Integer arithmetic must be linear. Other products and divisions answer+ `Unknown`; use an external solver for them.+- Strings are decided for bounded lengths, so some unsatisfiable string+ problems answer `unknown`.+- Regular expressions must be ground (they cannot depend on variables).+- Quantifiers, real numbers and general algebraic datatypes are not+ supported.+- Bit-vectors and floating point are bit-blasted, so wide multiplications+ and divisions can be slow.++## License++BSD-3-Clause. See [LICENSE](https://github.com/rodrigogribeiro/hsmt/blob/main/LICENSE).
+ app/Main.hs view
@@ -0,0 +1,100 @@+{-# LANGUAGE MultiWayIf #-}++module Main (main) where++import Data.List (isSuffixOf, stripPrefix)+import qualified Data.Text as T+import qualified Data.Text.IO as T+import Data.Version (showVersion)+import System.Environment (getArgs)+import System.Exit (exitFailure)+import System.IO (BufferMode (..), hPutStrLn, hSetBuffering, stderr, stdout)+import Text.Read (readMaybe)++import HSMT.Backend (Backend (..), solverFromCommand)+import HSMT.SAT.Dimacs+import HSMT.SAT.Solver+import HSMT.SAT.Types+import HSMT.SMT.Engine (CheckOptions (..), defaultCheckOptions)+import HSMT.SMTLib.Run (renderResponse, runScriptWithBackend)+import qualified Paths_hsmt as Paths++usage :: String+usage =+ unlines+ [ "usage: hsmt [OPTION]... [FILE]"+ , ""+ , "Solve an SMT-LIB 2.6 script, or a DIMACS CNF file (FILE.cnf). Without FILE,"+ , "or with FILE = -, the script is read from the standard input."+ , ""+ , " -t MS, --timeout=MS time limit of each check-sat, in milliseconds"+ , " --minimize-cores minimize unsatisfiable cores (:smt.core.minimize)"+ , " --validate check every model against the assertions"+ , " --solver=CMD decide the checks with an external solver (for"+ , " example --solver=z3, or --solver='cvc5 --incremental'),"+ , " reading its models back; z3 is found through HSMT_Z3"+ , " or the PATH"+ , " -h, --help show this help"+ , " --version show the version"+ ]++data Options = Options+ { optCheck :: CheckOptions+ , optBackend :: Backend+ , optFile :: Maybe FilePath+ }++parseArgs :: Options -> [String] -> Either String Options+parseArgs o = \case+ [] -> Right o+ ("-t" : ms : rest) -> timeout ms >>= \o' -> parseArgs o' rest+ ("--solver" : cmd : rest) -> solver cmd >>= \o' -> parseArgs o' rest+ (arg : rest)+ | Just ms <- stripPrefix "--timeout=" arg -> timeout ms >>= \o' -> parseArgs o' rest+ | Just cmd <- stripPrefix "--solver=" arg -> solver cmd >>= \o' -> parseArgs o' rest+ | arg == "--minimize-cores" -> parseArgs (check (\c -> c {coMinimizeCore = True})) rest+ | arg == "--validate" -> parseArgs (check (\c -> c {coValidate = True})) rest+ | arg == "-" || take 1 arg /= "-" -> case optFile o of+ Nothing -> parseArgs o {optFile = if arg == "-" then Nothing else Just arg} rest+ Just _ -> Left "more than one input file"+ | otherwise -> Left ("unknown option: " <> arg)+ where+ check f = o {optCheck = f (optCheck o)}+ solver cmd = case solverFromCommand (words cmd) of+ Just s -> Right o {optBackend = External s}+ Nothing -> Left "empty solver command"+ timeout ms = case readMaybe ms :: Maybe Integer of+ Just n | n > 0 -> Right (check (\c -> c {coTimeout = Just (fromInteger n / 1000)}))+ _ -> Left ("invalid timeout: " <> ms)++main :: IO ()+main = do+ hSetBuffering stdout LineBuffering+ args <- getArgs+ if+ | any (`elem` ["-h", "--help"]) args -> putStr usage+ | "--version" `elem` args -> putStrLn ("hsmt " <> showVersion Paths.version)+ | otherwise -> case parseArgs (Options defaultCheckOptions Native Nothing) args of+ Left err -> hPutStrLn stderr ("hsmt: " <> err) >> hPutStr' usage >> exitFailure+ Right o -> case optFile o of+ Just path | ".cnf" `isSuffixOf` path -> T.readFile path >>= dimacs+ Just path -> T.readFile path >>= smtlib o+ Nothing -> T.getContents >>= smtlib o+ where+ hPutStr' = hPutStrLn stderr++-- | Run a script, printing each response as soon as it is known.+smtlib :: Options -> T.Text -> IO ()+smtlib o = runScriptWithBackend (optBackend o) (optCheck o) (T.putStrLn . renderResponse)++dimacs :: T.Text -> IO ()+dimacs txt = case parseDimacs txt of+ Left err -> putStrLn ("error: " <> err) >> exitFailure+ Right cnf -> do+ s <- newSolver+ ok <- loadCnf s cnf+ r <- if ok then solve s else pure Unsat+ putStrLn $ case r of+ Sat -> "s SATISFIABLE"+ Unsat -> "s UNSATISFIABLE"+ Unknown -> "s UNKNOWN"
+ bench/Main.hs view
@@ -0,0 +1,114 @@+-- | Runs the SMT-LIB benchmarks in @bench/smtlib@ with hsmt and, when it+-- is available (through @HSMT_Z3@ or the @PATH@), with Z3, and prints the+-- answers and times of both.+--+-- > cabal bench --benchmark-options='--timeout=30 QF_BV'+--+-- Options: @--timeout=SECS@ (per check for hsmt, per file for Z3; default+-- 10) and substrings that select files. hsmt runs in this process and Z3+-- as a separate one, so Z3 times include starting it (a few+-- milliseconds). The program fails when hsmt gives an answer that+-- contradicts the @:status@ annotation of a file.+module Main (main) where++import Control.Exception (SomeException, evaluate, try)+import Data.IORef+import Data.List (isInfixOf, isPrefixOf, stripPrefix)+import Data.Maybe (fromMaybe, mapMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.IO as T+import GHC.Clock (getMonotonicTime)+import System.Directory (findExecutable)+import System.Environment (getArgs, lookupEnv)+import System.Exit (exitFailure)+import System.FilePath ((</>))+import System.IO (BufferMode (..), hSetBuffering, stdout)+import System.Process (readProcessWithExitCode)+import System.Timeout (timeout)+import Text.Printf (printf)+import Text.Read (readMaybe)++import HSMT.Benchmarks+import HSMT.SMT.Engine (CheckOptions (..), defaultCheckOptions)+import HSMT.SMTLib.Run++data Run = Run+ { runAnswers :: [Text]+ , runSeconds :: Double+ }++main :: IO ()+main = do+ hSetBuffering stdout LineBuffering+ args <- getArgs+ let secs = fromMaybe 10 (mapMaybe (\a -> stripPrefix "--timeout=" a >>= readMaybe) args `at` 0)+ filters = filter (not . ("--" `isPrefixOf`)) args+ files <- filter (\f -> null filters || any (`isInfixOf` f) filters) <$> benchmarkFiles+ z3 <- lookupEnv "HSMT_Z3" >>= maybe (findExecutable "z3") (pure . Just)+ printf "%-42s %-24s %-24s %8s %-24s %8s\n" ("benchmark" :: String) ("expected" :: String) ("hsmt" :: String) ("" :: String) (maybe "z3 (absent)" (const "z3") z3 :: String) ("" :: String)+ rows <- mapM (bench secs z3) files+ let checks = concat [zip e (runAnswers h) | (e, h, _) <- rows]+ wrong = length [() | (e, a) <- checks, a `elem` ["sat", "unsat"], e `elem` ["sat", "unsat"], a /= e]+ solved = length [() | (e, a) <- checks, a == e]+ z3Solved = length [() | (e, _, Just z) <- rows, (x, a) <- zip e (runAnswers z), x == a]+ total f = sum [runSeconds (f r) | r <- rows]+ printf "\n%d files, %d checks\n" (length rows) (length checks)+ printf "hsmt: %d solved, %d wrong, %.2f s in total\n" solved wrong (total (\(_, h, _) -> h))+ case z3 of+ Just _ -> printf "z3: %d solved, %.2f s in total\n" z3Solved (total (\(_, _, z) -> maybe (Run [] 0) id z))+ Nothing -> pure ()+ if wrong > 0 then exitFailure else pure ()+ where+ at xs i = if length xs > i then Just (xs !! i) else Nothing++bench :: Double -> Maybe FilePath -> FilePath -> IO ([Text], Run, Maybe Run)+bench secs z3 file = do+ txt <- T.readFile (benchmarkDir </> file)+ let expected = expectedStatuses txt+ h <- runHsmt secs txt+ z <- traverse (\exe -> runZ3 secs exe (benchmarkDir </> file)) z3+ let mark :: Run -> String+ mark r = if runAnswers r == expected then " " else "*"+ printf+ "%-42s %-24s %-24s %7.2fs%s %-24s %s\n"+ file+ (T.unpack (T.unwords expected))+ (T.unpack (T.unwords (runAnswers h)))+ (runSeconds h)+ (mark h)+ (maybe "" (T.unpack . T.unwords . runAnswers) z)+ (maybe "" (\r -> printf "%7.2fs%s" (runSeconds r) (mark r)) z :: String)+ pure (expected, h, z)++runHsmt :: Double -> Text -> IO Run+runHsmt secs txt = do+ out <- newIORef []+ start <- getMonotonicTime+ let opts = defaultCheckOptions {coTimeout = Just secs}+ record = \case+ CheckResult r -> modifyIORef' out (answerText r :)+ CommandError e -> modifyIORef' out (("error: " <> e) :)+ _ -> pure ()+ r <- try (runScriptWith opts (\x -> record x >> evaluate ()) txt)+ end <- getMonotonicTime+ answers <- reverse <$> readIORef out+ pure $ case r of+ Left (e :: SomeException) -> Run (answers <> ["crash: " <> T.pack (show e)]) (end - start)+ Right () -> Run (map short answers) (end - start)+ where+ short a = if "error" `T.isPrefixOf` a then "error" else a++runZ3 :: Double -> FilePath -> FilePath -> IO Run+runZ3 secs exe file = do+ start <- getMonotonicTime+ r <- timeout (round ((secs + 5) * 1e6)) (readProcessWithExitCode exe ["-T:" <> show (ceiling secs :: Int), file] "")+ end <- getMonotonicTime+ let answers = case r of+ Nothing -> ["timeout"]+ Just (_, out, _) ->+ [ if "(error" `T.isPrefixOf` l then "error" else l+ | l <- T.lines (T.pack out)+ , any (`T.isPrefixOf` l) ["sat", "unsat", "unknown", "timeout", "(error"]+ ]+ pure (Run answers (end - start))
+ bench/smtlib/QF_ABV/memory_copy.smt2 view
@@ -0,0 +1,14 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_ABV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const m (Array (_ BitVec 8) (_ BitVec 8)))+(declare-const src (_ BitVec 8))+(declare-const dst (_ BitVec 8))+(define-fun m1 () (Array (_ BitVec 8) (_ BitVec 8)) (store m dst (select m src)))+(define-fun m2 () (Array (_ BitVec 8) (_ BitVec 8)) (store m1 (bvadd dst #x01) (select m1 (bvadd src #x01))))+(assert (bvult src #x10))+(assert (bvuge dst #x20))+(assert (not (= (select m2 (bvadd dst #x01)) (select m (bvadd src #x01)))))+(check-sat)+(exit)
+ bench/smtlib/QF_ALIA/storecomm10_unsat.smt2 view
@@ -0,0 +1,29 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_ALIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const a (Array Int Int))+(declare-const i0 Int)+(declare-const e0 Int)+(declare-const i1 Int)+(declare-const e1 Int)+(declare-const i2 Int)+(declare-const e2 Int)+(declare-const i3 Int)+(declare-const e3 Int)+(declare-const i4 Int)+(declare-const e4 Int)+(declare-const i5 Int)+(declare-const e5 Int)+(declare-const i6 Int)+(declare-const e6 Int)+(declare-const i7 Int)+(declare-const e7 Int)+(declare-const i8 Int)+(declare-const e8 Int)+(declare-const i9 Int)+(declare-const e9 Int)+(assert (distinct i0 i1 i2 i3 i4 i5 i6 i7 i8 i9))+(assert (not (= (store (store (store (store (store (store (store (store (store (store a i0 e0) i1 e1) i2 e2) i3 e3) i4 e4) i5 e5) i6 e6) i7 e7) i8 e8) i9 e9) (store (store (store (store (store (store (store (store (store (store a i9 e9) i8 e8) i7 e7) i6 e6) i5 e5) i4 e4) i3 e3) i2 e2) i1 e1) i0 e0))))+(check-sat)+(exit)
+ bench/smtlib/QF_ALIA/storecomm6_sat.smt2 view
@@ -0,0 +1,21 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_ALIA)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const a (Array Int Int))+(declare-const i0 Int)+(declare-const e0 Int)+(declare-const i1 Int)+(declare-const e1 Int)+(declare-const i2 Int)+(declare-const e2 Int)+(declare-const i3 Int)+(declare-const e3 Int)+(declare-const i4 Int)+(declare-const e4 Int)+(declare-const i5 Int)+(declare-const e5 Int)+(assert (distinct i0 i1 i2 i3 i4 i5))+(assert (= (store (store (store (store (store (store a i0 e0) i1 e1) i2 e2) i3 e3) i4 e4) i5 e5) (store (store (store (store (store (store a i5 e5) i4 e4) i3 e3) i2 e2) i1 e1) i0 e0)))+(check-sat)+(exit)
+ bench/smtlib/QF_ALIA/storecomm6_unsat.smt2 view
@@ -0,0 +1,21 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_ALIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const a (Array Int Int))+(declare-const i0 Int)+(declare-const e0 Int)+(declare-const i1 Int)+(declare-const e1 Int)+(declare-const i2 Int)+(declare-const e2 Int)+(declare-const i3 Int)+(declare-const e3 Int)+(declare-const i4 Int)+(declare-const e4 Int)+(declare-const i5 Int)+(declare-const e5 Int)+(assert (distinct i0 i1 i2 i3 i4 i5))+(assert (not (= (store (store (store (store (store (store a i0 e0) i1 e1) i2 e2) i3 e3) i4 e4) i5 e5) (store (store (store (store (store (store a i5 e5) i4 e4) i3 e3) i2 e2) i1 e1) i0 e0))))+(check-sat)+(exit)
+ bench/smtlib/QF_ALIA/swap.smt2 view
@@ -0,0 +1,11 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_ALIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const a (Array Int Int))+(declare-const i Int)+(declare-const j Int)+(define-fun swapped () (Array Int Int) (store (store a i (select a j)) j (select a i)))+(assert (not (= (store (store swapped i (select swapped j)) j (select swapped i)) a)))+(check-sat)+(exit)
+ bench/smtlib/QF_AUF/extensionality.smt2 view
@@ -0,0 +1,13 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_AUF)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-sort E 0)+(declare-const a (Array Bool E))+(declare-const b (Array Bool E))+(declare-fun f ((Array Bool E)) E)+(assert (= (select a true) (select b true)))+(assert (= (select a false) (select b false)))+(assert (not (= (f a) (f b))))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/factor_143.smt2 view
@@ -0,0 +1,15 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const p (_ BitVec 16))+(declare-const q (_ BitVec 16))+(assert (= (bvmul p q) #x008f))+(assert (bvugt p #x0001))+(assert (bvugt q #x0001))+(assert (bvult p #x0100))+(assert (bvult q #x0100))+(assert (bvule p q))+(check-sat)+(get-value (p q))+(exit)
+ bench/smtlib/QF_BV/factor_32bit.smt2 view
@@ -0,0 +1,12 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const p (_ BitVec 32))+(declare-const q (_ BitVec 32))+; 3215031751 = 151 * 751 * 28351; find a nontrivial factorization without overflow+(assert (= (bvmul ((_ zero_extend 32) p) ((_ zero_extend 32) q)) #x00000000bfa1b0c7))+(assert (bvugt p #x00000001))+(assert (bvugt q #x00000001))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/factor_prime_251.smt2 view
@@ -0,0 +1,13 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const p (_ BitVec 16))+(declare-const q (_ BitVec 16))+(assert (= (bvmul p q) #x00fb))+(assert (bvugt p #x0001))+(assert (bvugt q #x0001))+(assert (bvult p #x0100))+(assert (bvult q #x0100))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/hd_add_decomposition.smt2 view
@@ -0,0 +1,10 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x (_ BitVec 32))+(declare-const y (_ BitVec 32))+; x + y = (x xor y) + 2 (x and y)+(assert (not (= (bvadd x y) (bvadd (bvxor x y) (bvshl (bvand x y) #x00000001)))))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/hd_average.smt2 view
@@ -0,0 +1,12 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x (_ BitVec 16))+(declare-const y (_ BitVec 16))+; floor((x + y) / 2) without overflow+(define-fun avg () (_ BitVec 16) (bvadd (bvand x y) (bvlshr (bvxor x y) #x0001)))+(define-fun wide () (_ BitVec 17) (bvlshr (bvadd ((_ zero_extend 1) x) ((_ zero_extend 1) y)) #b00000000000000001))+(assert (not (= ((_ zero_extend 1) avg) wide)))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/hd_average32.smt2 view
@@ -0,0 +1,11 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x (_ BitVec 32))+(declare-const y (_ BitVec 32))+(define-fun avg () (_ BitVec 32) (bvadd (bvand x y) (bvlshr (bvxor x y) #x00000001)))+(define-fun wide () (_ BitVec 33) (bvlshr (bvadd ((_ zero_extend 1) x) ((_ zero_extend 1) y)) ((_ zero_extend 32) #b1)))+(assert (not (= ((_ zero_extend 1) avg) wide)))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/hd_lowest_bit.smt2 view
@@ -0,0 +1,10 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x (_ BitVec 16))+; x and -x isolates the lowest set bit: a power of two, or zero+(define-fun b () (_ BitVec 16) (bvand x (bvneg x)))+(assert (not (= (bvand b (bvsub b #x0001)) #x0000)))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/hd_xor_or_and.smt2 view
@@ -0,0 +1,10 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x (_ BitVec 32))+(declare-const y (_ BitVec 32))+; x xor y = (x or y) - (x and y)+(assert (not (= (bvxor x y) (bvsub (bvor x y) (bvand x y)))))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/inverse_mod_2_16.smt2 view
@@ -0,0 +1,9 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const x (_ BitVec 16))+(assert (= (bvmul x #x0003) #x0001))+(check-sat)+(get-value (x))+(exit)
+ bench/smtlib/QF_BV/let_sum.smt2 view
@@ -0,0 +1,11 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const x (_ BitVec 8))+(assert+ (let ((a (bvadd x #x01)))+ (let ((b (bvadd a a)) (c (bvmul a #x03)))+ (and (= (bvsub c b) a) (bvugt a #xf0) (= (bvxnor a x) #xfe)))))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/mul_commutes16.smt2 view
@@ -0,0 +1,9 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x (_ BitVec 16))+(declare-const y (_ BitVec 16))+(assert (not (= (bvmul x y) (bvmul y x))))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/rotations.smt2 view
@@ -0,0 +1,12 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x (_ BitVec 12))+(declare-const k (_ BitVec 12))+(assert (= ((_ rotate_left 5) ((_ rotate_right 5) x)) x))+(assert (= (bvcomp ((_ rotate_left 3) x) ((_ rotate_right 9) x)) #b1))+(assert (= ((_ repeat 3) ((_ extract 3 0) x)) x))+(assert (not (= ((_ extract 3 0) x) ((_ extract 7 4) x))))+(check-sat)+(exit)
+ bench/smtlib/QF_BV/signed_division.smt2 view
@@ -0,0 +1,12 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const a (_ BitVec 8))+(declare-const b (_ BitVec 8))+(assert (not (= b #x00)))+(assert (not (and (= a #x80) (= b #xff))))+; a = (a sdiv b) * b + (a srem b)+(assert (not (= a (bvadd (bvmul (bvsdiv a b) b) (bvsrem a b)))))+(check-sat)+(exit)
+ bench/smtlib/QF_BVFP/int_conversion.smt2 view
@@ -0,0 +1,12 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BVFP)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x Float32)+(declare-const n (_ BitVec 16))+(assert (= x ((_ to_fp 8 24) RNE n)))+(assert (fp.gt x (fp #b0 #b10000101 #b10010000000000000000000)))+(assert (fp.lt x (fp #b0 #b10000101 #b10010100000000000000000)))+(assert (not (= ((_ fp.to_sbv 16) RTZ x) n)))+(check-sat)+(exit)
+ bench/smtlib/QF_DT/points.smt2 view
@@ -0,0 +1,13 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_DT)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-datatype Point ((mk-point (px Int) (py Int))))+(declare-const p Point)+(declare-const q Point)+(assert (= (px p) (py q)))+(assert (= (py p) (px q)))+(assert (= p q))+(assert (not (= (px p) (py p))))+(check-sat)+(exit)
+ bench/smtlib/QF_FP/non_associative.smt2 view
@@ -0,0 +1,11 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_FP)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const a Float16)+(declare-const b Float16)+(declare-const c Float16)+(assert (not (fp.isNaN (fp.add RNE (fp.add RNE a b) c))))+(assert (not (fp.eq (fp.add RNE (fp.add RNE a b) c) (fp.add RNE a (fp.add RNE b c)))))+(check-sat)+(exit)
+ bench/smtlib/QF_FP/point_one.smt2 view
@@ -0,0 +1,10 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_FP)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(define-fun tenth () Float64 ((_ to_fp 11 53) RNE (fp #b0 #b01111111011 #x999999999999a)))+(declare-const x Float64)+(assert (= x (fp.add RNE tenth (fp.add RNE tenth tenth))))+(assert (fp.eq x ((_ to_fp 11 53) RNE (fp #b0 #b01111111101 #x3333333333333))))+(check-sat)+(exit)
+ bench/smtlib/QF_FP/square_nonnegative.smt2 view
@@ -0,0 +1,8 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_FP)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x Float32)+(assert (fp.lt (fp.mul RNE x x) (_ +zero 8 24)))+(check-sat)+(exit)
+ bench/smtlib/QF_FP/x_plus_one.smt2 view
@@ -0,0 +1,9 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_FP)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x Float16)+(assert (fp.eq (fp.add RNE x ((_ to_fp 5 11) RNE (fp #b0 #b01111 #b0000000000))) x))+(assert (fp.lt (fp.abs x) (fp #b0 #b11010 #b0000000000)))+(check-sat)+(exit)
+ bench/smtlib/QF_LIA/diophantine.smt2 view
@@ -0,0 +1,12 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_LIA)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const x Int)+(declare-const y Int)+(assert (= (+ (* 13 x) (* 17 y)) 1000))+(assert (>= x 0))+(assert (>= y 0))+(assert (< x y))+(check-sat)+(exit)
+ bench/smtlib/QF_LIA/div_mod.smt2 view
@@ -0,0 +1,15 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_LIA)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const x Int)+(declare-const q Int)+(declare-const r Int)+(assert (= q (div x 7)))+(assert (= r (mod x 7)))+(assert (> x 100))+(assert (< x 200))+(assert (= (+ q r) 25))+(check-sat)+(get-value (x q r))+(exit)
+ bench/smtlib/QF_LIA/magic_square3.smt2 view
@@ -0,0 +1,33 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_LIA)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const m00 Int)+(declare-const m01 Int)+(declare-const m02 Int)+(declare-const m10 Int)+(declare-const m11 Int)+(declare-const m12 Int)+(declare-const m20 Int)+(declare-const m21 Int)+(declare-const m22 Int)+(assert (and (>= m00 1) (<= m00 9)))+(assert (and (>= m01 1) (<= m01 9)))+(assert (and (>= m02 1) (<= m02 9)))+(assert (and (>= m10 1) (<= m10 9)))+(assert (and (>= m11 1) (<= m11 9)))+(assert (and (>= m12 1) (<= m12 9)))+(assert (and (>= m20 1) (<= m20 9)))+(assert (and (>= m21 1) (<= m21 9)))+(assert (and (>= m22 1) (<= m22 9)))+(assert (distinct m00 m01 m02 m10 m11 m12 m20 m21 m22))+(assert (= (+ m00 m01 m02) 15))+(assert (= (+ m10 m11 m12) 15))+(assert (= (+ m20 m21 m22) 15))+(assert (= (+ m00 m10 m20) 15))+(assert (= (+ m01 m11 m21) 15))+(assert (= (+ m02 m12 m22) 15))+(assert (= (+ m00 m11 m22) 15))+(assert (= (+ m02 m11 m20) 15))+(check-sat)+(exit)
+ bench/smtlib/QF_LIA/magic_square3_wrong_sum.smt2 view
@@ -0,0 +1,33 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_LIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const m00 Int)+(declare-const m01 Int)+(declare-const m02 Int)+(declare-const m10 Int)+(declare-const m11 Int)+(declare-const m12 Int)+(declare-const m20 Int)+(declare-const m21 Int)+(declare-const m22 Int)+(assert (and (>= m00 1) (<= m00 9)))+(assert (and (>= m01 1) (<= m01 9)))+(assert (and (>= m02 1) (<= m02 9)))+(assert (and (>= m10 1) (<= m10 9)))+(assert (and (>= m11 1) (<= m11 9)))+(assert (and (>= m12 1) (<= m12 9)))+(assert (and (>= m20 1) (<= m20 9)))+(assert (and (>= m21 1) (<= m21 9)))+(assert (and (>= m22 1) (<= m22 9)))+(assert (distinct m00 m01 m02 m10 m11 m12 m20 m21 m22))+(assert (= (+ m00 m01 m02) 16))+(assert (= (+ m10 m11 m12) 16))+(assert (= (+ m20 m21 m22) 16))+(assert (= (+ m00 m10 m20) 16))+(assert (= (+ m01 m11 m21) 16))+(assert (= (+ m02 m12 m22) 16))+(assert (= (+ m00 m11 m22) 16))+(assert (= (+ m02 m11 m20) 16))+(check-sat)+(exit)
+ bench/smtlib/QF_LIA/parity.smt2 view
@@ -0,0 +1,10 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_LIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x Int)+(declare-const y Int)+(declare-const z Int)+(assert (= (+ (* 2 x) (* 4 y)) (+ (* 6 z) 1)))+(check-sat)+(exit)
+ bench/smtlib/QF_LIA/queens8.smt2 view
@@ -0,0 +1,79 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_LIA)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const q0 Int)+(declare-const q1 Int)+(declare-const q2 Int)+(declare-const q3 Int)+(declare-const q4 Int)+(declare-const q5 Int)+(declare-const q6 Int)+(declare-const q7 Int)+(assert (and (>= q0 0) (< q0 8)))+(assert (and (>= q1 0) (< q1 8)))+(assert (and (>= q2 0) (< q2 8)))+(assert (and (>= q3 0) (< q3 8)))+(assert (and (>= q4 0) (< q4 8)))+(assert (and (>= q5 0) (< q5 8)))+(assert (and (>= q6 0) (< q6 8)))+(assert (and (>= q7 0) (< q7 8)))+(assert (distinct q0 q1 q2 q3 q4 q5 q6 q7))+(assert (not (= (- q0 q1) 1)))+(assert (not (= (- q1 q0) 1)))+(assert (not (= (- q0 q2) 2)))+(assert (not (= (- q2 q0) 2)))+(assert (not (= (- q0 q3) 3)))+(assert (not (= (- q3 q0) 3)))+(assert (not (= (- q0 q4) 4)))+(assert (not (= (- q4 q0) 4)))+(assert (not (= (- q0 q5) 5)))+(assert (not (= (- q5 q0) 5)))+(assert (not (= (- q0 q6) 6)))+(assert (not (= (- q6 q0) 6)))+(assert (not (= (- q0 q7) 7)))+(assert (not (= (- q7 q0) 7)))+(assert (not (= (- q1 q2) 1)))+(assert (not (= (- q2 q1) 1)))+(assert (not (= (- q1 q3) 2)))+(assert (not (= (- q3 q1) 2)))+(assert (not (= (- q1 q4) 3)))+(assert (not (= (- q4 q1) 3)))+(assert (not (= (- q1 q5) 4)))+(assert (not (= (- q5 q1) 4)))+(assert (not (= (- q1 q6) 5)))+(assert (not (= (- q6 q1) 5)))+(assert (not (= (- q1 q7) 6)))+(assert (not (= (- q7 q1) 6)))+(assert (not (= (- q2 q3) 1)))+(assert (not (= (- q3 q2) 1)))+(assert (not (= (- q2 q4) 2)))+(assert (not (= (- q4 q2) 2)))+(assert (not (= (- q2 q5) 3)))+(assert (not (= (- q5 q2) 3)))+(assert (not (= (- q2 q6) 4)))+(assert (not (= (- q6 q2) 4)))+(assert (not (= (- q2 q7) 5)))+(assert (not (= (- q7 q2) 5)))+(assert (not (= (- q3 q4) 1)))+(assert (not (= (- q4 q3) 1)))+(assert (not (= (- q3 q5) 2)))+(assert (not (= (- q5 q3) 2)))+(assert (not (= (- q3 q6) 3)))+(assert (not (= (- q6 q3) 3)))+(assert (not (= (- q3 q7) 4)))+(assert (not (= (- q7 q3) 4)))+(assert (not (= (- q4 q5) 1)))+(assert (not (= (- q5 q4) 1)))+(assert (not (= (- q4 q6) 2)))+(assert (not (= (- q6 q4) 2)))+(assert (not (= (- q4 q7) 3)))+(assert (not (= (- q7 q4) 3)))+(assert (not (= (- q5 q6) 1)))+(assert (not (= (- q6 q5) 1)))+(assert (not (= (- q5 q7) 2)))+(assert (not (= (- q7 q5) 2)))+(assert (not (= (- q6 q7) 1)))+(assert (not (= (- q7 q6) 1)))+(check-sat)+(exit)
+ bench/smtlib/QF_LIA/schedule6_short.smt2 view
@@ -0,0 +1,35 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_LIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const s0 Int)+(declare-const s1 Int)+(declare-const s2 Int)+(declare-const s3 Int)+(declare-const s4 Int)+(declare-const s5 Int)+(assert (and (>= s0 0) (<= (+ s0 3) 14)))+(assert (and (>= s1 0) (<= (+ s1 2) 14)))+(assert (and (>= s2 0) (<= (+ s2 4) 14)))+(assert (and (>= s3 0) (<= (+ s3 1) 14)))+(assert (and (>= s4 0) (<= (+ s4 3) 14)))+(assert (and (>= s5 0) (<= (+ s5 2) 14)))+(assert (or (<= (+ s0 3) s1) (<= (+ s1 2) s0)))+(assert (or (<= (+ s0 3) s2) (<= (+ s2 4) s0)))+(assert (or (<= (+ s0 3) s3) (<= (+ s3 1) s0)))+(assert (or (<= (+ s0 3) s4) (<= (+ s4 3) s0)))+(assert (or (<= (+ s0 3) s5) (<= (+ s5 2) s0)))+(assert (or (<= (+ s1 2) s2) (<= (+ s2 4) s1)))+(assert (or (<= (+ s1 2) s3) (<= (+ s3 1) s1)))+(assert (or (<= (+ s1 2) s4) (<= (+ s4 3) s1)))+(assert (or (<= (+ s1 2) s5) (<= (+ s5 2) s1)))+(assert (or (<= (+ s2 4) s3) (<= (+ s3 1) s2)))+(assert (or (<= (+ s2 4) s4) (<= (+ s4 3) s2)))+(assert (or (<= (+ s2 4) s5) (<= (+ s5 2) s2)))+(assert (or (<= (+ s3 1) s4) (<= (+ s4 3) s3)))+(assert (or (<= (+ s3 1) s5) (<= (+ s5 2) s3)))+(assert (or (<= (+ s4 3) s5) (<= (+ s5 2) s4)))+(assert (<= (+ s0 3) s3))+(assert (<= (+ s1 2) s4))+(check-sat)+(exit)
+ bench/smtlib/QF_LIA/schedule6_tight.smt2 view
@@ -0,0 +1,35 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_LIA)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const s0 Int)+(declare-const s1 Int)+(declare-const s2 Int)+(declare-const s3 Int)+(declare-const s4 Int)+(declare-const s5 Int)+(assert (and (>= s0 0) (<= (+ s0 3) 15)))+(assert (and (>= s1 0) (<= (+ s1 2) 15)))+(assert (and (>= s2 0) (<= (+ s2 4) 15)))+(assert (and (>= s3 0) (<= (+ s3 1) 15)))+(assert (and (>= s4 0) (<= (+ s4 3) 15)))+(assert (and (>= s5 0) (<= (+ s5 2) 15)))+(assert (or (<= (+ s0 3) s1) (<= (+ s1 2) s0)))+(assert (or (<= (+ s0 3) s2) (<= (+ s2 4) s0)))+(assert (or (<= (+ s0 3) s3) (<= (+ s3 1) s0)))+(assert (or (<= (+ s0 3) s4) (<= (+ s4 3) s0)))+(assert (or (<= (+ s0 3) s5) (<= (+ s5 2) s0)))+(assert (or (<= (+ s1 2) s2) (<= (+ s2 4) s1)))+(assert (or (<= (+ s1 2) s3) (<= (+ s3 1) s1)))+(assert (or (<= (+ s1 2) s4) (<= (+ s4 3) s1)))+(assert (or (<= (+ s1 2) s5) (<= (+ s5 2) s1)))+(assert (or (<= (+ s2 4) s3) (<= (+ s3 1) s2)))+(assert (or (<= (+ s2 4) s4) (<= (+ s4 3) s2)))+(assert (or (<= (+ s2 4) s5) (<= (+ s5 2) s2)))+(assert (or (<= (+ s3 1) s4) (<= (+ s4 3) s3)))+(assert (or (<= (+ s3 1) s5) (<= (+ s5 2) s3)))+(assert (or (<= (+ s4 3) s5) (<= (+ s5 2) s4)))+(assert (<= (+ s0 3) s3))+(assert (<= (+ s1 2) s4))+(check-sat)+(exit)
+ bench/smtlib/QF_S/conjugate_words.smt2 view
@@ -0,0 +1,10 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_S)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const x String)+(assert (= (str.++ x "ab") (str.++ "ab" x)))+(assert (= (str.len x) 6))+(check-sat)+(get-value (x))+(exit)
+ bench/smtlib/QF_S/no_conjugate.smt2 view
@@ -0,0 +1,8 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_S)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x String)+(assert (= (str.++ x "a") (str.++ "b" x)))+(check-sat)+(exit)
+ bench/smtlib/QF_S/replace_contains.smt2 view
@@ -0,0 +1,11 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_S)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const s String)+(declare-const t String)+(assert (= t (str.replace s "cat" "dog")))+(assert (str.contains s "cat"))+(assert (not (str.contains t "dog")))+(check-sat)+(exit)
+ bench/smtlib/QF_SLIA/digits.smt2 view
@@ -0,0 +1,12 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_SLIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const s String)+(declare-const n Int)+(assert (= n (str.to_int s)))+(assert (= (str.len s) 3))+(assert (> n 990))+(assert (not (str.prefixof "9" s)))+(check-sat)+(exit)
+ bench/smtlib/QF_SLIA/from_int_roundtrip.smt2 view
@@ -0,0 +1,9 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_SLIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const n Int)+(assert (>= n 0))+(assert (not (= (str.to_int (str.from_int n)) n)))+(check-sat)+(exit)
+ bench/smtlib/QF_SLIA/regex_dates.smt2 view
@@ -0,0 +1,25 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_SLIA)+(set-info :source |hsmt benchmark set|)+(declare-const d String)+(declare-const year Int)+(define-fun digit () RegLan (re.range "0" "9"))+(define-fun date () RegLan (re.++ ((_ re.^ 4) digit) (str.to_re "-") (re.union (re.++ (str.to_re "0") (re.range "1" "9")) (re.++ (str.to_re "1") (re.range "0" "2"))) (str.to_re "-") ((_ re.^ 2) digit)))+(assert (str.in_re d date))+(assert (= year (str.to_int (str.substr d 0 4))))+(push 1)+(assert (> year 2020))+(assert (str.suffixof "-31" d))+(set-info :status sat)+(check-sat)+(pop 1)+(push 1)+(assert (str.contains d "-13-"))+(set-info :status unsat)+(check-sat)+(pop 1)+(assert (= (str.at d 5) "0"))+(assert (= (str.at d 6) "0"))+(set-info :status unsat)+(check-sat)+(exit)
+ bench/smtlib/QF_SLIA/regex_even_length.smt2 view
@@ -0,0 +1,11 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_SLIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x String)+(declare-const y String)+(assert (str.in_re x (re.* (str.to_re "ab"))))+(assert (str.in_re y (re.+ (re.union (str.to_re "ab") (str.to_re "ba")))))+(assert (= (+ (str.len x) (str.len y)) 13))+(check-sat)+(exit)
+ bench/smtlib/QF_SLIA/regex_last_char.smt2 view
@@ -0,0 +1,10 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_SLIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const x String)+(define-fun ab () RegLan (re.* (re.range "a" "b")))+(assert (str.in_re x (re.++ ab (str.to_re "a"))))+(assert (str.in_re x (re.++ ab (str.to_re "b"))))+(check-sat)+(exit)
+ bench/smtlib/QF_SLIA/regex_password.smt2 view
@@ -0,0 +1,16 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_SLIA)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const p String)+(define-fun digit () RegLan (re.range "0" "9"))+(define-fun upper () RegLan (re.range "A" "Z"))+(define-fun lower () RegLan (re.range "a" "z"))+(define-fun has ((r RegLan)) RegLan (re.++ re.all r re.all))+(assert (str.in_re p ((_ re.loop 8 12) (re.union digit upper lower (str.to_re "_")))))+(assert (str.in_re p (re.inter (has digit) (has upper) (has lower))))+(assert (not (str.contains p "pass")))+(assert (not (str.in_re p (re.++ re.all ((_ re.^ 3) digit) re.all))))+(assert (str.prefixof "Q" p))+(check-sat)+(exit)
+ bench/smtlib/QF_SLIA/split_email.smt2 view
@@ -0,0 +1,19 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_SLIA)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const email String)+(declare-const user String)+(declare-const domain String)+(declare-const at Int)+(assert (= at (str.indexof email "@" 0)))+(assert (>= at 1))+(assert (= user (str.substr email 0 at)))+(assert (= domain (str.substr email (+ at 1) (- (str.len email) (+ at 1)))))+(assert (str.suffixof ".br" domain))+(assert (not (str.contains domain "@")))+(assert (= (str.len user) 3))+(assert (<= (str.len email) 12))+(check-sat)+(get-value (email))+(exit)
+ bench/smtlib/QF_UF/congruence_chain.smt2 view
@@ -0,0 +1,18 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UF)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-sort U 0)+(declare-fun f (U) U)+(declare-fun g (U U) U)+(declare-const a U)+(declare-const b U)+(declare-const c U)+; f^3(a) = a and f^5(a) = a imply f(a) = a.+(assert (= (f (f (f a))) a))+(assert (= (f (f (f (f (f a))))) a))+(assert (= b (g a (f a))))+(assert (= c (g (f a) a)))+(assert (not (= b c)))+(check-sat)+(exit)
+ bench/smtlib/QF_UF/eq_diamond10.smt2 view
@@ -0,0 +1,49 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UF)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-sort U 0)+(declare-const x0 U)+(declare-const x1 U)+(declare-const x2 U)+(declare-const x3 U)+(declare-const x4 U)+(declare-const x5 U)+(declare-const x6 U)+(declare-const x7 U)+(declare-const x8 U)+(declare-const x9 U)+(declare-const x10 U)+(declare-const y0 U)+(declare-const z0 U)+(declare-const y1 U)+(declare-const z1 U)+(declare-const y2 U)+(declare-const z2 U)+(declare-const y3 U)+(declare-const z3 U)+(declare-const y4 U)+(declare-const z4 U)+(declare-const y5 U)+(declare-const z5 U)+(declare-const y6 U)+(declare-const z6 U)+(declare-const y7 U)+(declare-const z7 U)+(declare-const y8 U)+(declare-const z8 U)+(declare-const y9 U)+(declare-const z9 U)+(assert (or (and (= x0 y0) (= y0 x1)) (and (= x0 z0) (= z0 x1))))+(assert (or (and (= x1 y1) (= y1 x2)) (and (= x1 z1) (= z1 x2))))+(assert (or (and (= x2 y2) (= y2 x3)) (and (= x2 z2) (= z2 x3))))+(assert (or (and (= x3 y3) (= y3 x4)) (and (= x3 z3) (= z3 x4))))+(assert (or (and (= x4 y4) (= y4 x5)) (and (= x4 z4) (= z4 x5))))+(assert (or (and (= x5 y5) (= y5 x6)) (and (= x5 z5) (= z5 x6))))+(assert (or (and (= x6 y6) (= y6 x7)) (and (= x6 z6) (= z6 x7))))+(assert (or (and (= x7 y7) (= y7 x8)) (and (= x7 z7) (= z7 x8))))+(assert (or (and (= x8 y8) (= y8 x9)) (and (= x8 z8) (= z8 x9))))+(assert (or (and (= x9 y9) (= y9 x10)) (and (= x9 z9) (= z9 x10))))+(assert (distinct x0 x10))+(check-sat)+(exit)
+ bench/smtlib/QF_UF/eq_diamond100.smt2 view
@@ -0,0 +1,409 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UF)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-sort U 0)+(declare-const x0 U)+(declare-const x1 U)+(declare-const x2 U)+(declare-const x3 U)+(declare-const x4 U)+(declare-const x5 U)+(declare-const x6 U)+(declare-const x7 U)+(declare-const x8 U)+(declare-const x9 U)+(declare-const x10 U)+(declare-const x11 U)+(declare-const x12 U)+(declare-const x13 U)+(declare-const x14 U)+(declare-const x15 U)+(declare-const x16 U)+(declare-const x17 U)+(declare-const x18 U)+(declare-const x19 U)+(declare-const x20 U)+(declare-const x21 U)+(declare-const x22 U)+(declare-const x23 U)+(declare-const x24 U)+(declare-const x25 U)+(declare-const x26 U)+(declare-const x27 U)+(declare-const x28 U)+(declare-const x29 U)+(declare-const x30 U)+(declare-const x31 U)+(declare-const x32 U)+(declare-const x33 U)+(declare-const x34 U)+(declare-const x35 U)+(declare-const x36 U)+(declare-const x37 U)+(declare-const x38 U)+(declare-const x39 U)+(declare-const x40 U)+(declare-const x41 U)+(declare-const x42 U)+(declare-const x43 U)+(declare-const x44 U)+(declare-const x45 U)+(declare-const x46 U)+(declare-const x47 U)+(declare-const x48 U)+(declare-const x49 U)+(declare-const x50 U)+(declare-const x51 U)+(declare-const x52 U)+(declare-const x53 U)+(declare-const x54 U)+(declare-const x55 U)+(declare-const x56 U)+(declare-const x57 U)+(declare-const x58 U)+(declare-const x59 U)+(declare-const x60 U)+(declare-const x61 U)+(declare-const x62 U)+(declare-const x63 U)+(declare-const x64 U)+(declare-const x65 U)+(declare-const x66 U)+(declare-const x67 U)+(declare-const x68 U)+(declare-const x69 U)+(declare-const x70 U)+(declare-const x71 U)+(declare-const x72 U)+(declare-const x73 U)+(declare-const x74 U)+(declare-const x75 U)+(declare-const x76 U)+(declare-const x77 U)+(declare-const x78 U)+(declare-const x79 U)+(declare-const x80 U)+(declare-const x81 U)+(declare-const x82 U)+(declare-const x83 U)+(declare-const x84 U)+(declare-const x85 U)+(declare-const x86 U)+(declare-const x87 U)+(declare-const x88 U)+(declare-const x89 U)+(declare-const x90 U)+(declare-const x91 U)+(declare-const x92 U)+(declare-const x93 U)+(declare-const x94 U)+(declare-const x95 U)+(declare-const x96 U)+(declare-const x97 U)+(declare-const x98 U)+(declare-const x99 U)+(declare-const x100 U)+(declare-const y0 U)+(declare-const z0 U)+(declare-const y1 U)+(declare-const z1 U)+(declare-const y2 U)+(declare-const z2 U)+(declare-const y3 U)+(declare-const z3 U)+(declare-const y4 U)+(declare-const z4 U)+(declare-const y5 U)+(declare-const z5 U)+(declare-const y6 U)+(declare-const z6 U)+(declare-const y7 U)+(declare-const z7 U)+(declare-const y8 U)+(declare-const z8 U)+(declare-const y9 U)+(declare-const z9 U)+(declare-const y10 U)+(declare-const z10 U)+(declare-const y11 U)+(declare-const z11 U)+(declare-const y12 U)+(declare-const z12 U)+(declare-const y13 U)+(declare-const z13 U)+(declare-const y14 U)+(declare-const z14 U)+(declare-const y15 U)+(declare-const z15 U)+(declare-const y16 U)+(declare-const z16 U)+(declare-const y17 U)+(declare-const z17 U)+(declare-const y18 U)+(declare-const z18 U)+(declare-const y19 U)+(declare-const z19 U)+(declare-const y20 U)+(declare-const z20 U)+(declare-const y21 U)+(declare-const z21 U)+(declare-const y22 U)+(declare-const z22 U)+(declare-const y23 U)+(declare-const z23 U)+(declare-const y24 U)+(declare-const z24 U)+(declare-const y25 U)+(declare-const z25 U)+(declare-const y26 U)+(declare-const z26 U)+(declare-const y27 U)+(declare-const z27 U)+(declare-const y28 U)+(declare-const z28 U)+(declare-const y29 U)+(declare-const z29 U)+(declare-const y30 U)+(declare-const z30 U)+(declare-const y31 U)+(declare-const z31 U)+(declare-const y32 U)+(declare-const z32 U)+(declare-const y33 U)+(declare-const z33 U)+(declare-const y34 U)+(declare-const z34 U)+(declare-const y35 U)+(declare-const z35 U)+(declare-const y36 U)+(declare-const z36 U)+(declare-const y37 U)+(declare-const z37 U)+(declare-const y38 U)+(declare-const z38 U)+(declare-const y39 U)+(declare-const z39 U)+(declare-const y40 U)+(declare-const z40 U)+(declare-const y41 U)+(declare-const z41 U)+(declare-const y42 U)+(declare-const z42 U)+(declare-const y43 U)+(declare-const z43 U)+(declare-const y44 U)+(declare-const z44 U)+(declare-const y45 U)+(declare-const z45 U)+(declare-const y46 U)+(declare-const z46 U)+(declare-const y47 U)+(declare-const z47 U)+(declare-const y48 U)+(declare-const z48 U)+(declare-const y49 U)+(declare-const z49 U)+(declare-const y50 U)+(declare-const z50 U)+(declare-const y51 U)+(declare-const z51 U)+(declare-const y52 U)+(declare-const z52 U)+(declare-const y53 U)+(declare-const z53 U)+(declare-const y54 U)+(declare-const z54 U)+(declare-const y55 U)+(declare-const z55 U)+(declare-const y56 U)+(declare-const z56 U)+(declare-const y57 U)+(declare-const z57 U)+(declare-const y58 U)+(declare-const z58 U)+(declare-const y59 U)+(declare-const z59 U)+(declare-const y60 U)+(declare-const z60 U)+(declare-const y61 U)+(declare-const z61 U)+(declare-const y62 U)+(declare-const z62 U)+(declare-const y63 U)+(declare-const z63 U)+(declare-const y64 U)+(declare-const z64 U)+(declare-const y65 U)+(declare-const z65 U)+(declare-const y66 U)+(declare-const z66 U)+(declare-const y67 U)+(declare-const z67 U)+(declare-const y68 U)+(declare-const z68 U)+(declare-const y69 U)+(declare-const z69 U)+(declare-const y70 U)+(declare-const z70 U)+(declare-const y71 U)+(declare-const z71 U)+(declare-const y72 U)+(declare-const z72 U)+(declare-const y73 U)+(declare-const z73 U)+(declare-const y74 U)+(declare-const z74 U)+(declare-const y75 U)+(declare-const z75 U)+(declare-const y76 U)+(declare-const z76 U)+(declare-const y77 U)+(declare-const z77 U)+(declare-const y78 U)+(declare-const z78 U)+(declare-const y79 U)+(declare-const z79 U)+(declare-const y80 U)+(declare-const z80 U)+(declare-const y81 U)+(declare-const z81 U)+(declare-const y82 U)+(declare-const z82 U)+(declare-const y83 U)+(declare-const z83 U)+(declare-const y84 U)+(declare-const z84 U)+(declare-const y85 U)+(declare-const z85 U)+(declare-const y86 U)+(declare-const z86 U)+(declare-const y87 U)+(declare-const z87 U)+(declare-const y88 U)+(declare-const z88 U)+(declare-const y89 U)+(declare-const z89 U)+(declare-const y90 U)+(declare-const z90 U)+(declare-const y91 U)+(declare-const z91 U)+(declare-const y92 U)+(declare-const z92 U)+(declare-const y93 U)+(declare-const z93 U)+(declare-const y94 U)+(declare-const z94 U)+(declare-const y95 U)+(declare-const z95 U)+(declare-const y96 U)+(declare-const z96 U)+(declare-const y97 U)+(declare-const z97 U)+(declare-const y98 U)+(declare-const z98 U)+(declare-const y99 U)+(declare-const z99 U)+(assert (or (and (= x0 y0) (= y0 x1)) (and (= x0 z0) (= z0 x1))))+(assert (or (and (= x1 y1) (= y1 x2)) (and (= x1 z1) (= z1 x2))))+(assert (or (and (= x2 y2) (= y2 x3)) (and (= x2 z2) (= z2 x3))))+(assert (or (and (= x3 y3) (= y3 x4)) (and (= x3 z3) (= z3 x4))))+(assert (or (and (= x4 y4) (= y4 x5)) (and (= x4 z4) (= z4 x5))))+(assert (or (and (= x5 y5) (= y5 x6)) (and (= x5 z5) (= z5 x6))))+(assert (or (and (= x6 y6) (= y6 x7)) (and (= x6 z6) (= z6 x7))))+(assert (or (and (= x7 y7) (= y7 x8)) (and (= x7 z7) (= z7 x8))))+(assert (or (and (= x8 y8) (= y8 x9)) (and (= x8 z8) (= z8 x9))))+(assert (or (and (= x9 y9) (= y9 x10)) (and (= x9 z9) (= z9 x10))))+(assert (or (and (= x10 y10) (= y10 x11)) (and (= x10 z10) (= z10 x11))))+(assert (or (and (= x11 y11) (= y11 x12)) (and (= x11 z11) (= z11 x12))))+(assert (or (and (= x12 y12) (= y12 x13)) (and (= x12 z12) (= z12 x13))))+(assert (or (and (= x13 y13) (= y13 x14)) (and (= x13 z13) (= z13 x14))))+(assert (or (and (= x14 y14) (= y14 x15)) (and (= x14 z14) (= z14 x15))))+(assert (or (and (= x15 y15) (= y15 x16)) (and (= x15 z15) (= z15 x16))))+(assert (or (and (= x16 y16) (= y16 x17)) (and (= x16 z16) (= z16 x17))))+(assert (or (and (= x17 y17) (= y17 x18)) (and (= x17 z17) (= z17 x18))))+(assert (or (and (= x18 y18) (= y18 x19)) (and (= x18 z18) (= z18 x19))))+(assert (or (and (= x19 y19) (= y19 x20)) (and (= x19 z19) (= z19 x20))))+(assert (or (and (= x20 y20) (= y20 x21)) (and (= x20 z20) (= z20 x21))))+(assert (or (and (= x21 y21) (= y21 x22)) (and (= x21 z21) (= z21 x22))))+(assert (or (and (= x22 y22) (= y22 x23)) (and (= x22 z22) (= z22 x23))))+(assert (or (and (= x23 y23) (= y23 x24)) (and (= x23 z23) (= z23 x24))))+(assert (or (and (= x24 y24) (= y24 x25)) (and (= x24 z24) (= z24 x25))))+(assert (or (and (= x25 y25) (= y25 x26)) (and (= x25 z25) (= z25 x26))))+(assert (or (and (= x26 y26) (= y26 x27)) (and (= x26 z26) (= z26 x27))))+(assert (or (and (= x27 y27) (= y27 x28)) (and (= x27 z27) (= z27 x28))))+(assert (or (and (= x28 y28) (= y28 x29)) (and (= x28 z28) (= z28 x29))))+(assert (or (and (= x29 y29) (= y29 x30)) (and (= x29 z29) (= z29 x30))))+(assert (or (and (= x30 y30) (= y30 x31)) (and (= x30 z30) (= z30 x31))))+(assert (or (and (= x31 y31) (= y31 x32)) (and (= x31 z31) (= z31 x32))))+(assert (or (and (= x32 y32) (= y32 x33)) (and (= x32 z32) (= z32 x33))))+(assert (or (and (= x33 y33) (= y33 x34)) (and (= x33 z33) (= z33 x34))))+(assert (or (and (= x34 y34) (= y34 x35)) (and (= x34 z34) (= z34 x35))))+(assert (or (and (= x35 y35) (= y35 x36)) (and (= x35 z35) (= z35 x36))))+(assert (or (and (= x36 y36) (= y36 x37)) (and (= x36 z36) (= z36 x37))))+(assert (or (and (= x37 y37) (= y37 x38)) (and (= x37 z37) (= z37 x38))))+(assert (or (and (= x38 y38) (= y38 x39)) (and (= x38 z38) (= z38 x39))))+(assert (or (and (= x39 y39) (= y39 x40)) (and (= x39 z39) (= z39 x40))))+(assert (or (and (= x40 y40) (= y40 x41)) (and (= x40 z40) (= z40 x41))))+(assert (or (and (= x41 y41) (= y41 x42)) (and (= x41 z41) (= z41 x42))))+(assert (or (and (= x42 y42) (= y42 x43)) (and (= x42 z42) (= z42 x43))))+(assert (or (and (= x43 y43) (= y43 x44)) (and (= x43 z43) (= z43 x44))))+(assert (or (and (= x44 y44) (= y44 x45)) (and (= x44 z44) (= z44 x45))))+(assert (or (and (= x45 y45) (= y45 x46)) (and (= x45 z45) (= z45 x46))))+(assert (or (and (= x46 y46) (= y46 x47)) (and (= x46 z46) (= z46 x47))))+(assert (or (and (= x47 y47) (= y47 x48)) (and (= x47 z47) (= z47 x48))))+(assert (or (and (= x48 y48) (= y48 x49)) (and (= x48 z48) (= z48 x49))))+(assert (or (and (= x49 y49) (= y49 x50)) (and (= x49 z49) (= z49 x50))))+(assert (or (and (= x50 y50) (= y50 x51)) (and (= x50 z50) (= z50 x51))))+(assert (or (and (= x51 y51) (= y51 x52)) (and (= x51 z51) (= z51 x52))))+(assert (or (and (= x52 y52) (= y52 x53)) (and (= x52 z52) (= z52 x53))))+(assert (or (and (= x53 y53) (= y53 x54)) (and (= x53 z53) (= z53 x54))))+(assert (or (and (= x54 y54) (= y54 x55)) (and (= x54 z54) (= z54 x55))))+(assert (or (and (= x55 y55) (= y55 x56)) (and (= x55 z55) (= z55 x56))))+(assert (or (and (= x56 y56) (= y56 x57)) (and (= x56 z56) (= z56 x57))))+(assert (or (and (= x57 y57) (= y57 x58)) (and (= x57 z57) (= z57 x58))))+(assert (or (and (= x58 y58) (= y58 x59)) (and (= x58 z58) (= z58 x59))))+(assert (or (and (= x59 y59) (= y59 x60)) (and (= x59 z59) (= z59 x60))))+(assert (or (and (= x60 y60) (= y60 x61)) (and (= x60 z60) (= z60 x61))))+(assert (or (and (= x61 y61) (= y61 x62)) (and (= x61 z61) (= z61 x62))))+(assert (or (and (= x62 y62) (= y62 x63)) (and (= x62 z62) (= z62 x63))))+(assert (or (and (= x63 y63) (= y63 x64)) (and (= x63 z63) (= z63 x64))))+(assert (or (and (= x64 y64) (= y64 x65)) (and (= x64 z64) (= z64 x65))))+(assert (or (and (= x65 y65) (= y65 x66)) (and (= x65 z65) (= z65 x66))))+(assert (or (and (= x66 y66) (= y66 x67)) (and (= x66 z66) (= z66 x67))))+(assert (or (and (= x67 y67) (= y67 x68)) (and (= x67 z67) (= z67 x68))))+(assert (or (and (= x68 y68) (= y68 x69)) (and (= x68 z68) (= z68 x69))))+(assert (or (and (= x69 y69) (= y69 x70)) (and (= x69 z69) (= z69 x70))))+(assert (or (and (= x70 y70) (= y70 x71)) (and (= x70 z70) (= z70 x71))))+(assert (or (and (= x71 y71) (= y71 x72)) (and (= x71 z71) (= z71 x72))))+(assert (or (and (= x72 y72) (= y72 x73)) (and (= x72 z72) (= z72 x73))))+(assert (or (and (= x73 y73) (= y73 x74)) (and (= x73 z73) (= z73 x74))))+(assert (or (and (= x74 y74) (= y74 x75)) (and (= x74 z74) (= z74 x75))))+(assert (or (and (= x75 y75) (= y75 x76)) (and (= x75 z75) (= z75 x76))))+(assert (or (and (= x76 y76) (= y76 x77)) (and (= x76 z76) (= z76 x77))))+(assert (or (and (= x77 y77) (= y77 x78)) (and (= x77 z77) (= z77 x78))))+(assert (or (and (= x78 y78) (= y78 x79)) (and (= x78 z78) (= z78 x79))))+(assert (or (and (= x79 y79) (= y79 x80)) (and (= x79 z79) (= z79 x80))))+(assert (or (and (= x80 y80) (= y80 x81)) (and (= x80 z80) (= z80 x81))))+(assert (or (and (= x81 y81) (= y81 x82)) (and (= x81 z81) (= z81 x82))))+(assert (or (and (= x82 y82) (= y82 x83)) (and (= x82 z82) (= z82 x83))))+(assert (or (and (= x83 y83) (= y83 x84)) (and (= x83 z83) (= z83 x84))))+(assert (or (and (= x84 y84) (= y84 x85)) (and (= x84 z84) (= z84 x85))))+(assert (or (and (= x85 y85) (= y85 x86)) (and (= x85 z85) (= z85 x86))))+(assert (or (and (= x86 y86) (= y86 x87)) (and (= x86 z86) (= z86 x87))))+(assert (or (and (= x87 y87) (= y87 x88)) (and (= x87 z87) (= z87 x88))))+(assert (or (and (= x88 y88) (= y88 x89)) (and (= x88 z88) (= z88 x89))))+(assert (or (and (= x89 y89) (= y89 x90)) (and (= x89 z89) (= z89 x90))))+(assert (or (and (= x90 y90) (= y90 x91)) (and (= x90 z90) (= z90 x91))))+(assert (or (and (= x91 y91) (= y91 x92)) (and (= x91 z91) (= z91 x92))))+(assert (or (and (= x92 y92) (= y92 x93)) (and (= x92 z92) (= z92 x93))))+(assert (or (and (= x93 y93) (= y93 x94)) (and (= x93 z93) (= z93 x94))))+(assert (or (and (= x94 y94) (= y94 x95)) (and (= x94 z94) (= z94 x95))))+(assert (or (and (= x95 y95) (= y95 x96)) (and (= x95 z95) (= z95 x96))))+(assert (or (and (= x96 y96) (= y96 x97)) (and (= x96 z96) (= z96 x97))))+(assert (or (and (= x97 y97) (= y97 x98)) (and (= x97 z97) (= z97 x98))))+(assert (or (and (= x98 y98) (= y98 x99)) (and (= x98 z98) (= z98 x99))))+(assert (or (and (= x99 y99) (= y99 x100)) (and (= x99 z99) (= z99 x100))))+(assert (distinct x0 x100))+(check-sat)+(exit)
+ bench/smtlib/QF_UF/eq_diamond30.smt2 view
@@ -0,0 +1,129 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UF)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-sort U 0)+(declare-const x0 U)+(declare-const x1 U)+(declare-const x2 U)+(declare-const x3 U)+(declare-const x4 U)+(declare-const x5 U)+(declare-const x6 U)+(declare-const x7 U)+(declare-const x8 U)+(declare-const x9 U)+(declare-const x10 U)+(declare-const x11 U)+(declare-const x12 U)+(declare-const x13 U)+(declare-const x14 U)+(declare-const x15 U)+(declare-const x16 U)+(declare-const x17 U)+(declare-const x18 U)+(declare-const x19 U)+(declare-const x20 U)+(declare-const x21 U)+(declare-const x22 U)+(declare-const x23 U)+(declare-const x24 U)+(declare-const x25 U)+(declare-const x26 U)+(declare-const x27 U)+(declare-const x28 U)+(declare-const x29 U)+(declare-const x30 U)+(declare-const y0 U)+(declare-const z0 U)+(declare-const y1 U)+(declare-const z1 U)+(declare-const y2 U)+(declare-const z2 U)+(declare-const y3 U)+(declare-const z3 U)+(declare-const y4 U)+(declare-const z4 U)+(declare-const y5 U)+(declare-const z5 U)+(declare-const y6 U)+(declare-const z6 U)+(declare-const y7 U)+(declare-const z7 U)+(declare-const y8 U)+(declare-const z8 U)+(declare-const y9 U)+(declare-const z9 U)+(declare-const y10 U)+(declare-const z10 U)+(declare-const y11 U)+(declare-const z11 U)+(declare-const y12 U)+(declare-const z12 U)+(declare-const y13 U)+(declare-const z13 U)+(declare-const y14 U)+(declare-const z14 U)+(declare-const y15 U)+(declare-const z15 U)+(declare-const y16 U)+(declare-const z16 U)+(declare-const y17 U)+(declare-const z17 U)+(declare-const y18 U)+(declare-const z18 U)+(declare-const y19 U)+(declare-const z19 U)+(declare-const y20 U)+(declare-const z20 U)+(declare-const y21 U)+(declare-const z21 U)+(declare-const y22 U)+(declare-const z22 U)+(declare-const y23 U)+(declare-const z23 U)+(declare-const y24 U)+(declare-const z24 U)+(declare-const y25 U)+(declare-const z25 U)+(declare-const y26 U)+(declare-const z26 U)+(declare-const y27 U)+(declare-const z27 U)+(declare-const y28 U)+(declare-const z28 U)+(declare-const y29 U)+(declare-const z29 U)+(assert (or (and (= x0 y0) (= y0 x1)) (and (= x0 z0) (= z0 x1))))+(assert (or (and (= x1 y1) (= y1 x2)) (and (= x1 z1) (= z1 x2))))+(assert (or (and (= x2 y2) (= y2 x3)) (and (= x2 z2) (= z2 x3))))+(assert (or (and (= x3 y3) (= y3 x4)) (and (= x3 z3) (= z3 x4))))+(assert (or (and (= x4 y4) (= y4 x5)) (and (= x4 z4) (= z4 x5))))+(assert (or (and (= x5 y5) (= y5 x6)) (and (= x5 z5) (= z5 x6))))+(assert (or (and (= x6 y6) (= y6 x7)) (and (= x6 z6) (= z6 x7))))+(assert (or (and (= x7 y7) (= y7 x8)) (and (= x7 z7) (= z7 x8))))+(assert (or (and (= x8 y8) (= y8 x9)) (and (= x8 z8) (= z8 x9))))+(assert (or (and (= x9 y9) (= y9 x10)) (and (= x9 z9) (= z9 x10))))+(assert (or (and (= x10 y10) (= y10 x11)) (and (= x10 z10) (= z10 x11))))+(assert (or (and (= x11 y11) (= y11 x12)) (and (= x11 z11) (= z11 x12))))+(assert (or (and (= x12 y12) (= y12 x13)) (and (= x12 z12) (= z12 x13))))+(assert (or (and (= x13 y13) (= y13 x14)) (and (= x13 z13) (= z13 x14))))+(assert (or (and (= x14 y14) (= y14 x15)) (and (= x14 z14) (= z14 x15))))+(assert (or (and (= x15 y15) (= y15 x16)) (and (= x15 z15) (= z15 x16))))+(assert (or (and (= x16 y16) (= y16 x17)) (and (= x16 z16) (= z16 x17))))+(assert (or (and (= x17 y17) (= y17 x18)) (and (= x17 z17) (= z17 x18))))+(assert (or (and (= x18 y18) (= y18 x19)) (and (= x18 z18) (= z18 x19))))+(assert (or (and (= x19 y19) (= y19 x20)) (and (= x19 z19) (= z19 x20))))+(assert (or (and (= x20 y20) (= y20 x21)) (and (= x20 z20) (= z20 x21))))+(assert (or (and (= x21 y21) (= y21 x22)) (and (= x21 z21) (= z21 x22))))+(assert (or (and (= x22 y22) (= y22 x23)) (and (= x22 z22) (= z22 x23))))+(assert (or (and (= x23 y23) (= y23 x24)) (and (= x23 z23) (= z23 x24))))+(assert (or (and (= x24 y24) (= y24 x25)) (and (= x24 z24) (= z24 x25))))+(assert (or (and (= x25 y25) (= y25 x26)) (and (= x25 z25) (= z25 x26))))+(assert (or (and (= x26 y26) (= y26 x27)) (and (= x26 z26) (= z26 x27))))+(assert (or (and (= x27 y27) (= y27 x28)) (and (= x27 z27) (= z27 x28))))+(assert (or (and (= x28 y28) (= y28 x29)) (and (= x28 z28) (= z28 x29))))+(assert (or (and (= x29 y29) (= y29 x30)) (and (= x29 z29) (= z29 x30))))+(assert (distinct x0 x30))+(check-sat)+(exit)
+ bench/smtlib/QF_UF/latin_square_bool4.smt2 view
@@ -0,0 +1,377 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UF)+(set-info :source |hsmt benchmark set|)+(set-info :status sat)+(declare-const c000 Bool)+(declare-const c001 Bool)+(declare-const c002 Bool)+(declare-const c003 Bool)+(declare-const c010 Bool)+(declare-const c011 Bool)+(declare-const c012 Bool)+(declare-const c013 Bool)+(declare-const c020 Bool)+(declare-const c021 Bool)+(declare-const c022 Bool)+(declare-const c023 Bool)+(declare-const c030 Bool)+(declare-const c031 Bool)+(declare-const c032 Bool)+(declare-const c033 Bool)+(declare-const c100 Bool)+(declare-const c101 Bool)+(declare-const c102 Bool)+(declare-const c103 Bool)+(declare-const c110 Bool)+(declare-const c111 Bool)+(declare-const c112 Bool)+(declare-const c113 Bool)+(declare-const c120 Bool)+(declare-const c121 Bool)+(declare-const c122 Bool)+(declare-const c123 Bool)+(declare-const c130 Bool)+(declare-const c131 Bool)+(declare-const c132 Bool)+(declare-const c133 Bool)+(declare-const c200 Bool)+(declare-const c201 Bool)+(declare-const c202 Bool)+(declare-const c203 Bool)+(declare-const c210 Bool)+(declare-const c211 Bool)+(declare-const c212 Bool)+(declare-const c213 Bool)+(declare-const c220 Bool)+(declare-const c221 Bool)+(declare-const c222 Bool)+(declare-const c223 Bool)+(declare-const c230 Bool)+(declare-const c231 Bool)+(declare-const c232 Bool)+(declare-const c233 Bool)+(declare-const c300 Bool)+(declare-const c301 Bool)+(declare-const c302 Bool)+(declare-const c303 Bool)+(declare-const c310 Bool)+(declare-const c311 Bool)+(declare-const c312 Bool)+(declare-const c313 Bool)+(declare-const c320 Bool)+(declare-const c321 Bool)+(declare-const c322 Bool)+(declare-const c323 Bool)+(declare-const c330 Bool)+(declare-const c331 Bool)+(declare-const c332 Bool)+(declare-const c333 Bool)+(assert (or c000 c001 c002 c003))+(assert (or c010 c011 c012 c013))+(assert (or c020 c021 c022 c023))+(assert (or c030 c031 c032 c033))+(assert (or c100 c101 c102 c103))+(assert (or c110 c111 c112 c113))+(assert (or c120 c121 c122 c123))+(assert (or c130 c131 c132 c133))+(assert (or c200 c201 c202 c203))+(assert (or c210 c211 c212 c213))+(assert (or c220 c221 c222 c223))+(assert (or c230 c231 c232 c233))+(assert (or c300 c301 c302 c303))+(assert (or c310 c311 c312 c313))+(assert (or c320 c321 c322 c323))+(assert (or c330 c331 c332 c333))+(assert (not (and c000 c010)))+(assert (not (and c000 c020)))+(assert (not (and c000 c030)))+(assert (not (and c010 c020)))+(assert (not (and c010 c030)))+(assert (not (and c020 c030)))+(assert (not (and c001 c011)))+(assert (not (and c001 c021)))+(assert (not (and c001 c031)))+(assert (not (and c011 c021)))+(assert (not (and c011 c031)))+(assert (not (and c021 c031)))+(assert (not (and c002 c012)))+(assert (not (and c002 c022)))+(assert (not (and c002 c032)))+(assert (not (and c012 c022)))+(assert (not (and c012 c032)))+(assert (not (and c022 c032)))+(assert (not (and c003 c013)))+(assert (not (and c003 c023)))+(assert (not (and c003 c033)))+(assert (not (and c013 c023)))+(assert (not (and c013 c033)))+(assert (not (and c023 c033)))+(assert (not (and c100 c110)))+(assert (not (and c100 c120)))+(assert (not (and c100 c130)))+(assert (not (and c110 c120)))+(assert (not (and c110 c130)))+(assert (not (and c120 c130)))+(assert (not (and c101 c111)))+(assert (not (and c101 c121)))+(assert (not (and c101 c131)))+(assert (not (and c111 c121)))+(assert (not (and c111 c131)))+(assert (not (and c121 c131)))+(assert (not (and c102 c112)))+(assert (not (and c102 c122)))+(assert (not (and c102 c132)))+(assert (not (and c112 c122)))+(assert (not (and c112 c132)))+(assert (not (and c122 c132)))+(assert (not (and c103 c113)))+(assert (not (and c103 c123)))+(assert (not (and c103 c133)))+(assert (not (and c113 c123)))+(assert (not (and c113 c133)))+(assert (not (and c123 c133)))+(assert (not (and c200 c210)))+(assert (not (and c200 c220)))+(assert (not (and c200 c230)))+(assert (not (and c210 c220)))+(assert (not (and c210 c230)))+(assert (not (and c220 c230)))+(assert (not (and c201 c211)))+(assert (not (and c201 c221)))+(assert (not (and c201 c231)))+(assert (not (and c211 c221)))+(assert (not (and c211 c231)))+(assert (not (and c221 c231)))+(assert (not (and c202 c212)))+(assert (not (and c202 c222)))+(assert (not (and c202 c232)))+(assert (not (and c212 c222)))+(assert (not (and c212 c232)))+(assert (not (and c222 c232)))+(assert (not (and c203 c213)))+(assert (not (and c203 c223)))+(assert (not (and c203 c233)))+(assert (not (and c213 c223)))+(assert (not (and c213 c233)))+(assert (not (and c223 c233)))+(assert (not (and c300 c310)))+(assert (not (and c300 c320)))+(assert (not (and c300 c330)))+(assert (not (and c310 c320)))+(assert (not (and c310 c330)))+(assert (not (and c320 c330)))+(assert (not (and c301 c311)))+(assert (not (and c301 c321)))+(assert (not (and c301 c331)))+(assert (not (and c311 c321)))+(assert (not (and c311 c331)))+(assert (not (and c321 c331)))+(assert (not (and c302 c312)))+(assert (not (and c302 c322)))+(assert (not (and c302 c332)))+(assert (not (and c312 c322)))+(assert (not (and c312 c332)))+(assert (not (and c322 c332)))+(assert (not (and c303 c313)))+(assert (not (and c303 c323)))+(assert (not (and c303 c333)))+(assert (not (and c313 c323)))+(assert (not (and c313 c333)))+(assert (not (and c323 c333)))+(assert (not (and c000 c100)))+(assert (not (and c000 c200)))+(assert (not (and c000 c300)))+(assert (not (and c100 c200)))+(assert (not (and c100 c300)))+(assert (not (and c200 c300)))+(assert (not (and c001 c101)))+(assert (not (and c001 c201)))+(assert (not (and c001 c301)))+(assert (not (and c101 c201)))+(assert (not (and c101 c301)))+(assert (not (and c201 c301)))+(assert (not (and c002 c102)))+(assert (not (and c002 c202)))+(assert (not (and c002 c302)))+(assert (not (and c102 c202)))+(assert (not (and c102 c302)))+(assert (not (and c202 c302)))+(assert (not (and c003 c103)))+(assert (not (and c003 c203)))+(assert (not (and c003 c303)))+(assert (not (and c103 c203)))+(assert (not (and c103 c303)))+(assert (not (and c203 c303)))+(assert (not (and c010 c110)))+(assert (not (and c010 c210)))+(assert (not (and c010 c310)))+(assert (not (and c110 c210)))+(assert (not (and c110 c310)))+(assert (not (and c210 c310)))+(assert (not (and c011 c111)))+(assert (not (and c011 c211)))+(assert (not (and c011 c311)))+(assert (not (and c111 c211)))+(assert (not (and c111 c311)))+(assert (not (and c211 c311)))+(assert (not (and c012 c112)))+(assert (not (and c012 c212)))+(assert (not (and c012 c312)))+(assert (not (and c112 c212)))+(assert (not (and c112 c312)))+(assert (not (and c212 c312)))+(assert (not (and c013 c113)))+(assert (not (and c013 c213)))+(assert (not (and c013 c313)))+(assert (not (and c113 c213)))+(assert (not (and c113 c313)))+(assert (not (and c213 c313)))+(assert (not (and c020 c120)))+(assert (not (and c020 c220)))+(assert (not (and c020 c320)))+(assert (not (and c120 c220)))+(assert (not (and c120 c320)))+(assert (not (and c220 c320)))+(assert (not (and c021 c121)))+(assert (not (and c021 c221)))+(assert (not (and c021 c321)))+(assert (not (and c121 c221)))+(assert (not (and c121 c321)))+(assert (not (and c221 c321)))+(assert (not (and c022 c122)))+(assert (not (and c022 c222)))+(assert (not (and c022 c322)))+(assert (not (and c122 c222)))+(assert (not (and c122 c322)))+(assert (not (and c222 c322)))+(assert (not (and c023 c123)))+(assert (not (and c023 c223)))+(assert (not (and c023 c323)))+(assert (not (and c123 c223)))+(assert (not (and c123 c323)))+(assert (not (and c223 c323)))+(assert (not (and c030 c130)))+(assert (not (and c030 c230)))+(assert (not (and c030 c330)))+(assert (not (and c130 c230)))+(assert (not (and c130 c330)))+(assert (not (and c230 c330)))+(assert (not (and c031 c131)))+(assert (not (and c031 c231)))+(assert (not (and c031 c331)))+(assert (not (and c131 c231)))+(assert (not (and c131 c331)))+(assert (not (and c231 c331)))+(assert (not (and c032 c132)))+(assert (not (and c032 c232)))+(assert (not (and c032 c332)))+(assert (not (and c132 c232)))+(assert (not (and c132 c332)))+(assert (not (and c232 c332)))+(assert (not (and c033 c133)))+(assert (not (and c033 c233)))+(assert (not (and c033 c333)))+(assert (not (and c133 c233)))+(assert (not (and c133 c333)))+(assert (not (and c233 c333)))+(assert (not (and c000 c001)))+(assert (not (and c000 c002)))+(assert (not (and c000 c003)))+(assert (not (and c001 c002)))+(assert (not (and c001 c003)))+(assert (not (and c002 c003)))+(assert (not (and c010 c011)))+(assert (not (and c010 c012)))+(assert (not (and c010 c013)))+(assert (not (and c011 c012)))+(assert (not (and c011 c013)))+(assert (not (and c012 c013)))+(assert (not (and c020 c021)))+(assert (not (and c020 c022)))+(assert (not (and c020 c023)))+(assert (not (and c021 c022)))+(assert (not (and c021 c023)))+(assert (not (and c022 c023)))+(assert (not (and c030 c031)))+(assert (not (and c030 c032)))+(assert (not (and c030 c033)))+(assert (not (and c031 c032)))+(assert (not (and c031 c033)))+(assert (not (and c032 c033)))+(assert (not (and c100 c101)))+(assert (not (and c100 c102)))+(assert (not (and c100 c103)))+(assert (not (and c101 c102)))+(assert (not (and c101 c103)))+(assert (not (and c102 c103)))+(assert (not (and c110 c111)))+(assert (not (and c110 c112)))+(assert (not (and c110 c113)))+(assert (not (and c111 c112)))+(assert (not (and c111 c113)))+(assert (not (and c112 c113)))+(assert (not (and c120 c121)))+(assert (not (and c120 c122)))+(assert (not (and c120 c123)))+(assert (not (and c121 c122)))+(assert (not (and c121 c123)))+(assert (not (and c122 c123)))+(assert (not (and c130 c131)))+(assert (not (and c130 c132)))+(assert (not (and c130 c133)))+(assert (not (and c131 c132)))+(assert (not (and c131 c133)))+(assert (not (and c132 c133)))+(assert (not (and c200 c201)))+(assert (not (and c200 c202)))+(assert (not (and c200 c203)))+(assert (not (and c201 c202)))+(assert (not (and c201 c203)))+(assert (not (and c202 c203)))+(assert (not (and c210 c211)))+(assert (not (and c210 c212)))+(assert (not (and c210 c213)))+(assert (not (and c211 c212)))+(assert (not (and c211 c213)))+(assert (not (and c212 c213)))+(assert (not (and c220 c221)))+(assert (not (and c220 c222)))+(assert (not (and c220 c223)))+(assert (not (and c221 c222)))+(assert (not (and c221 c223)))+(assert (not (and c222 c223)))+(assert (not (and c230 c231)))+(assert (not (and c230 c232)))+(assert (not (and c230 c233)))+(assert (not (and c231 c232)))+(assert (not (and c231 c233)))+(assert (not (and c232 c233)))+(assert (not (and c300 c301)))+(assert (not (and c300 c302)))+(assert (not (and c300 c303)))+(assert (not (and c301 c302)))+(assert (not (and c301 c303)))+(assert (not (and c302 c303)))+(assert (not (and c310 c311)))+(assert (not (and c310 c312)))+(assert (not (and c310 c313)))+(assert (not (and c311 c312)))+(assert (not (and c311 c313)))+(assert (not (and c312 c313)))+(assert (not (and c320 c321)))+(assert (not (and c320 c322)))+(assert (not (and c320 c323)))+(assert (not (and c321 c322)))+(assert (not (and c321 c323)))+(assert (not (and c322 c323)))+(assert (not (and c330 c331)))+(assert (not (and c330 c332)))+(assert (not (and c330 c333)))+(assert (not (and c331 c332)))+(assert (not (and c331 c333)))+(assert (not (and c332 c333)))+(assert c000)+(assert c011)+(assert c112)+(check-sat)+(exit)
+ bench/smtlib/QF_UF/pigeonhole_bool7.smt2 view
@@ -0,0 +1,266 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UF)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const p0_0 Bool)+(declare-const p0_1 Bool)+(declare-const p0_2 Bool)+(declare-const p0_3 Bool)+(declare-const p0_4 Bool)+(declare-const p0_5 Bool)+(declare-const p0_6 Bool)+(declare-const p1_0 Bool)+(declare-const p1_1 Bool)+(declare-const p1_2 Bool)+(declare-const p1_3 Bool)+(declare-const p1_4 Bool)+(declare-const p1_5 Bool)+(declare-const p1_6 Bool)+(declare-const p2_0 Bool)+(declare-const p2_1 Bool)+(declare-const p2_2 Bool)+(declare-const p2_3 Bool)+(declare-const p2_4 Bool)+(declare-const p2_5 Bool)+(declare-const p2_6 Bool)+(declare-const p3_0 Bool)+(declare-const p3_1 Bool)+(declare-const p3_2 Bool)+(declare-const p3_3 Bool)+(declare-const p3_4 Bool)+(declare-const p3_5 Bool)+(declare-const p3_6 Bool)+(declare-const p4_0 Bool)+(declare-const p4_1 Bool)+(declare-const p4_2 Bool)+(declare-const p4_3 Bool)+(declare-const p4_4 Bool)+(declare-const p4_5 Bool)+(declare-const p4_6 Bool)+(declare-const p5_0 Bool)+(declare-const p5_1 Bool)+(declare-const p5_2 Bool)+(declare-const p5_3 Bool)+(declare-const p5_4 Bool)+(declare-const p5_5 Bool)+(declare-const p5_6 Bool)+(declare-const p6_0 Bool)+(declare-const p6_1 Bool)+(declare-const p6_2 Bool)+(declare-const p6_3 Bool)+(declare-const p6_4 Bool)+(declare-const p6_5 Bool)+(declare-const p6_6 Bool)+(declare-const p7_0 Bool)+(declare-const p7_1 Bool)+(declare-const p7_2 Bool)+(declare-const p7_3 Bool)+(declare-const p7_4 Bool)+(declare-const p7_5 Bool)+(declare-const p7_6 Bool)+(assert (or p0_0 p0_1 p0_2 p0_3 p0_4 p0_5 p0_6))+(assert (or p1_0 p1_1 p1_2 p1_3 p1_4 p1_5 p1_6))+(assert (or p2_0 p2_1 p2_2 p2_3 p2_4 p2_5 p2_6))+(assert (or p3_0 p3_1 p3_2 p3_3 p3_4 p3_5 p3_6))+(assert (or p4_0 p4_1 p4_2 p4_3 p4_4 p4_5 p4_6))+(assert (or p5_0 p5_1 p5_2 p5_3 p5_4 p5_5 p5_6))+(assert (or p6_0 p6_1 p6_2 p6_3 p6_4 p6_5 p6_6))+(assert (or p7_0 p7_1 p7_2 p7_3 p7_4 p7_5 p7_6))+(assert (or (not p0_0) (not p1_0)))+(assert (or (not p0_0) (not p2_0)))+(assert (or (not p0_0) (not p3_0)))+(assert (or (not p0_0) (not p4_0)))+(assert (or (not p0_0) (not p5_0)))+(assert (or (not p0_0) (not p6_0)))+(assert (or (not p0_0) (not p7_0)))+(assert (or (not p1_0) (not p2_0)))+(assert (or (not p1_0) (not p3_0)))+(assert (or (not p1_0) (not p4_0)))+(assert (or (not p1_0) (not p5_0)))+(assert (or (not p1_0) (not p6_0)))+(assert (or (not p1_0) (not p7_0)))+(assert (or (not p2_0) (not p3_0)))+(assert (or (not p2_0) (not p4_0)))+(assert (or (not p2_0) (not p5_0)))+(assert (or (not p2_0) (not p6_0)))+(assert (or (not p2_0) (not p7_0)))+(assert (or (not p3_0) (not p4_0)))+(assert (or (not p3_0) (not p5_0)))+(assert (or (not p3_0) (not p6_0)))+(assert (or (not p3_0) (not p7_0)))+(assert (or (not p4_0) (not p5_0)))+(assert (or (not p4_0) (not p6_0)))+(assert (or (not p4_0) (not p7_0)))+(assert (or (not p5_0) (not p6_0)))+(assert (or (not p5_0) (not p7_0)))+(assert (or (not p6_0) (not p7_0)))+(assert (or (not p0_1) (not p1_1)))+(assert (or (not p0_1) (not p2_1)))+(assert (or (not p0_1) (not p3_1)))+(assert (or (not p0_1) (not p4_1)))+(assert (or (not p0_1) (not p5_1)))+(assert (or (not p0_1) (not p6_1)))+(assert (or (not p0_1) (not p7_1)))+(assert (or (not p1_1) (not p2_1)))+(assert (or (not p1_1) (not p3_1)))+(assert (or (not p1_1) (not p4_1)))+(assert (or (not p1_1) (not p5_1)))+(assert (or (not p1_1) (not p6_1)))+(assert (or (not p1_1) (not p7_1)))+(assert (or (not p2_1) (not p3_1)))+(assert (or (not p2_1) (not p4_1)))+(assert (or (not p2_1) (not p5_1)))+(assert (or (not p2_1) (not p6_1)))+(assert (or (not p2_1) (not p7_1)))+(assert (or (not p3_1) (not p4_1)))+(assert (or (not p3_1) (not p5_1)))+(assert (or (not p3_1) (not p6_1)))+(assert (or (not p3_1) (not p7_1)))+(assert (or (not p4_1) (not p5_1)))+(assert (or (not p4_1) (not p6_1)))+(assert (or (not p4_1) (not p7_1)))+(assert (or (not p5_1) (not p6_1)))+(assert (or (not p5_1) (not p7_1)))+(assert (or (not p6_1) (not p7_1)))+(assert (or (not p0_2) (not p1_2)))+(assert (or (not p0_2) (not p2_2)))+(assert (or (not p0_2) (not p3_2)))+(assert (or (not p0_2) (not p4_2)))+(assert (or (not p0_2) (not p5_2)))+(assert (or (not p0_2) (not p6_2)))+(assert (or (not p0_2) (not p7_2)))+(assert (or (not p1_2) (not p2_2)))+(assert (or (not p1_2) (not p3_2)))+(assert (or (not p1_2) (not p4_2)))+(assert (or (not p1_2) (not p5_2)))+(assert (or (not p1_2) (not p6_2)))+(assert (or (not p1_2) (not p7_2)))+(assert (or (not p2_2) (not p3_2)))+(assert (or (not p2_2) (not p4_2)))+(assert (or (not p2_2) (not p5_2)))+(assert (or (not p2_2) (not p6_2)))+(assert (or (not p2_2) (not p7_2)))+(assert (or (not p3_2) (not p4_2)))+(assert (or (not p3_2) (not p5_2)))+(assert (or (not p3_2) (not p6_2)))+(assert (or (not p3_2) (not p7_2)))+(assert (or (not p4_2) (not p5_2)))+(assert (or (not p4_2) (not p6_2)))+(assert (or (not p4_2) (not p7_2)))+(assert (or (not p5_2) (not p6_2)))+(assert (or (not p5_2) (not p7_2)))+(assert (or (not p6_2) (not p7_2)))+(assert (or (not p0_3) (not p1_3)))+(assert (or (not p0_3) (not p2_3)))+(assert (or (not p0_3) (not p3_3)))+(assert (or (not p0_3) (not p4_3)))+(assert (or (not p0_3) (not p5_3)))+(assert (or (not p0_3) (not p6_3)))+(assert (or (not p0_3) (not p7_3)))+(assert (or (not p1_3) (not p2_3)))+(assert (or (not p1_3) (not p3_3)))+(assert (or (not p1_3) (not p4_3)))+(assert (or (not p1_3) (not p5_3)))+(assert (or (not p1_3) (not p6_3)))+(assert (or (not p1_3) (not p7_3)))+(assert (or (not p2_3) (not p3_3)))+(assert (or (not p2_3) (not p4_3)))+(assert (or (not p2_3) (not p5_3)))+(assert (or (not p2_3) (not p6_3)))+(assert (or (not p2_3) (not p7_3)))+(assert (or (not p3_3) (not p4_3)))+(assert (or (not p3_3) (not p5_3)))+(assert (or (not p3_3) (not p6_3)))+(assert (or (not p3_3) (not p7_3)))+(assert (or (not p4_3) (not p5_3)))+(assert (or (not p4_3) (not p6_3)))+(assert (or (not p4_3) (not p7_3)))+(assert (or (not p5_3) (not p6_3)))+(assert (or (not p5_3) (not p7_3)))+(assert (or (not p6_3) (not p7_3)))+(assert (or (not p0_4) (not p1_4)))+(assert (or (not p0_4) (not p2_4)))+(assert (or (not p0_4) (not p3_4)))+(assert (or (not p0_4) (not p4_4)))+(assert (or (not p0_4) (not p5_4)))+(assert (or (not p0_4) (not p6_4)))+(assert (or (not p0_4) (not p7_4)))+(assert (or (not p1_4) (not p2_4)))+(assert (or (not p1_4) (not p3_4)))+(assert (or (not p1_4) (not p4_4)))+(assert (or (not p1_4) (not p5_4)))+(assert (or (not p1_4) (not p6_4)))+(assert (or (not p1_4) (not p7_4)))+(assert (or (not p2_4) (not p3_4)))+(assert (or (not p2_4) (not p4_4)))+(assert (or (not p2_4) (not p5_4)))+(assert (or (not p2_4) (not p6_4)))+(assert (or (not p2_4) (not p7_4)))+(assert (or (not p3_4) (not p4_4)))+(assert (or (not p3_4) (not p5_4)))+(assert (or (not p3_4) (not p6_4)))+(assert (or (not p3_4) (not p7_4)))+(assert (or (not p4_4) (not p5_4)))+(assert (or (not p4_4) (not p6_4)))+(assert (or (not p4_4) (not p7_4)))+(assert (or (not p5_4) (not p6_4)))+(assert (or (not p5_4) (not p7_4)))+(assert (or (not p6_4) (not p7_4)))+(assert (or (not p0_5) (not p1_5)))+(assert (or (not p0_5) (not p2_5)))+(assert (or (not p0_5) (not p3_5)))+(assert (or (not p0_5) (not p4_5)))+(assert (or (not p0_5) (not p5_5)))+(assert (or (not p0_5) (not p6_5)))+(assert (or (not p0_5) (not p7_5)))+(assert (or (not p1_5) (not p2_5)))+(assert (or (not p1_5) (not p3_5)))+(assert (or (not p1_5) (not p4_5)))+(assert (or (not p1_5) (not p5_5)))+(assert (or (not p1_5) (not p6_5)))+(assert (or (not p1_5) (not p7_5)))+(assert (or (not p2_5) (not p3_5)))+(assert (or (not p2_5) (not p4_5)))+(assert (or (not p2_5) (not p5_5)))+(assert (or (not p2_5) (not p6_5)))+(assert (or (not p2_5) (not p7_5)))+(assert (or (not p3_5) (not p4_5)))+(assert (or (not p3_5) (not p5_5)))+(assert (or (not p3_5) (not p6_5)))+(assert (or (not p3_5) (not p7_5)))+(assert (or (not p4_5) (not p5_5)))+(assert (or (not p4_5) (not p6_5)))+(assert (or (not p4_5) (not p7_5)))+(assert (or (not p5_5) (not p6_5)))+(assert (or (not p5_5) (not p7_5)))+(assert (or (not p6_5) (not p7_5)))+(assert (or (not p0_6) (not p1_6)))+(assert (or (not p0_6) (not p2_6)))+(assert (or (not p0_6) (not p3_6)))+(assert (or (not p0_6) (not p4_6)))+(assert (or (not p0_6) (not p5_6)))+(assert (or (not p0_6) (not p6_6)))+(assert (or (not p0_6) (not p7_6)))+(assert (or (not p1_6) (not p2_6)))+(assert (or (not p1_6) (not p3_6)))+(assert (or (not p1_6) (not p4_6)))+(assert (or (not p1_6) (not p5_6)))+(assert (or (not p1_6) (not p6_6)))+(assert (or (not p1_6) (not p7_6)))+(assert (or (not p2_6) (not p3_6)))+(assert (or (not p2_6) (not p4_6)))+(assert (or (not p2_6) (not p5_6)))+(assert (or (not p2_6) (not p6_6)))+(assert (or (not p2_6) (not p7_6)))+(assert (or (not p3_6) (not p4_6)))+(assert (or (not p3_6) (not p5_6)))+(assert (or (not p3_6) (not p6_6)))+(assert (or (not p3_6) (not p7_6)))+(assert (or (not p4_6) (not p5_6)))+(assert (or (not p4_6) (not p6_6)))+(assert (or (not p4_6) (not p7_6)))+(assert (or (not p5_6) (not p6_6)))+(assert (or (not p5_6) (not p7_6)))+(assert (or (not p6_6) (not p7_6)))+(check-sat)+(exit)
+ bench/smtlib/QF_UF/pigeonhole_bool8.smt2 view
@@ -0,0 +1,375 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UF)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-const p0_0 Bool)+(declare-const p0_1 Bool)+(declare-const p0_2 Bool)+(declare-const p0_3 Bool)+(declare-const p0_4 Bool)+(declare-const p0_5 Bool)+(declare-const p0_6 Bool)+(declare-const p0_7 Bool)+(declare-const p1_0 Bool)+(declare-const p1_1 Bool)+(declare-const p1_2 Bool)+(declare-const p1_3 Bool)+(declare-const p1_4 Bool)+(declare-const p1_5 Bool)+(declare-const p1_6 Bool)+(declare-const p1_7 Bool)+(declare-const p2_0 Bool)+(declare-const p2_1 Bool)+(declare-const p2_2 Bool)+(declare-const p2_3 Bool)+(declare-const p2_4 Bool)+(declare-const p2_5 Bool)+(declare-const p2_6 Bool)+(declare-const p2_7 Bool)+(declare-const p3_0 Bool)+(declare-const p3_1 Bool)+(declare-const p3_2 Bool)+(declare-const p3_3 Bool)+(declare-const p3_4 Bool)+(declare-const p3_5 Bool)+(declare-const p3_6 Bool)+(declare-const p3_7 Bool)+(declare-const p4_0 Bool)+(declare-const p4_1 Bool)+(declare-const p4_2 Bool)+(declare-const p4_3 Bool)+(declare-const p4_4 Bool)+(declare-const p4_5 Bool)+(declare-const p4_6 Bool)+(declare-const p4_7 Bool)+(declare-const p5_0 Bool)+(declare-const p5_1 Bool)+(declare-const p5_2 Bool)+(declare-const p5_3 Bool)+(declare-const p5_4 Bool)+(declare-const p5_5 Bool)+(declare-const p5_6 Bool)+(declare-const p5_7 Bool)+(declare-const p6_0 Bool)+(declare-const p6_1 Bool)+(declare-const p6_2 Bool)+(declare-const p6_3 Bool)+(declare-const p6_4 Bool)+(declare-const p6_5 Bool)+(declare-const p6_6 Bool)+(declare-const p6_7 Bool)+(declare-const p7_0 Bool)+(declare-const p7_1 Bool)+(declare-const p7_2 Bool)+(declare-const p7_3 Bool)+(declare-const p7_4 Bool)+(declare-const p7_5 Bool)+(declare-const p7_6 Bool)+(declare-const p7_7 Bool)+(declare-const p8_0 Bool)+(declare-const p8_1 Bool)+(declare-const p8_2 Bool)+(declare-const p8_3 Bool)+(declare-const p8_4 Bool)+(declare-const p8_5 Bool)+(declare-const p8_6 Bool)+(declare-const p8_7 Bool)+(assert (or p0_0 p0_1 p0_2 p0_3 p0_4 p0_5 p0_6 p0_7))+(assert (or p1_0 p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7))+(assert (or p2_0 p2_1 p2_2 p2_3 p2_4 p2_5 p2_6 p2_7))+(assert (or p3_0 p3_1 p3_2 p3_3 p3_4 p3_5 p3_6 p3_7))+(assert (or p4_0 p4_1 p4_2 p4_3 p4_4 p4_5 p4_6 p4_7))+(assert (or p5_0 p5_1 p5_2 p5_3 p5_4 p5_5 p5_6 p5_7))+(assert (or p6_0 p6_1 p6_2 p6_3 p6_4 p6_5 p6_6 p6_7))+(assert (or p7_0 p7_1 p7_2 p7_3 p7_4 p7_5 p7_6 p7_7))+(assert (or p8_0 p8_1 p8_2 p8_3 p8_4 p8_5 p8_6 p8_7))+(assert (or (not p0_0) (not p1_0)))+(assert (or (not p0_0) (not p2_0)))+(assert (or (not p0_0) (not p3_0)))+(assert (or (not p0_0) (not p4_0)))+(assert (or (not p0_0) (not p5_0)))+(assert (or (not p0_0) (not p6_0)))+(assert (or (not p0_0) (not p7_0)))+(assert (or (not p0_0) (not p8_0)))+(assert (or (not p1_0) (not p2_0)))+(assert (or (not p1_0) (not p3_0)))+(assert (or (not p1_0) (not p4_0)))+(assert (or (not p1_0) (not p5_0)))+(assert (or (not p1_0) (not p6_0)))+(assert (or (not p1_0) (not p7_0)))+(assert (or (not p1_0) (not p8_0)))+(assert (or (not p2_0) (not p3_0)))+(assert (or (not p2_0) (not p4_0)))+(assert (or (not p2_0) (not p5_0)))+(assert (or (not p2_0) (not p6_0)))+(assert (or (not p2_0) (not p7_0)))+(assert (or (not p2_0) (not p8_0)))+(assert (or (not p3_0) (not p4_0)))+(assert (or (not p3_0) (not p5_0)))+(assert (or (not p3_0) (not p6_0)))+(assert (or (not p3_0) (not p7_0)))+(assert (or (not p3_0) (not p8_0)))+(assert (or (not p4_0) (not p5_0)))+(assert (or (not p4_0) (not p6_0)))+(assert (or (not p4_0) (not p7_0)))+(assert (or (not p4_0) (not p8_0)))+(assert (or (not p5_0) (not p6_0)))+(assert (or (not p5_0) (not p7_0)))+(assert (or (not p5_0) (not p8_0)))+(assert (or (not p6_0) (not p7_0)))+(assert (or (not p6_0) (not p8_0)))+(assert (or (not p7_0) (not p8_0)))+(assert (or (not p0_1) (not p1_1)))+(assert (or (not p0_1) (not p2_1)))+(assert (or (not p0_1) (not p3_1)))+(assert (or (not p0_1) (not p4_1)))+(assert (or (not p0_1) (not p5_1)))+(assert (or (not p0_1) (not p6_1)))+(assert (or (not p0_1) (not p7_1)))+(assert (or (not p0_1) (not p8_1)))+(assert (or (not p1_1) (not p2_1)))+(assert (or (not p1_1) (not p3_1)))+(assert (or (not p1_1) (not p4_1)))+(assert (or (not p1_1) (not p5_1)))+(assert (or (not p1_1) (not p6_1)))+(assert (or (not p1_1) (not p7_1)))+(assert (or (not p1_1) (not p8_1)))+(assert (or (not p2_1) (not p3_1)))+(assert (or (not p2_1) (not p4_1)))+(assert (or (not p2_1) (not p5_1)))+(assert (or (not p2_1) (not p6_1)))+(assert (or (not p2_1) (not p7_1)))+(assert (or (not p2_1) (not p8_1)))+(assert (or (not p3_1) (not p4_1)))+(assert (or (not p3_1) (not p5_1)))+(assert (or (not p3_1) (not p6_1)))+(assert (or (not p3_1) (not p7_1)))+(assert (or (not p3_1) (not p8_1)))+(assert (or (not p4_1) (not p5_1)))+(assert (or (not p4_1) (not p6_1)))+(assert (or (not p4_1) (not p7_1)))+(assert (or (not p4_1) (not p8_1)))+(assert (or (not p5_1) (not p6_1)))+(assert (or (not p5_1) (not p7_1)))+(assert (or (not p5_1) (not p8_1)))+(assert (or (not p6_1) (not p7_1)))+(assert (or (not p6_1) (not p8_1)))+(assert (or (not p7_1) (not p8_1)))+(assert (or (not p0_2) (not p1_2)))+(assert (or (not p0_2) (not p2_2)))+(assert (or (not p0_2) (not p3_2)))+(assert (or (not p0_2) (not p4_2)))+(assert (or (not p0_2) (not p5_2)))+(assert (or (not p0_2) (not p6_2)))+(assert (or (not p0_2) (not p7_2)))+(assert (or (not p0_2) (not p8_2)))+(assert (or (not p1_2) (not p2_2)))+(assert (or (not p1_2) (not p3_2)))+(assert (or (not p1_2) (not p4_2)))+(assert (or (not p1_2) (not p5_2)))+(assert (or (not p1_2) (not p6_2)))+(assert (or (not p1_2) (not p7_2)))+(assert (or (not p1_2) (not p8_2)))+(assert (or (not p2_2) (not p3_2)))+(assert (or (not p2_2) (not p4_2)))+(assert (or (not p2_2) (not p5_2)))+(assert (or (not p2_2) (not p6_2)))+(assert (or (not p2_2) (not p7_2)))+(assert (or (not p2_2) (not p8_2)))+(assert (or (not p3_2) (not p4_2)))+(assert (or (not p3_2) (not p5_2)))+(assert (or (not p3_2) (not p6_2)))+(assert (or (not p3_2) (not p7_2)))+(assert (or (not p3_2) (not p8_2)))+(assert (or (not p4_2) (not p5_2)))+(assert (or (not p4_2) (not p6_2)))+(assert (or (not p4_2) (not p7_2)))+(assert (or (not p4_2) (not p8_2)))+(assert (or (not p5_2) (not p6_2)))+(assert (or (not p5_2) (not p7_2)))+(assert (or (not p5_2) (not p8_2)))+(assert (or (not p6_2) (not p7_2)))+(assert (or (not p6_2) (not p8_2)))+(assert (or (not p7_2) (not p8_2)))+(assert (or (not p0_3) (not p1_3)))+(assert (or (not p0_3) (not p2_3)))+(assert (or (not p0_3) (not p3_3)))+(assert (or (not p0_3) (not p4_3)))+(assert (or (not p0_3) (not p5_3)))+(assert (or (not p0_3) (not p6_3)))+(assert (or (not p0_3) (not p7_3)))+(assert (or (not p0_3) (not p8_3)))+(assert (or (not p1_3) (not p2_3)))+(assert (or (not p1_3) (not p3_3)))+(assert (or (not p1_3) (not p4_3)))+(assert (or (not p1_3) (not p5_3)))+(assert (or (not p1_3) (not p6_3)))+(assert (or (not p1_3) (not p7_3)))+(assert (or (not p1_3) (not p8_3)))+(assert (or (not p2_3) (not p3_3)))+(assert (or (not p2_3) (not p4_3)))+(assert (or (not p2_3) (not p5_3)))+(assert (or (not p2_3) (not p6_3)))+(assert (or (not p2_3) (not p7_3)))+(assert (or (not p2_3) (not p8_3)))+(assert (or (not p3_3) (not p4_3)))+(assert (or (not p3_3) (not p5_3)))+(assert (or (not p3_3) (not p6_3)))+(assert (or (not p3_3) (not p7_3)))+(assert (or (not p3_3) (not p8_3)))+(assert (or (not p4_3) (not p5_3)))+(assert (or (not p4_3) (not p6_3)))+(assert (or (not p4_3) (not p7_3)))+(assert (or (not p4_3) (not p8_3)))+(assert (or (not p5_3) (not p6_3)))+(assert (or (not p5_3) (not p7_3)))+(assert (or (not p5_3) (not p8_3)))+(assert (or (not p6_3) (not p7_3)))+(assert (or (not p6_3) (not p8_3)))+(assert (or (not p7_3) (not p8_3)))+(assert (or (not p0_4) (not p1_4)))+(assert (or (not p0_4) (not p2_4)))+(assert (or (not p0_4) (not p3_4)))+(assert (or (not p0_4) (not p4_4)))+(assert (or (not p0_4) (not p5_4)))+(assert (or (not p0_4) (not p6_4)))+(assert (or (not p0_4) (not p7_4)))+(assert (or (not p0_4) (not p8_4)))+(assert (or (not p1_4) (not p2_4)))+(assert (or (not p1_4) (not p3_4)))+(assert (or (not p1_4) (not p4_4)))+(assert (or (not p1_4) (not p5_4)))+(assert (or (not p1_4) (not p6_4)))+(assert (or (not p1_4) (not p7_4)))+(assert (or (not p1_4) (not p8_4)))+(assert (or (not p2_4) (not p3_4)))+(assert (or (not p2_4) (not p4_4)))+(assert (or (not p2_4) (not p5_4)))+(assert (or (not p2_4) (not p6_4)))+(assert (or (not p2_4) (not p7_4)))+(assert (or (not p2_4) (not p8_4)))+(assert (or (not p3_4) (not p4_4)))+(assert (or (not p3_4) (not p5_4)))+(assert (or (not p3_4) (not p6_4)))+(assert (or (not p3_4) (not p7_4)))+(assert (or (not p3_4) (not p8_4)))+(assert (or (not p4_4) (not p5_4)))+(assert (or (not p4_4) (not p6_4)))+(assert (or (not p4_4) (not p7_4)))+(assert (or (not p4_4) (not p8_4)))+(assert (or (not p5_4) (not p6_4)))+(assert (or (not p5_4) (not p7_4)))+(assert (or (not p5_4) (not p8_4)))+(assert (or (not p6_4) (not p7_4)))+(assert (or (not p6_4) (not p8_4)))+(assert (or (not p7_4) (not p8_4)))+(assert (or (not p0_5) (not p1_5)))+(assert (or (not p0_5) (not p2_5)))+(assert (or (not p0_5) (not p3_5)))+(assert (or (not p0_5) (not p4_5)))+(assert (or (not p0_5) (not p5_5)))+(assert (or (not p0_5) (not p6_5)))+(assert (or (not p0_5) (not p7_5)))+(assert (or (not p0_5) (not p8_5)))+(assert (or (not p1_5) (not p2_5)))+(assert (or (not p1_5) (not p3_5)))+(assert (or (not p1_5) (not p4_5)))+(assert (or (not p1_5) (not p5_5)))+(assert (or (not p1_5) (not p6_5)))+(assert (or (not p1_5) (not p7_5)))+(assert (or (not p1_5) (not p8_5)))+(assert (or (not p2_5) (not p3_5)))+(assert (or (not p2_5) (not p4_5)))+(assert (or (not p2_5) (not p5_5)))+(assert (or (not p2_5) (not p6_5)))+(assert (or (not p2_5) (not p7_5)))+(assert (or (not p2_5) (not p8_5)))+(assert (or (not p3_5) (not p4_5)))+(assert (or (not p3_5) (not p5_5)))+(assert (or (not p3_5) (not p6_5)))+(assert (or (not p3_5) (not p7_5)))+(assert (or (not p3_5) (not p8_5)))+(assert (or (not p4_5) (not p5_5)))+(assert (or (not p4_5) (not p6_5)))+(assert (or (not p4_5) (not p7_5)))+(assert (or (not p4_5) (not p8_5)))+(assert (or (not p5_5) (not p6_5)))+(assert (or (not p5_5) (not p7_5)))+(assert (or (not p5_5) (not p8_5)))+(assert (or (not p6_5) (not p7_5)))+(assert (or (not p6_5) (not p8_5)))+(assert (or (not p7_5) (not p8_5)))+(assert (or (not p0_6) (not p1_6)))+(assert (or (not p0_6) (not p2_6)))+(assert (or (not p0_6) (not p3_6)))+(assert (or (not p0_6) (not p4_6)))+(assert (or (not p0_6) (not p5_6)))+(assert (or (not p0_6) (not p6_6)))+(assert (or (not p0_6) (not p7_6)))+(assert (or (not p0_6) (not p8_6)))+(assert (or (not p1_6) (not p2_6)))+(assert (or (not p1_6) (not p3_6)))+(assert (or (not p1_6) (not p4_6)))+(assert (or (not p1_6) (not p5_6)))+(assert (or (not p1_6) (not p6_6)))+(assert (or (not p1_6) (not p7_6)))+(assert (or (not p1_6) (not p8_6)))+(assert (or (not p2_6) (not p3_6)))+(assert (or (not p2_6) (not p4_6)))+(assert (or (not p2_6) (not p5_6)))+(assert (or (not p2_6) (not p6_6)))+(assert (or (not p2_6) (not p7_6)))+(assert (or (not p2_6) (not p8_6)))+(assert (or (not p3_6) (not p4_6)))+(assert (or (not p3_6) (not p5_6)))+(assert (or (not p3_6) (not p6_6)))+(assert (or (not p3_6) (not p7_6)))+(assert (or (not p3_6) (not p8_6)))+(assert (or (not p4_6) (not p5_6)))+(assert (or (not p4_6) (not p6_6)))+(assert (or (not p4_6) (not p7_6)))+(assert (or (not p4_6) (not p8_6)))+(assert (or (not p5_6) (not p6_6)))+(assert (or (not p5_6) (not p7_6)))+(assert (or (not p5_6) (not p8_6)))+(assert (or (not p6_6) (not p7_6)))+(assert (or (not p6_6) (not p8_6)))+(assert (or (not p7_6) (not p8_6)))+(assert (or (not p0_7) (not p1_7)))+(assert (or (not p0_7) (not p2_7)))+(assert (or (not p0_7) (not p3_7)))+(assert (or (not p0_7) (not p4_7)))+(assert (or (not p0_7) (not p5_7)))+(assert (or (not p0_7) (not p6_7)))+(assert (or (not p0_7) (not p7_7)))+(assert (or (not p0_7) (not p8_7)))+(assert (or (not p1_7) (not p2_7)))+(assert (or (not p1_7) (not p3_7)))+(assert (or (not p1_7) (not p4_7)))+(assert (or (not p1_7) (not p5_7)))+(assert (or (not p1_7) (not p6_7)))+(assert (or (not p1_7) (not p7_7)))+(assert (or (not p1_7) (not p8_7)))+(assert (or (not p2_7) (not p3_7)))+(assert (or (not p2_7) (not p4_7)))+(assert (or (not p2_7) (not p5_7)))+(assert (or (not p2_7) (not p6_7)))+(assert (or (not p2_7) (not p7_7)))+(assert (or (not p2_7) (not p8_7)))+(assert (or (not p3_7) (not p4_7)))+(assert (or (not p3_7) (not p5_7)))+(assert (or (not p3_7) (not p6_7)))+(assert (or (not p3_7) (not p7_7)))+(assert (or (not p3_7) (not p8_7)))+(assert (or (not p4_7) (not p5_7)))+(assert (or (not p4_7) (not p6_7)))+(assert (or (not p4_7) (not p7_7)))+(assert (or (not p4_7) (not p8_7)))+(assert (or (not p5_7) (not p6_7)))+(assert (or (not p5_7) (not p7_7)))+(assert (or (not p5_7) (not p8_7)))+(assert (or (not p6_7) (not p7_7)))+(assert (or (not p6_7) (not p8_7)))+(assert (or (not p7_7) (not p8_7)))+(check-sat)+(exit)
+ bench/smtlib/QF_UF/pigeonhole_uf5.smt2 view
@@ -0,0 +1,42 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UF)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-sort P 0)+(declare-sort H 0)+(declare-fun f (P) H)+(declare-const p0 P)+(declare-const p1 P)+(declare-const p2 P)+(declare-const p3 P)+(declare-const p4 P)+(declare-const p5 P)+(declare-const h0 H)+(declare-const h1 H)+(declare-const h2 H)+(declare-const h3 H)+(declare-const h4 H)+(assert (distinct p0 p1 p2 p3 p4 p5))+(assert (or (= (f p0) h0) (= (f p0) h1) (= (f p0) h2) (= (f p0) h3) (= (f p0) h4)))+(assert (or (= (f p1) h0) (= (f p1) h1) (= (f p1) h2) (= (f p1) h3) (= (f p1) h4)))+(assert (or (= (f p2) h0) (= (f p2) h1) (= (f p2) h2) (= (f p2) h3) (= (f p2) h4)))+(assert (or (= (f p3) h0) (= (f p3) h1) (= (f p3) h2) (= (f p3) h3) (= (f p3) h4)))+(assert (or (= (f p4) h0) (= (f p4) h1) (= (f p4) h2) (= (f p4) h3) (= (f p4) h4)))+(assert (or (= (f p5) h0) (= (f p5) h1) (= (f p5) h2) (= (f p5) h3) (= (f p5) h4)))+(assert (not (= (f p0) (f p1))))+(assert (not (= (f p0) (f p2))))+(assert (not (= (f p0) (f p3))))+(assert (not (= (f p0) (f p4))))+(assert (not (= (f p0) (f p5))))+(assert (not (= (f p1) (f p2))))+(assert (not (= (f p1) (f p3))))+(assert (not (= (f p1) (f p4))))+(assert (not (= (f p1) (f p5))))+(assert (not (= (f p2) (f p3))))+(assert (not (= (f p2) (f p4))))+(assert (not (= (f p2) (f p5))))+(assert (not (= (f p3) (f p4))))+(assert (not (= (f p3) (f p5))))+(assert (not (= (f p4) (f p5))))+(check-sat)+(exit)
+ bench/smtlib/QF_UFLIA/array_like.smt2 view
@@ -0,0 +1,12 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UFLIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-fun mem (Int) Int)+(declare-const i Int)+(declare-const j Int)+(assert (= (+ i 2) (* 2 j)))+(assert (= i (- (* 2 j) 2)))+(assert (not (= (mem i) (mem (- (* 2 j) 2)))))+(check-sat)+(exit)
+ bench/smtlib/QF_UFLIA/monotone.smt2 view
@@ -0,0 +1,13 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_UFLIA)+(set-info :source |hsmt benchmark set|)+(set-info :status unsat)+(declare-fun f (Int) Int)+(declare-const a Int)+(declare-const b Int)+(assert (=> (<= a b) (<= (f a) (f b))))+(assert (=> (<= b a) (<= (f b) (f a))))+(assert (= a (+ b 1)))+(assert (> (f b) (f a)))+(check-sat)+(exit)
+ bench/smtlib/incremental/bounded_counter.smt2 view
@@ -0,0 +1,26 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_LIA)+(set-info :source |hsmt benchmark set: one status per check-sat|)+(declare-const x0 Int)+(declare-const x1 Int)+(declare-const x2 Int)+(declare-const x3 Int)+(assert (= x0 0))+(assert (or (= x1 (+ x0 2)) (= x1 (+ x0 3))))+(assert (or (= x2 (+ x1 2)) (= x2 (+ x1 3))))+(assert (or (= x3 (+ x2 2)) (= x3 (+ x2 3))))+(push 1)+(assert (= x3 7))+(set-info :status sat)+(check-sat)+(pop 1)+(push 1)+(assert (= x3 5))+(set-info :status unsat)+(check-sat)+(pop 1)+(set-info :status unsat)+(check-sat-assuming ((> x3 9)))+(set-info :status sat)+(check-sat-assuming ((= x3 9) (= x1 3)))+(exit)
+ bench/smtlib/incremental/bv_sessions.smt2 view
@@ -0,0 +1,26 @@+(set-info :smt-lib-version 2.6)+(set-logic QF_BV)+(set-info :source |hsmt benchmark set: many checks over one session|)+(declare-const x (_ BitVec 16))+(declare-const y (_ BitVec 16))+(assert (= (bvmul x y) #x0399))+(assert (bvult x y))+(push 1)+(assert (= x #x0001))+(set-info :status sat)+(check-sat)+(pop 1)+(push 1)+(assert (bvugt x #x0001))+(assert (bvult y #x0100))+(set-info :status unsat)+(check-sat)+(pop 1)+(push 1)+(assert (= ((_ extract 0 0) x) #b0))+(set-info :status unsat)+(check-sat)+(pop 1)+(set-info :status unsat)+(check-sat-assuming ((bvugt x #x0100) (bvult y #x0100)))+(exit)
+ bench/smtlib/incremental/scoped_declarations.smt2 view
@@ -0,0 +1,30 @@+(set-info :smt-lib-version 2.6)+(set-logic ALL)+(set-info :source |hsmt benchmark set: declarations removed by pop|)+(declare-fun f (Int) Int)+(push 1)+(declare-const x Int)+(assert (= (f x) x))+(assert (= (f (f x)) (+ x 1)))+(set-info :status unsat)+(check-sat)+(pop 1)+(push 1)+(declare-const x (_ BitVec 4))+(declare-fun g ((_ BitVec 4)) Int)+(assert (= (f (g x)) 3))+(assert (= (g (bvadd x #x1)) (g x)))+(set-info :status sat)+(check-sat)+(pop 1)+(push 1)+(declare-const x String)+(assert (= (f (str.len x)) (str.len x)))+(assert (= (str.len x) 2))+(assert (= (f 2) 3))+(set-info :status unsat)+(check-sat)+(pop 1)+(set-info :status sat)+(check-sat)+(exit)
+ hsmt.cabal view
@@ -0,0 +1,166 @@+cabal-version: 3.0+name: hsmt+version: 0.1.0.0+synopsis: An SMT solver written in Haskell with a type-safe API+description:+ hsmt is an SMT solver implemented in Haskell. It offers a type-safe+ embedded API, a CDCL(T) core and decision procedures for integers,+ strings, arrays, bit-vectors, records and floating point, and an+ SMT-LIB 2.6 front end. See "HSMT.Tutorial" for a tutorial.+license: BSD-3-Clause+license-file: LICENSE+author: rodrigogribeiro+maintainer: rodrigo.ribeiro@ufop.edu.br+copyright: (c) 2026 rodrigogribeiro+homepage: https://github.com/rodrigogribeiro/hsmt+bug-reports: https://github.com/rodrigogribeiro/hsmt/issues+category: Language, Logic+build-type: Simple+tested-with: GHC == 9.10.3+extra-doc-files:+ CHANGELOG.md+ README.md+extra-source-files:+ test/regressions/*.smt2+ bench/smtlib/**/*.smt2++source-repository head+ type: git+ location: https://github.com/rodrigogribeiro/hsmt.git++common common+ default-language: GHC2021+ default-extensions:+ DataKinds+ LambdaCase+ OverloadedStrings+ ghc-options:+ -Wall -Wcompat -Wincomplete-uni-patterns+ -Wincomplete-record-updates -Wredundant-constraints+ build-depends:+ base ^>=4.20,+ containers >=0.6 && <0.8,+ text >=2.0 && <2.2++library+ import: common+ hs-source-dirs: src+ exposed-modules:+ HSMT+ HSMT.Tutorial+ HSMT.API.Sort+ HSMT.API.Expr+ HSMT.API.Monad+ HSMT.API.Model+ HSMT.Core.Sort+ HSMT.Core.Op+ HSMT.Core.Expr+ HSMT.Core.Typing+ HSMT.Core.Term+ HSMT.Core.Value+ HSMT.Core.Float+ HSMT.Core.Regex+ HSMT.Core.Eval+ HSMT.SMT.Engine+ HSMT.Backend+ HSMT.Backend.External+ HSMT.Theory.EUF+ HSMT.Theory.Arith+ HSMT.Theory.Arith.Simplex+ HSMT.Theory.BitBlast+ HSMT.Theory.FloatBlast+ HSMT.SAT.Types+ HSMT.SAT.Solver+ HSMT.SAT.Dimacs+ HSMT.SMTLib.Syntax+ HSMT.SMTLib.Printer+ HSMT.SMTLib.Parser+ HSMT.SMTLib.Run+ HSMT.Util.GrowVec+ other-modules:+ Paths_hsmt+ autogen-modules:+ Paths_hsmt+ build-depends:+ filepath >=1.4 && <1.6,+ mtl ^>=2.3,+ process >=1.6 && <1.7,+ vector >=0.13 && <0.14++executable hsmt+ import: common+ main-is: Main.hs+ hs-source-dirs: app+ other-modules: Paths_hsmt+ autogen-modules: Paths_hsmt+ build-depends: hsmt+ ghc-options: -rtsopts++test-suite hsmt-test+ import: common+ type: exitcode-stdio-1.0+ hs-source-dirs: test test-common+ main-is: Main.hs+ other-modules:+ HSMT.SATSpec+ HSMT.EvalSpec+ HSMT.APISpec+ HSMT.EUFSpec+ HSMT.LIASpec+ HSMT.ArraySpec+ HSMT.RecordSpec+ HSMT.StringSpec+ HSMT.RegexSpec+ HSMT.FloatSpec+ HSMT.BVSpec+ HSMT.SMTLibSpec+ HSMT.TutorialSpec+ HSMT.IncrementalSpec+ HSMT.RegressionSpec+ HSMT.Gen.Expr+ HSMT.Benchmarks+ build-depends:+ hsmt,+ directory >=1.3 && <1.4,+ filepath >=1.4 && <1.6,+ tasty >=1.4 && <1.6,+ tasty-hunit >=0.10 && <0.11,+ tasty-quickcheck >=0.10 && <0.12,+ QuickCheck >=2.14 && <2.17+ ghc-options: -threaded -rtsopts++-- Differential tests against Z3; skipped when z3 is not available.+test-suite hsmt-diff+ import: common+ type: exitcode-stdio-1.0+ hs-source-dirs: test-diff test-common+ main-is: Main.hs+ other-modules:+ Differential.Z3+ Differential.Oracle+ HSMT.Gen.Expr+ build-depends:+ hsmt,+ directory >=1.3 && <1.4,+ filepath >=1.4 && <1.6,+ process >=1.6 && <1.7,+ tasty >=1.4 && <1.6,+ tasty-quickcheck >=0.10 && <0.12,+ QuickCheck >=2.14 && <2.17+ ghc-options: -threaded -rtsopts++-- Runs the SMT-LIB benchmarks in bench/smtlib with hsmt and, when it is+-- available, with Z3, comparing answers and times.+benchmark hsmt-bench+ import: common+ type: exitcode-stdio-1.0+ hs-source-dirs: bench test-common+ main-is: Main.hs+ other-modules:+ HSMT.Benchmarks+ build-depends:+ hsmt,+ directory >=1.3 && <1.4,+ filepath >=1.4 && <1.6,+ process >=1.6 && <1.7+ ghc-options: -threaded -rtsopts
+ src/HSMT.hs view
@@ -0,0 +1,70 @@+-- | hsmt: an SMT solver with a type-safe API.+--+-- > {-# LANGUAGE DataKinds, OverloadedStrings, OverloadedLabels, TypeApplications #-}+-- > import HSMT+-- >+-- > example :: IO (Maybe Bool)+-- > example = runSMT defaultConfig $ do+-- > p <- declare @BoolS "p"+-- > q <- declare @BoolS "q"+-- > assert (p .|| q)+-- > assert (notB p)+-- > checkSat >>= \case+-- > Sat m -> pure (Just (eval m q))+-- > _ -> pure Nothing+module HSMT+ ( -- * Running the solver+ SMT+ , runSMT+ , Config (..)+ , defaultConfig+ , Backend (..)+ , ExternalSolver (..)+ , Dialect (..)+ , z3Backend+ , SMTError (..)+ , Result (..)+ , Core+ , coreAssertions+ , coreAssumptions+ , declare+ , declareFun+ , fresh+ , assert+ , push+ , pop+ , scoped+ , checkSat+ , checkSatAssuming+ -- * Sorts and values+ , Sort (..)+ , KnownSort+ , Value+ , BitVector (..)+ , ArrayValue (..)+ , RecordValue+ , Uninterp (..)+ , FloatingPoint (..)+ , RoundingMode (..)+ , Float16S+ , Float32S+ , Float64S+ , floatValue+ , floatFromValue+ , toFloat+ , fromFloat+ , toDouble+ , fromDouble+ -- * Models+ , Model+ , eval+ , field+ -- * Expressions+ , module HSMT.API.Expr+ ) where++import HSMT.API.Expr hiding (CurryFn (..), Expr (..))+import HSMT.API.Expr (Expr)+import HSMT.API.Model+import HSMT.API.Monad+import HSMT.API.Sort
+ src/HSMT/API/Expr.hs view
@@ -0,0 +1,873 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+-- Some constraints (e.g. @1 <= n@ or the bounds of 'bvExtract') are not+-- needed by the implementation: they exist only to reject ill-formed+-- expressions at compile time.+{-# OPTIONS_GHC -Wno-redundant-constraints #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE UndecidableInstances #-}++-- | Typed expressions.+--+-- @Expr ctx s@ is an expression of sort @s@ belonging to the solver instance+-- @ctx@ (see 'HSMT.API.Monad.runSMT'). Only well-sorted expressions can be+-- built: sort errors are Haskell type errors.+module HSMT.API.Expr+ ( Expr (..)+ -- * Booleans+ , true+ , false+ , bool+ , notB+ , (.&&)+ , (.||)+ , (.=>)+ , xorB+ , andB+ , orB+ , ite+ , (.==)+ , (./=)+ , distinct+ -- * Integers+ , int+ , (.<)+ , (.<=)+ , (.>)+ , (.>=)+ , idiv+ , imod+ -- * Bit-vectors+ , bv+ , bvNot+ , bvAnd+ , bvOr+ , bvXor+ , bvNeg+ , bvAdd+ , bvSub+ , bvMul+ , bvUDiv+ , bvURem+ , bvSDiv+ , bvSRem+ , bvSMod+ , bvShl+ , bvLShr+ , bvAShr+ , bvConcat+ , bvExtract+ , bvZeroExtend+ , bvSignExtend+ , bvULt+ , bvULe+ , bvUGt+ , bvUGe+ , bvSLt+ , bvSLe+ , bvSGt+ , bvSGe+ -- * Arrays+ , select+ , store+ , constArray+ -- * Strings+ , str+ , (<+>)+ , strLen+ , strAt+ , substr+ , contains+ , prefixOf+ , suffixOf+ , indexOf+ , replace+ , strToInt+ , strFromInt+ , strLt+ , strLe+ -- * Regular expressions+ , toRe+ , inRe+ , reNone+ , reAll+ , reAllChar+ , reRange+ , reConcat+ , reUnion+ , reInter+ , reStar+ , rePlus+ , reOpt+ , reComp+ , reDiff+ , reLoop+ , rePower+ -- * Floating point+ , rne+ , rna+ , rtp+ , rtn+ , rtz+ , roundingMode+ , fpValue+ , fpLit+ , fpNaN+ , fpInf+ , fpZero+ , fpFromFields+ , fpFromBV+ , fpAbs+ , fpNeg+ , fpAdd+ , fpSub+ , fpMul+ , fpDiv+ , fpFma+ , fpSqrt+ , fpRem+ , fpRoundToIntegral+ , fpMin+ , fpMax+ , fpLeq+ , fpLt+ , fpGeq+ , fpGt+ , fpEq+ , fpIsNormal+ , fpIsSubnormal+ , fpIsZero+ , fpIsInfinite+ , fpIsNaN+ , fpIsNegative+ , fpIsPositive+ , toFP+ , sbvToFP+ , ubvToFP+ , fpToUBV+ , fpToSBV+ -- * Records+ , Label (..)+ , Field (..)+ , Fields (..)+ , record+ , (!)+ , getField+ , setField+ -- * Uninterpreted functions+ , Fn+ , CurryFn (..)+ ) where++import Data.Kind (Type)+import Data.Proxy (Proxy (..))+import Data.String (IsString (..))+import Data.Text (Text)+import qualified Data.Text as T+import GHC.OverloadedLabels (IsLabel (..))+import GHC.TypeLits++import HSMT.API.Sort+import qualified HSMT.Core.Expr as C+import qualified HSMT.Core.Float as F+import HSMT.Core.Op (Op (..))+import qualified HSMT.Core.Value as C++-- | A typed expression. The constructor is internal; use the smart+-- constructors in this module.+--+-- t'Eq' and t'Ord' compare expressions structurally (for instance to look+-- for an assertion in an unsatisfiable core); use '.==' for the equality+-- of the logic.+newtype Expr (ctx :: Type) (s :: Sort) = Expr {unExpr :: C.Expr}+ deriving (Eq, Ord)++instance Show (Expr ctx s) where+ show (Expr e) = show e++op0 :: Op -> Expr ctx s+op0 o = Expr (C.App o [])++op1 :: Op -> Expr ctx a -> Expr ctx s+op1 o (Expr a) = Expr (C.App o [a])++op2 :: Op -> Expr ctx a -> Expr ctx b -> Expr ctx s+op2 o (Expr a) (Expr b) = Expr (C.App o [a, b])++op3 :: Op -> Expr ctx a -> Expr ctx b -> Expr ctx c -> Expr ctx s+op3 o (Expr a) (Expr b) (Expr c) = Expr (C.App o [a, b, c])++opN :: Op -> [Expr ctx a] -> Expr ctx s+opN o es = Expr (C.App o (map unExpr es))++-------------------------------------------------------------------------------+-- Booleans++infixr 3 .&&+infixr 2 .||+infixr 1 .=>+infix 4 .==, ./=, .<, .<=, .>, .>=++-- | The Boolean constant true.+true :: Expr ctx 'BoolS+true = bool True++-- | The Boolean constant false.+false :: Expr ctx 'BoolS+false = bool False++-- | A Boolean literal.+bool :: Bool -> Expr ctx 'BoolS+bool = op0 . BoolConst++-- | Negation.+notB :: Expr ctx 'BoolS -> Expr ctx 'BoolS+notB = op1 Not++-- | Conjunction.+(.&&) :: Expr ctx 'BoolS -> Expr ctx 'BoolS -> Expr ctx 'BoolS+(.&&) = op2 And++-- | Disjunction.+(.||) :: Expr ctx 'BoolS -> Expr ctx 'BoolS -> Expr ctx 'BoolS+(.||) = op2 Or++-- | Implication (right associative).+(.=>) :: Expr ctx 'BoolS -> Expr ctx 'BoolS -> Expr ctx 'BoolS+(.=>) = op2 Implies++-- | Exclusive or.+xorB :: Expr ctx 'BoolS -> Expr ctx 'BoolS -> Expr ctx 'BoolS+xorB = op2 Xor++-- | Conjunction of a list (true when empty).+andB :: [Expr ctx 'BoolS] -> Expr ctx 'BoolS+andB = opN And++-- | Disjunction of a list (false when empty).+orB :: [Expr ctx 'BoolS] -> Expr ctx 'BoolS+orB = opN Or++-- | @ite c t e@ is @t@ when @c@ holds and @e@ otherwise, for any sort.+ite :: Expr ctx 'BoolS -> Expr ctx s -> Expr ctx s -> Expr ctx s+ite = op3 Ite++-- | Equality, for any sort (extensional for arrays, field-wise for+-- records; for floating point it is the identity of values, see 'fpEq').+(.==) :: Expr ctx s -> Expr ctx s -> Expr ctx 'BoolS+(.==) = op2 Eq++-- | Disequality: @a ./= b = notB (a .== b)@.+(./=) :: Expr ctx s -> Expr ctx s -> Expr ctx 'BoolS+a ./= b = notB (a .== b)++-- | Pairwise distinctness. Lists with fewer than two elements are trivially+-- distinct.+distinct :: [Expr ctx s] -> Expr ctx 'BoolS+distinct es+ | length es < 2 = true+ | otherwise = opN Distinct es++-------------------------------------------------------------------------------+-- Integers++-- | An integer literal. Integer literals can also be written directly,+-- through the 'Num' instance.+int :: Integer -> Expr ctx 'IntS+int = op0 . IntConst++-- | Integer arithmetic. Multiplication is supported by the solver only when+-- one of the factors is a constant; other products make 'HSMT.checkSat'+-- answer unknown.+instance Num (Expr ctx 'IntS) where+ fromInteger = int+ (+) = op2 Add+ (-) = op2 Sub+ (*) = op2 Mul+ negate = op1 Neg+ abs = op1 Abs+ signum x = ite (x .> 0) 1 (ite (x .< 0) (-1) 0)++-- | Integer less than.+(.<) :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'BoolS+(.<) = op2 Lt++-- | Integer less than or equal.+(.<=) :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'BoolS+(.<=) = op2 Le++-- | Integer greater than.+(.>) :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'BoolS+(.>) = op2 Gt++-- | Integer greater than or equal.+(.>=) :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'BoolS+(.>=) = op2 Ge++-- | Euclidean division (SMT-LIB @div@): the remainder 'imod' is never+-- negative. The divisor must be a constant for the solver; division by+-- zero is unspecified (an uninterpreted function of the dividend).+idiv :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'IntS+idiv = op2 IntDiv++-- | Euclidean remainder (SMT-LIB @mod@), between 0 and the absolute value+-- of the divisor minus one.+imod :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'IntS+imod = op2 IntMod++-------------------------------------------------------------------------------+-- Bit-vectors++widthOf :: forall n. KnownNat n => Int+widthOf = fromIntegral (natVal (Proxy @n))++-- | A bit-vector literal; the integer is taken modulo @2^n@, so negative+-- numbers give their two's complement representation.+bv :: forall n ctx. (KnownNat n, 1 <= n) => Integer -> Expr ctx ('BVS n)+bv x = let w = widthOf @n in op0 (BVConst w (C.bvNormalize w x))++-- | Arithmetic is modulo @2^n@; 'abs' and 'signum' use the signed+-- interpretation.+instance (KnownNat n, 1 <= n) => Num (Expr ctx ('BVS n)) where+ fromInteger = bv+ (+) = bvAdd+ (-) = bvSub+ (*) = bvMul+ negate = bvNeg+ abs x = ite (bvSLt x 0) (bvNeg x) x+ signum x = ite (bvSGt x 0) 1 (ite (bvSLt x 0) (bv (-1)) 0)++type BVUn n = forall ctx. Expr ctx ('BVS n) -> Expr ctx ('BVS n)++type BVBin n = forall ctx. Expr ctx ('BVS n) -> Expr ctx ('BVS n) -> Expr ctx ('BVS n)++type BVCmp n = forall ctx. Expr ctx ('BVS n) -> Expr ctx ('BVS n) -> Expr ctx 'BoolS++-- | Bitwise complement.+bvNot :: BVUn n+bvNot = op1 BVNot++-- | Two's complement negation.+bvNeg :: BVUn n+bvNeg = op1 BVNeg++-- | Bitwise and.+bvAnd :: BVBin n+bvAnd = op2 BVAnd++-- | Bitwise or.+bvOr :: BVBin n+bvOr = op2 BVOr++-- | Bitwise exclusive or.+bvXor :: BVBin n+bvXor = op2 BVXor++-- | Addition modulo @2^n@.+bvAdd :: BVBin n+bvAdd = op2 BVAdd++-- | Subtraction modulo @2^n@.+bvSub :: BVBin n+bvSub = op2 BVSub++-- | Multiplication modulo @2^n@.+bvMul :: BVBin n+bvMul = op2 BVMul++-- | Unsigned division; division by zero gives all ones, as in SMT-LIB.+bvUDiv :: BVBin n+bvUDiv = op2 BVUDiv++-- | Unsigned remainder; the remainder of a division by zero is the dividend.+bvURem :: BVBin n+bvURem = op2 BVURem++-- | Signed division, rounding towards zero.+bvSDiv :: BVBin n+bvSDiv = op2 BVSDiv++-- | Signed remainder, with the sign of the dividend.+bvSRem :: BVBin n+bvSRem = op2 BVSRem++-- | Signed modulo, with the sign of the divisor.+bvSMod :: BVBin n+bvSMod = op2 BVSMod++-- | Shift left by the (unsigned) value of the second argument.+bvShl :: BVBin n+bvShl = op2 BVShl++-- | Logical shift right (filling with zeros).+bvLShr :: BVBin n+bvLShr = op2 BVLShr++-- | Arithmetic shift right (filling with the sign bit).+bvAShr :: BVBin n+bvAShr = op2 BVAShr++-- | Unsigned less than.+bvULt :: BVCmp n+bvULt = op2 BVULt++-- | Unsigned less than or equal.+bvULe :: BVCmp n+bvULe = op2 BVULe++-- | Unsigned greater than.+bvUGt :: BVCmp n+bvUGt = op2 BVUGt++-- | Unsigned greater than or equal.+bvUGe :: BVCmp n+bvUGe = op2 BVUGe++-- | Signed (two's complement) less than.+bvSLt :: BVCmp n+bvSLt = op2 BVSLt++-- | Signed less than or equal.+bvSLe :: BVCmp n+bvSLe = op2 BVSLe++-- | Signed greater than.+bvSGt :: BVCmp n+bvSGt = op2 BVSGt++-- | Signed greater than or equal.+bvSGe :: BVCmp n+bvSGe = op2 BVSGe++-- | Concatenation; the first argument gives the most significant bits.+bvConcat :: Expr ctx ('BVS n) -> Expr ctx ('BVS m) -> Expr ctx ('BVS (n + m))+bvConcat = op2 BVConcat++-- | @bvExtract \@hi \@lo x@ selects bits @hi@ down to @lo@ of @x@.+bvExtract+ :: forall hi lo n ctx+ . (KnownNat hi, KnownNat lo, lo <= hi, hi + 1 <= n)+ => Expr ctx ('BVS n)+ -> Expr ctx ('BVS (hi - lo + 1))+bvExtract = op1 (BVExtract (widthOf @hi) (widthOf @lo))++-- | Extend with @k@ zero bits.+bvZeroExtend :: forall k n ctx. KnownNat k => Expr ctx ('BVS n) -> Expr ctx ('BVS (n + k))+bvZeroExtend = op1 (BVZeroExtend (widthOf @k))++-- | Extend with @k@ copies of the sign bit.+bvSignExtend :: forall k n ctx. KnownNat k => Expr ctx ('BVS n) -> Expr ctx ('BVS (n + k))+bvSignExtend = op1 (BVSignExtend (widthOf @k))++-------------------------------------------------------------------------------+-- Arrays++-- | The element at an index.+select :: Expr ctx ('ArrayS i e) -> Expr ctx i -> Expr ctx e+select = op2 Select++-- | @store a i v@ is the array equal to @a@ except at @i@, where it is @v@.+store :: Expr ctx ('ArrayS i e) -> Expr ctx i -> Expr ctx e -> Expr ctx ('ArrayS i e)+store = op3 Store++-- | The array mapping every index to the given value.+constArray :: forall i e ctx. KnownSort i => Expr ctx e -> Expr ctx ('ArrayS i e)+constArray = op1 (ConstArray (sortRep @i))++-------------------------------------------------------------------------------+-- Strings++-- | A string literal. With @OverloadedStrings@, literals can be written+-- directly, through the 'IsString' instance.+str :: Text -> Expr ctx 'StringS+str = op0 . StrConst++instance IsString (Expr ctx 'StringS) where+ fromString = str . T.pack++infixr 5 <+>++-- | String concatenation.+(<+>) :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'StringS+(<+>) = op2 StrConcat++-- | The length of a string, in characters (code points).+strLen :: Expr ctx 'StringS -> Expr ctx 'IntS+strLen = op1 StrLen++-- | The one-character string at a position (empty if out of range).+strAt :: Expr ctx 'StringS -> Expr ctx 'IntS -> Expr ctx 'StringS+strAt = op2 StrAt++-- | @substr s offset length@.+substr :: Expr ctx 'StringS -> Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'StringS+substr = op3 StrSubstr++-- | @contains s t@ holds when @t@ occurs in @s@.+contains :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS+contains = op2 StrContains++-- | @prefixOf s t@ holds when @s@ is a prefix of @t@.+prefixOf :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS+prefixOf = op2 StrPrefixOf++-- | @suffixOf s t@ holds when @s@ is a suffix of @t@.+suffixOf :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS+suffixOf = op2 StrSuffixOf++-- | @indexOf s t i@: first position of @t@ in @s@ at or after @i@, or -1.+indexOf :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'IntS -> Expr ctx 'IntS+indexOf = op3 StrIndexOf++-- | @replace s t t'@ replaces the first occurrence of @t@ in @s@ by @t'@.+replace :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'StringS+replace = op3 StrReplace++-- | The natural number written by a string of decimal digits, or -1 when+-- the string is empty or has another character.+strToInt :: Expr ctx 'StringS -> Expr ctx 'IntS+strToInt = op1 StrToInt++-- | The decimal representation of a natural number, or the empty string+-- for negative numbers.+strFromInt :: Expr ctx 'IntS -> Expr ctx 'StringS+strFromInt = op1 StrFromInt++-- | Lexicographic order by code point, strict.+strLt :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS+strLt = op2 StrLt++-- | Lexicographic order by code point, reflexive.+strLe :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS+strLe = op2 StrLe++-------------------------------------------------------------------------------+-- Regular expressions++-- | @str.to_re@: the language of one string. The string must be a literal+-- (or a term built from literals): the solver answers unknown for+-- regular expressions that depend on variables. With @OverloadedStrings@,+-- string literals can be used directly as regular expressions.+toRe :: Expr ctx 'StringS -> Expr ctx 'RegLanS+toRe = op1 StrToRe++instance IsString (Expr ctx 'RegLanS) where+ fromString = toRe . str . T.pack++-- | @inRe s r@ holds when the string @s@ belongs to the language @r@.+inRe :: Expr ctx 'StringS -> Expr ctx 'RegLanS -> Expr ctx 'BoolS+inRe = op2 StrInRe++-- | The empty language.+reNone :: Expr ctx 'RegLanS+reNone = op0 ReNone++-- | The language of all strings.+reAll :: Expr ctx 'RegLanS+reAll = op0 ReAll++-- | The language of all one-character strings.+reAllChar :: Expr ctx 'RegLanS+reAllChar = op0 ReAllChar++-- | The one-character strings between two characters (by code point).+reRange :: Char -> Char -> Expr ctx 'RegLanS+reRange a b = op2 ReRange (str (T.singleton a)) (str (T.singleton b))++-- | Concatenation of a list of languages (the empty string when empty).+reConcat :: [Expr ctx 'RegLanS] -> Expr ctx 'RegLanS+reConcat = \case+ [] -> toRe (str "")+ [r] -> r+ rs -> opN ReConcat rs++-- | Union of a list of languages (the empty language when empty).+reUnion :: [Expr ctx 'RegLanS] -> Expr ctx 'RegLanS+reUnion = \case+ [] -> reNone+ [r] -> r+ rs -> opN ReUnion rs++-- | Intersection of a list of languages (all strings when empty).+reInter :: [Expr ctx 'RegLanS] -> Expr ctx 'RegLanS+reInter = \case+ [] -> reAll+ [r] -> r+ rs -> opN ReInter rs++-- | Kleene star: zero or more repetitions.+reStar :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS+reStar = op1 ReStar++-- | One or more repetitions.+rePlus :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS+rePlus = op1 RePlus++-- | Zero or one occurrence.+reOpt :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS+reOpt = op1 ReOpt++-- | Complement: the strings not in the language.+reComp :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS+reComp = op1 ReComp++-- | Difference: the strings of the first language not in the second.+reDiff :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS -> Expr ctx 'RegLanS+reDiff = op2 ReDiff++-- | @reLoop i j r@: between @i@ and @j@ repetitions of @r@ (both+-- non-negative).+reLoop :: Int -> Int -> Expr ctx 'RegLanS -> Expr ctx 'RegLanS+reLoop i j = op1 (ReLoop (max 0 i) (max 0 j))++-- | @rePower n r@: exactly @n@ repetitions of @r@ (non-negative).+rePower :: Int -> Expr ctx 'RegLanS -> Expr ctx 'RegLanS+rePower n = op1 (RePower (max 0 n))++-------------------------------------------------------------------------------+-- Floating point++-- | Rounding modes: to nearest (ties to even, ties away from zero), towards+-- positive and negative infinity, and towards zero.+rne, rna, rtp, rtn, rtz :: Expr ctx 'RoundingModeS+rne = roundingMode RNE+rna = roundingMode RNA+rtp = roundingMode RTP+rtn = roundingMode RTN+rtz = roundingMode RTZ++-- | A rounding mode literal.+roundingMode :: RoundingMode -> Expr ctx 'RoundingModeS+roundingMode = op0 . RMConst++fpFormat :: forall eb sb. (KnownNat eb, KnownNat sb) => (Int, Int)+fpFormat = (widthOf @eb, widthOf @sb)++-- | A floating-point literal.+fpLit :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => FloatingPoint eb sb -> Expr ctx ('FPS eb sb)+fpLit (FloatingPoint x) = let (eb, sb) = fpFormat @eb @sb in op0 (FPConst eb sb (F.canonicalize eb sb x))++-- | The literal nearest to a rational number (ties to even).+fpValue :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => Rational -> Expr ctx ('FPS eb sb)+fpValue r = fpLit (floatFromValue @eb @sb (if r == 0 then F.Zero False else F.Finite (r < 0) (abs r)))++-- | Not a number. SMT-LIB has a single NaN.+fpNaN :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => Expr ctx ('FPS eb sb)+fpNaN = fpLit (floatFromValue @eb @sb F.NaN)++-- | The infinity of the given sign ('True' for negative).+fpInf :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => Bool -> Expr ctx ('FPS eb sb)+fpInf neg = fpLit (floatFromValue @eb @sb (F.Inf neg))++-- | The zero of the given sign ('True' for negative).+fpZero :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => Bool -> Expr ctx ('FPS eb sb)+fpZero neg = fpLit (floatFromValue @eb @sb (F.Zero neg))++-- | The @fp@ constructor: sign bit, biased exponent and trailing+-- significand.+fpFromFields :: Expr ctx ('BVS 1) -> Expr ctx ('BVS eb) -> Expr ctx ('BVS m) -> Expr ctx ('FPS eb (m + 1))+fpFromFields = op3 FPFromFields++-- | A bit pattern read as a floating-point number.+fpFromBV+ :: forall eb sb ctx+ . (KnownNat eb, KnownNat sb)+ => Expr ctx ('BVS (eb + sb))+ -> Expr ctx ('FPS eb sb)+fpFromBV = let (eb, sb) = fpFormat @eb @sb in op1 (ToFP eb sb)++type FPUn eb sb = forall ctx. Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)++type FPBin eb sb = forall ctx. Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)++type FPRounded eb sb =+ forall ctx. Expr ctx 'RoundingModeS -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)++type FPPred eb sb = forall ctx. Expr ctx ('FPS eb sb) -> Expr ctx 'BoolS++type FPCmp eb sb = forall ctx. Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb) -> Expr ctx 'BoolS++-- | Absolute value (clears the sign bit; exact, no rounding).+fpAbs :: FPUn eb sb+fpAbs = op1 FPAbs++-- | Negation (flips the sign bit; exact, no rounding).+fpNeg :: FPUn eb sb+fpNeg = op1 FPNeg++-- | Arithmetic, rounded with the given mode.+fpAdd, fpSub, fpMul, fpDiv :: FPRounded eb sb+fpAdd = op3 FPAdd+fpSub = op3 FPSub+fpMul = op3 FPMul+fpDiv = op3 FPDiv++-- | @fpFma rm x y z@ is @x * y + z@ with a single rounding.+fpFma+ :: Expr ctx 'RoundingModeS+ -> Expr ctx ('FPS eb sb)+ -> Expr ctx ('FPS eb sb)+ -> Expr ctx ('FPS eb sb)+ -> Expr ctx ('FPS eb sb)+fpFma rm x y z = Expr (C.App FPFma [unExpr rm, unExpr x, unExpr y, unExpr z])++-- | Square root, rounded with the given mode (NaN for negative numbers;+-- the square root of @-0@ is @-0@).+fpSqrt :: Expr ctx 'RoundingModeS -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)+fpSqrt = op2 FPSqrt++-- | The integral value obtained by rounding with the given mode, in the+-- same format.+fpRoundToIntegral :: Expr ctx 'RoundingModeS -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)+fpRoundToIntegral = op2 FPRoundToIntegral++-- | The IEEE remainder (@x - y * n@, with @n@ the nearest integer to+-- @x / y@), and the minimum and maximum. SMT-LIB leaves 'fpMin' and+-- 'fpMax' of two zeros of different signs unspecified: either zero.+fpRem, fpMin, fpMax :: FPBin eb sb+fpRem = op2 FPRem+fpMin = op2 FPMin+fpMax = op2 FPMax++-- | IEEE comparisons: false when an argument is NaN, and the two zeros+-- are equal. Unlike '.==', 'fpEq' is false on NaN and true on @+0, -0@.+fpLeq, fpLt, fpGeq, fpGt, fpEq :: FPCmp eb sb+fpLeq = op2 FPLeq+fpLt = op2 FPLt+fpGeq = op2 FPGeq+fpGt = op2 FPGt+fpEq = op2 FPEq++-- | Whether a number is normal (nonzero, finite and not subnormal).+fpIsNormal :: FPPred eb sb+fpIsNormal = op1 FPIsNormal++-- | Whether a number is subnormal (nonzero with the minimum exponent).+fpIsSubnormal :: FPPred eb sb+fpIsSubnormal = op1 FPIsSubnormal++-- | Whether a number is a zero of either sign.+fpIsZero :: FPPred eb sb+fpIsZero = op1 FPIsZero++-- | Whether a number is an infinity of either sign.+fpIsInfinite :: FPPred eb sb+fpIsInfinite = op1 FPIsInfinite++-- | Whether a value is NaN.+fpIsNaN :: FPPred eb sb+fpIsNaN = op1 FPIsNaN++-- | Whether a value is negative (including @-0@ and @-oo@, but not NaN).+fpIsNegative :: FPPred eb sb+fpIsNegative = op1 FPIsNegative++-- | Whether a value is positive (including @+0@ and @+oo@, but not NaN).+fpIsPositive :: FPPred eb sb+fpIsPositive = op1 FPIsPositive++-- | Conversion to another format.+toFP+ :: forall eb' sb' eb sb ctx+ . (KnownNat eb', KnownNat sb')+ => Expr ctx 'RoundingModeS+ -> Expr ctx ('FPS eb sb)+ -> Expr ctx ('FPS eb' sb')+toFP = let (eb, sb) = fpFormat @eb' @sb' in op2 (ToFP eb sb)++-- | Conversion from a signed or unsigned bit-vector.+sbvToFP, ubvToFP+ :: forall eb sb n ctx+ . (KnownNat eb, KnownNat sb)+ => Expr ctx 'RoundingModeS+ -> Expr ctx ('BVS n)+ -> Expr ctx ('FPS eb sb)+sbvToFP = let (eb, sb) = fpFormat @eb @sb in op2 (ToFP eb sb)+ubvToFP = let (eb, sb) = fpFormat @eb @sb in op2 (ToFPUnsigned eb sb)++-- | Conversion to an unsigned or signed bit-vector of width @w@ (after+-- rounding). Unspecified for NaN, infinities and values out of range.+fpToUBV, fpToSBV+ :: forall w eb sb ctx+ . (KnownNat w, 1 <= w)+ => Expr ctx 'RoundingModeS+ -> Expr ctx ('FPS eb sb)+ -> Expr ctx ('BVS w)+fpToUBV = op2 (FPToUBV (widthOf @w))+fpToSBV = op2 (FPToSBV (widthOf @w))++-------------------------------------------------------------------------------+-- Records++-- | Field labels, usually written with @OverloadedLabels@ as @#name@.+data Label (l :: Symbol) = Label++instance l ~ l' => IsLabel l (Label l') where+ fromLabel = Label++labelText :: forall l. KnownSymbol l => Text+labelText = T.pack (symbolVal (Proxy @l))++infix 6 :=++infixr 5 :&++-- | A field definition: @#name := expr@.+data Field ctx (f :: (Symbol, Sort)) where+ (:=) :: Label l -> Expr ctx s -> Field ctx '(l, s)++-- | A list of field definitions, terminated by 'FNil'.+data Fields ctx (fs :: [(Symbol, Sort)]) where+ FNil :: Fields ctx '[]+ (:&) :: KnownSymbol l => Field ctx '(l, s) -> Fields ctx fs -> Fields ctx ('(l, s) ': fs)++-- | Build a record:+--+-- > record (#name := "Ana" :& #age := 30 :& FNil)+record :: KnownSort ('RecordS fs) => Fields ctx fs -> Expr ctx ('RecordS fs)+record fs = Expr (C.App (RecordMk (names fs)) (exprs fs))+ where+ names :: Fields ctx gs -> [Text]+ names FNil = []+ names (((_ :: Label l) := _) :& rest) = labelText @l : names rest+ exprs :: Fields ctx gs -> [C.Expr]+ exprs FNil = []+ exprs ((_ := Expr e) :& rest) = e : exprs rest++infixl 9 !++-- | Field access: @p ! #age@.+(!) :: forall l fs ctx. KnownSymbol l => Expr ctx ('RecordS fs) -> Label l -> Expr ctx (FieldSort l fs)+r ! _ = op1 (RecordGet (labelText @l)) r++-- | Field access with the label first: @getField #age p = p ! #age@.+getField :: forall l fs ctx. KnownSymbol l => Label l -> Expr ctx ('RecordS fs) -> Expr ctx (FieldSort l fs)+getField l r = r ! l++-- | Functional update of a field.+setField+ :: forall l fs ctx+ . KnownSymbol l+ => Label l+ -> Expr ctx (FieldSort l fs)+ -> Expr ctx ('RecordS fs)+ -> Expr ctx ('RecordS fs)+setField _ v r = op2 (RecordSet (labelText @l)) r v++-------------------------------------------------------------------------------+-- Uninterpreted functions++-- | The curried Haskell type of an uninterpreted function with domain+-- @args@ and range @r@.+type family Fn ctx (args :: [Sort]) (r :: Sort) where+ Fn ctx '[] r = Expr ctx r+ Fn ctx (a ': as) r = Expr ctx a -> Fn ctx as r++-- | Turn an n-ary application builder into a curried function.+class CurryFn (args :: [Sort]) where+ curryFn :: Proxy ctx -> Proxy r -> ([C.Expr] -> C.Expr) -> Fn ctx args r++instance CurryFn '[] where+ curryFn _ _ k = Expr (k [])++instance CurryFn as => CurryFn (a ': as) where+ curryFn pc pr k = \(Expr e) -> curryFn @as pc pr (\es -> k (e : es))
+ src/HSMT/API/Model.hs view
@@ -0,0 +1,46 @@+{-# LANGUAGE AllowAmbiguousTypes #-}++-- | Models returned by satisfiable queries.+module HSMT.API.Model+ ( Model (..)+ , eval+ , evalCore+ , field+ ) where++import Data.Proxy (Proxy (..))+import qualified Data.Text as T+import GHC.TypeLits (KnownSymbol, symbolVal)++import HSMT.API.Expr+import HSMT.API.Sort+import qualified HSMT.Core.Eval as C+import qualified HSMT.Core.Value as C++-- | A model of the assertions, valid for the solver instance @ctx@.+newtype Model ctx = Model {modelInterpretation :: C.Interpretation}+ deriving (Show)++-- | Evaluate any expression of the solver instance under a model.+eval :: forall s ctx. KnownSort s => Model ctx -> Expr ctx s -> Value s+eval m e = case decodeValue @s (evalCore m e) of+ Just v -> v+ Nothing -> error "hsmt: internal error, model value has the wrong sort"++-- | Evaluate to an untyped core value.+evalCore :: Model ctx -> Expr ctx s -> C.Value+evalCore (Model interp) (Expr e) = case C.evalExpr interp e of+ Right v -> v+ Left err -> error ("hsmt: internal error during evaluation: " <> show err)++-- | Read a field of a record value.+field+ :: forall l fs+ . (KnownSymbol l, KnownSort (FieldSort l fs))+ => Label l+ -> RecordValue fs+ -> Value (FieldSort l fs)+field _ (RecordValue fs) =+ case lookup (T.pack (symbolVal (Proxy @l))) fs >>= decodeValue @(FieldSort l fs) of+ Just v -> v+ Nothing -> error "hsmt: internal error, malformed record value"
+ src/HSMT/API/Monad.hs view
@@ -0,0 +1,250 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE RankNTypes #-}++-- | The t'SMT' monad: declaring symbols, asserting formulas and checking+-- satisfiability.+module HSMT.API.Monad+ ( SMT+ , runSMT+ , Config (..)+ , defaultConfig+ , Backend (..)+ , ExternalSolver (..)+ , Dialect (..)+ , z3Backend+ , SMTError (..)+ , Result (..)+ , Core+ , coreAssertions+ , coreAssumptions+ , declare+ , declareFun+ , fresh+ , assert+ , push+ , pop+ , scoped+ , checkSat+ , checkSatAssuming+ , assertions+ ) where++import Control.Exception (Exception, bracket, throwIO)+import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Reader (ReaderT (..), ask)+import Data.IORef+import qualified Data.IntSet as IntSet+import Data.Kind (Type)+import Data.Proxy (Proxy (..))+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as T++import HSMT.API.Expr+import HSMT.API.Model+import HSMT.API.Sort+import qualified HSMT.Core.Expr as C+import HSMT.Core.Op (Op (..), Symbol (..))+import HSMT.Backend+import HSMT.SMT.Engine++-- | Solver configuration.+data Config = Config+ { cfgValidateModels :: Bool+ -- ^ Check every model against the assertions before returning it.+ , cfgTimeout :: Maybe Int+ -- ^ Time limit of each check, in milliseconds; a check that reaches it+ -- answers @Unknown "timeout"@.+ , cfgConflictLimit :: Maybe Int+ -- ^ Limit on the conflicts of the SAT solver in each check; a check+ -- that reaches it answers @Unknown "resource limit reached"@.+ , cfgMinimizeCores :: Bool+ -- ^ Make unsatisfiable cores minimal: removing any formula of the core+ -- makes the others satisfiable. Each formula of the core costs one more+ -- check. Without it, cores are usually small but not minimal.+ , cfgBackend :: Backend+ -- ^ The solver that decides the formulas: the Haskell engine+ -- ('Native') or an external process such as @'External' 'z3Backend'@.+ -- The API is the same for both; with an external solver, results that+ -- SMT-LIB leaves unspecified (division by zero, @fp.min@ of zeros of+ -- different signs, out-of-range @fp.to_ubv@) agree with the solver on+ -- the terms of the checked formulas and take the evaluator's defaults+ -- elsewhere.+ }+ deriving (Show)++-- | The Haskell engine, validated models, no limits, cores without+-- minimization.+defaultConfig :: Config+defaultConfig =+ Config+ { cfgValidateModels = True+ , cfgTimeout = Nothing+ , cfgConflictLimit = Nothing+ , cfgMinimizeCores = False+ , cfgBackend = Native+ }++-- | Misuses of the solver, thrown as exceptions by 'runSMT'.+data SMTError+ = DuplicateDeclaration Text+ -- ^ A name was declared twice.+ | PopWithoutPush+ -- ^ 'pop' without a matching 'push'.+ deriving (Show)++instance Exception SMTError++data SolverState = SolverState+ { stConfig :: Config+ , stDecls :: Map Text Symbol+ , stScopes :: [[C.Expr]]+ -- ^ Assertion scopes, innermost first; each scope is in reverse order.+ , stFresh :: Int+ , stSession :: BackendSession+ -- ^ The solver's incremental state, shared by all checks.+ }++-- | Computations over one solver instance. The phantom parameter @ctx@+-- prevents expressions and models from leaking into other instances.+newtype SMT (ctx :: Type) a = SMT (ReaderT (IORef SolverState) IO a)+ deriving newtype (Functor, Applicative, Monad, MonadIO)++-- | Run a solver instance. An external solver process is stopped when the+-- computation ends.+runSMT :: Config -> (forall ctx. SMT ctx a) -> IO a+runSMT cfg (SMT m) =+ bracket (newBackendSession (cfgBackend cfg)) closeBackendSession $ \sess -> do+ ref <- newIORef (SolverState cfg Map.empty [[]] 0 sess)+ runReaderT m ref++getState :: SMT ctx SolverState+getState = SMT (ask >>= liftIO . readIORef)++modifyState :: (SolverState -> SolverState) -> SMT ctx ()+modifyState f = SMT (ask >>= \r -> liftIO (modifyIORef' r f))++-- | The answer of a check.+data Result ctx+ = Sat (Model ctx)+ -- ^ Satisfiable, with a model of the assertions (and assumptions).+ | Unsat (Core ctx)+ -- ^ Unsatisfiable, with a subset of the assertions and assumptions+ -- that is unsatisfiable on its own.+ | Unknown Text+ -- ^ The solver gave up; the text explains why.+ deriving (Show)++-- | An unsatisfiable core: active assertions and assumptions whose+-- conjunction is unsatisfiable.+data Core ctx = Core [C.Expr] [C.Expr]+ deriving (Show)++-- | The assertions of the core, in assertion order.+coreAssertions :: Core ctx -> [Expr ctx 'BoolS]+coreAssertions (Core as _) = map Expr as++-- | The assumptions of the core (see 'checkSatAssuming'), in the given+-- order.+coreAssumptions :: Core ctx -> [Expr ctx 'BoolS]+coreAssumptions (Core _ as) = map Expr as++declareSymbol :: Text -> Symbol -> SMT ctx ()+declareSymbol name sym = do+ st <- getState+ case Map.lookup name (stDecls st) of+ Just _ -> liftIO (throwIO (DuplicateDeclaration name))+ Nothing -> modifyState (\s -> s {stDecls = Map.insert name sym (stDecls s)})++-- | Declare a constant: @x <- declare \@IntS "x"@.+declare :: forall s ctx. KnownSort s => Text -> SMT ctx (Expr ctx s)+declare name = do+ let sym = Symbol name [] (sortRep @s)+ declareSymbol name sym+ pure (Expr (C.App (Uninterpreted sym) []))++-- | Declare an uninterpreted function:+--+-- > f <- declareFun @'[IntS, IntS] @BoolS "f"+-- > assert (f x y)+declareFun+ :: forall args r ctx+ . (KnownSorts args, KnownSort r, CurryFn args)+ => Text+ -> SMT ctx (Fn ctx args r)+declareFun name = do+ let sym = Symbol name (sortReps @args) (sortRep @r)+ declareSymbol name sym+ pure (curryFn @args (Proxy @ctx) (Proxy @r) (C.App (Uninterpreted sym)))++-- | Declare a constant with a unique name derived from the prefix.+fresh :: forall s ctx. KnownSort s => Text -> SMT ctx (Expr ctx s)+fresh prefix = do+ st <- getState+ let n = stFresh st+ name = prefix <> "!" <> T.pack (show n)+ modifyState (\s -> s {stFresh = n + 1})+ if Map.member name (stDecls st) then fresh prefix else declare @s name++-- | Add an assertion to the innermost scope.+assert :: Expr ctx 'BoolS -> SMT ctx ()+assert (Expr e) = modifyState $ \s -> case stScopes s of+ (sc : rest) -> s {stScopes = (e : sc) : rest}+ [] -> s {stScopes = [[e]]}++-- | Open a new assertion scope.+push :: SMT ctx ()+push = modifyState (\s -> s {stScopes = [] : stScopes s})++-- | Discard the assertions of the innermost scope. Declarations are global+-- and survive 'pop'.+pop :: SMT ctx ()+pop = do+ st <- getState+ case stScopes st of+ (_ : rest@(_ : _)) -> modifyState (\s -> s {stScopes = rest})+ _ -> liftIO (throwIO PopWithoutPush)++-- | Run an action inside a fresh scope.+scoped :: SMT ctx a -> SMT ctx a+scoped m = push *> m <* pop++-- | All active assertions, in assertion order.+assertions :: SMT ctx [C.Expr]+assertions = concatMap reverse . reverse . stScopes <$> getState++-- | Decide the conjunction of the active assertions.+checkSat :: SMT ctx (Result ctx)+checkSat = checkSatAssuming []++-- | Decide the conjunction of the active assertions and of the given+-- formulas, which are assumed for this check only. Checks reuse the work of+-- earlier ones (see t'HSMT.SMT.Engine.Session'); an external solver keeps+-- the assertion scopes as its own assertion levels.+checkSatAssuming :: [Expr ctx 'BoolS] -> SMT ctx (Result ctx)+checkSatAssuming assumed = do+ st <- getState+ let levels = map reverse (reverse (stScopes st))+ as = concat levels+ cfg = stConfig st+ extra = map unExpr assumed+ opts =+ CheckOptions+ { coValidate = cfgValidateModels cfg+ , coTimeout = (\ms -> fromIntegral ms / 1000) <$> cfgTimeout cfg+ , coConflictLimit = cfgConflictLimit cfg+ , coMinimizeCore = cfgMinimizeCores cfg+ , coNeedCore = True+ }+ n = length as+ r <- liftIO (checkBackend (stSession st) opts levels extra)+ pure $ case r of+ ESat interp -> Sat (Model interp)+ EUnsat idx ->+ let picked = IntSet.fromList idx+ keep off es = [e | (i, e) <- zip [off ..] es, IntSet.member i picked]+ in Unsat (Core (keep 0 as) (keep n extra))+ EUnknown why -> Unknown why
+ src/HSMT/API/Sort.hs view
@@ -0,0 +1,261 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE UndecidableInstances #-}++-- | Type-level sorts of the typed API and their Haskell value types.+module HSMT.API.Sort+ ( -- * Sorts+ Sort (..)+ , KnownSort (..)+ , KnownSorts (..)+ , KnownFields (..)+ , sortOfProxy+ -- * Records+ , FieldSort+ , UniqueFields+ , NotMember+ -- * Values+ , Value+ , BitVector (..)+ , ArrayValue (..)+ , RecordValue (..)+ , Uninterp (..)+ -- * Floating point+ , FloatingPoint (..)+ , RoundingMode (..)+ , Float16S+ , Float32S+ , Float64S+ , floatValue+ , floatFromValue+ , toFloat+ , fromFloat+ , toDouble+ , fromDouble+ ) where++import Data.Kind (Constraint, Type)+import qualified Data.Map.Strict as Map+import Data.Proxy (Proxy (..))+import Data.Text (Text)+import qualified Data.Text as T+import GHC.TypeLits+ ( ErrorMessage (..)+ , KnownNat+ , KnownSymbol+ , Nat+ , Symbol+ , TypeError+ , natVal+ , symbolVal+ , type (<=)+ )++import GHC.Float (castDoubleToWord64, castFloatToWord32, castWord32ToFloat, castWord64ToDouble)++import HSMT.Core.Float (RoundingMode (..))+import qualified HSMT.Core.Float as F+import qualified HSMT.Core.Sort as C+import qualified HSMT.Core.Value as C++-- | Sorts, promoted to the kind level with @DataKinds@.+data Sort+ = BoolS+ | IntS+ | StringS+ | BVS Nat+ -- ^ Bit-vectors of the given (positive) width.+ | ArrayS Sort Sort+ -- ^ Arrays from the first sort to the second.+ | RecordS [(Symbol, Sort)]+ -- ^ Records with named fields.+ | UninterpS Symbol+ -- ^ Uninterpreted sort with the given name.+ | FPS Nat Nat+ -- ^ Floating-point numbers with the given exponent and significand+ -- widths (the significand width counts the hidden bit; both at+ -- least 2).+ | RoundingModeS+ | RegLanS+ -- ^ Regular languages over strings. Expressions of this sort must be+ -- ground (built from string literals), so there are no constants or+ -- model values of it.++-- | IEEE half precision (binary16).+type Float16S = 'FPS 5 11++-- | IEEE single precision (binary32), the format of 'Float'.+type Float32S = 'FPS 8 24++-- | IEEE double precision (binary64), the format of 'Double'.+type Float64S = 'FPS 11 53++-- | Sort of a field in a record field list, with a readable error when the+-- field does not exist.+type family FieldSort (l :: Symbol) (fs :: [(Symbol, Sort)]) :: Sort where+ FieldSort l '[] = TypeError ('Text "Record has no field " ':<>: 'ShowType l)+ FieldSort l ('(l, s) ': _) = s+ FieldSort l (_ ': fs) = FieldSort l fs++-- | Rejects records with repeated field names.+type family UniqueFields (fs :: [(Symbol, Sort)]) :: Constraint where+ UniqueFields '[] = ()+ UniqueFields ('(l, _) ': fs) = (NotMember l fs, UniqueFields fs)++-- | Rejects a field name that occurs in the rest of the field list.+type family NotMember (l :: Symbol) (fs :: [(Symbol, Sort)]) :: Constraint where+ NotMember _ '[] = ()+ NotMember l ('(l, _) ': _) = TypeError ('Text "Duplicated record field " ':<>: 'ShowType l)+ NotMember l (_ ': fs) = NotMember l fs++-- | Haskell representation of values of each sort, as returned by models.+type family Value (s :: Sort) :: Type where+ Value 'BoolS = Bool+ Value 'IntS = Integer+ Value 'StringS = Text+ Value ('BVS n) = BitVector n+ Value ('ArrayS i e) = ArrayValue (Value i) (Value e)+ Value ('RecordS fs) = RecordValue fs+ Value ('UninterpS n) = Uninterp n+ Value ('FPS eb sb) = FloatingPoint eb sb+ Value 'RoundingModeS = RoundingMode++-- | An unsigned bit-vector value of width @n@.+newtype BitVector (n :: Nat) = BitVector {bitVectorValue :: Integer}+ deriving (Eq, Ord, Show)++-- | A finite array value: explicit entries plus the value at every other+-- index.+data ArrayValue i e = ArrayValue+ { arrayEntries :: [(i, e)]+ , arrayDefault :: e+ }+ deriving (Eq, Show)++-- | A record value. Fields are read with 'HSMT.API.Model.field'.+newtype RecordValue (fs :: [(Symbol, Sort)]) = RecordValue [(Text, C.Value)]+ deriving (Eq)++instance Show (RecordValue fs) where+ show (RecordValue fs) =+ "{" <> T.unpack (T.intercalate ", " [f <> " = " <> C.prettyValue v | (f, v) <- fs]) <> "}"++-- | An abstract element of an uninterpreted sort.+newtype Uninterp (n :: Symbol) = Uninterp Int+ deriving (Eq, Ord, Show)++-- | A floating-point value: its IEEE bit pattern (sign, biased exponent and+-- trailing significand, from the most significant bit). There is a single+-- NaN, with the pattern 'HSMT.Core.Float.canonicalNaN'.+newtype FloatingPoint (eb :: Nat) (sb :: Nat) = FloatingPoint {floatingPointBits :: Integer}+ deriving (Eq, Ord)++instance (KnownNat eb, KnownNat sb) => Show (FloatingPoint eb sb) where+ show x = show (floatValue x)++formatOf :: forall eb sb. (KnownNat eb, KnownNat sb) => (Int, Int)+formatOf = (fromIntegral (natVal (Proxy @eb)), fromIntegral (natVal (Proxy @sb)))++-- | The value of a pattern: NaN, an infinity, a zero or a finite number+-- (with its sign and exact magnitude).+floatValue :: forall eb sb. (KnownNat eb, KnownNat sb) => FloatingPoint eb sb -> F.FP+floatValue (FloatingPoint x) = let (eb, sb) = formatOf @eb @sb in F.decode eb sb x++-- | The pattern of a value, rounding finite numbers to nearest (ties to+-- even).+floatFromValue :: forall eb sb. (KnownNat eb, KnownNat sb) => F.FP -> FloatingPoint eb sb+floatFromValue v =+ let (eb, sb) = formatOf @eb @sb+ in FloatingPoint . F.encode eb sb $ case v of+ F.Finite neg m -> F.roundRational RNE eb sb neg m+ other -> other++-- | The 'Float' with the same bit pattern (NaN for the NaN).+toFloat :: FloatingPoint 8 24 -> Float+toFloat (FloatingPoint x) = castWord32ToFloat (fromInteger x)++-- | The value of a 'Float'; every NaN becomes the single NaN of SMT-LIB.+fromFloat :: Float -> FloatingPoint 8 24+fromFloat = FloatingPoint . F.canonicalize 8 24 . toInteger . castFloatToWord32++-- | The 'Double' with the same bit pattern (NaN for the NaN).+toDouble :: FloatingPoint 11 53 -> Double+toDouble (FloatingPoint x) = castWord64ToDouble (fromInteger x)++-- | The value of a 'Double'; every NaN becomes the single NaN of SMT-LIB.+fromDouble :: Double -> FloatingPoint 11 53+fromDouble = FloatingPoint . F.canonicalize 11 53 . toInteger . castDoubleToWord64++-- | Sorts with a run-time representation.+class KnownSort (s :: Sort) where+ sortRep :: C.Sort+ decodeValue :: C.Value -> Maybe (Value s)++-- | The run-time representation of the sort of a proxy.+sortOfProxy :: forall s proxy. KnownSort s => proxy s -> C.Sort+sortOfProxy _ = sortRep @s++instance KnownSort 'BoolS where+ sortRep = C.BoolSort+ decodeValue = \case C.VBool b -> Just b; _ -> Nothing++instance KnownSort 'IntS where+ sortRep = C.IntSort+ decodeValue = \case C.VInt n -> Just n; _ -> Nothing++instance KnownSort 'StringS where+ sortRep = C.StringSort+ decodeValue = \case C.VString s -> Just s; _ -> Nothing++instance (KnownNat n, 1 <= n) => KnownSort ('BVS n) where+ sortRep = C.BVSort (fromIntegral (natVal (Proxy @n)))+ decodeValue = \case C.VBV _ x -> Just (BitVector x); _ -> Nothing++instance (KnownSort i, KnownSort e) => KnownSort ('ArrayS i e) where+ sortRep = C.ArraySort (sortRep @i) (sortRep @e)+ decodeValue = \case+ C.VArray _ entries def ->+ ArrayValue+ <$> traverse+ (\(k, v) -> (,) <$> decodeValue @i k <*> decodeValue @e v)+ (Map.toList entries)+ <*> decodeValue @e def+ _ -> Nothing++instance (KnownFields fs, UniqueFields fs) => KnownSort ('RecordS fs) where+ sortRep = C.RecordSort (fieldReps @fs)+ decodeValue = \case+ C.VRecord fs -> Just (RecordValue fs)+ _ -> Nothing++instance KnownSymbol n => KnownSort ('UninterpS n) where+ sortRep = C.UninterpretedSort (T.pack (symbolVal (Proxy @n)))+ decodeValue = \case C.VUninterp _ k -> Just (Uninterp k); _ -> Nothing++instance (KnownNat eb, KnownNat sb, 2 <= eb, 2 <= sb) => KnownSort ('FPS eb sb) where+ sortRep = let (eb, sb) = formatOf @eb @sb in C.FPSort eb sb+ decodeValue = \case C.VFP _ _ x -> Just (FloatingPoint x); _ -> Nothing++instance KnownSort 'RoundingModeS where+ sortRep = C.RoundingModeSort+ decodeValue = \case C.VRM r -> Just r; _ -> Nothing++-- | Record field lists with a run-time representation.+class KnownFields (fs :: [(Symbol, Sort)]) where+ fieldReps :: [(Text, C.Sort)]++instance KnownFields '[] where+ fieldReps = []++instance (KnownSymbol l, KnownSort s, KnownFields fs) => KnownFields ('(l, s) ': fs) where+ fieldReps = (T.pack (symbolVal (Proxy @l)), sortRep @s) : fieldReps @fs++-- | Lists of sorts, used for the domains of uninterpreted functions.+class KnownSorts (ss :: [Sort]) where+ sortReps :: [C.Sort]++instance KnownSorts '[] where+ sortReps = []++instance (KnownSort s, KnownSorts ss) => KnownSorts (s ': ss) where+ sortReps = sortRep @s : sortReps @ss
+ src/HSMT/Backend.hs view
@@ -0,0 +1,52 @@+-- | The solvers behind the API and the SMT-LIB runner: the Haskell engine+-- ('HSMT.SMT.Engine') or an external solver process+-- ('HSMT.Backend.External'), with one check interface.+module HSMT.Backend+ ( Backend (..)+ , ExternalSolver (..)+ , Dialect (..)+ , z3Backend+ , solverFromCommand+ , BackendSession+ , newBackendSession+ , closeBackendSession+ , checkBackend+ ) where++import HSMT.Backend.External+import HSMT.Core.Expr (Expr)+import HSMT.SMT.Engine++-- | Which solver decides the formulas.+data Backend+ = Native+ -- ^ The Haskell engine of hsmt.+ | External ExternalSolver+ -- ^ An external solver process, such as 'z3Backend'.+ deriving (Eq, Show)++-- | An incremental session of either backend.+data BackendSession+ = NativeSession Session+ | ExternalBackendSession ExternalSession++-- | A session with no checks yet; external solvers start on the first+-- check.+newBackendSession :: Backend -> IO BackendSession+newBackendSession = \case+ Native -> NativeSession <$> newSession+ External s -> ExternalBackendSession <$> newExternalSession s++-- | Release the session; an external solver process is stopped.+closeBackendSession :: BackendSession -> IO ()+closeBackendSession = \case+ NativeSession _ -> pure ()+ ExternalBackendSession s -> closeExternalSession s++-- | Decide the conjunction of assertion levels (outermost first, each in+-- assertion order) and assumptions. An 'EUnsat' answer carries positions+-- in the concatenated levels followed by the assumptions.+checkBackend :: BackendSession -> CheckOptions -> [[Expr]] -> [Expr] -> IO EngineResult+checkBackend sess opts levels assumed = case sess of+ NativeSession s -> checkSession s opts (concat levels <> assumed)+ ExternalBackendSession s -> checkExternal s opts levels assumed
+ src/HSMT/Backend/External.hs view
@@ -0,0 +1,770 @@+{-# LANGUAGE MultiWayIf #-}++-- | An external SMT solver (Z3 by default) driven through textual SMT-LIB+-- over a pipe, behind the same check interface as the Haskell engine+-- ('HSMT.SMT.Engine.checkSession').+--+-- One solver process serves all checks of a session. Formulas that only+-- grow are sent once; a check that drops formulas resets the solver,+-- unless 'solverIncremental' asks for one @push@ level per assertion+-- scope. Declarations of sorts and symbols are emitted on demand, at the+-- level of the first formula that needs them.+-- Unsatisfiable cores come from a separate tracked check (see+-- 'checkExternal'), whose indicator constants are named @hsmt!s!k@; the+-- prefix @hsmt!@ is reserved.+--+-- Models are read from @get-model@ (constants, @ite@ tables of functions,+-- @store@ chains, @as-array@ and @lambda@ arrays, elements of+-- uninterpreted sorts) and completed with @get-value@ at the applications+-- of uninterpreted functions, divisions by zero and unspecified+-- floating-point operations occurring in the formulas, so the model+-- agrees with the solver on every term the formulas mention. Elsewhere,+-- unspecified results take the evaluator's defaults.+--+-- The responses are read with the SMT-LIB parser of hsmt. The library+-- @simple-smt@ was considered, but its reader splits string literals at+-- spaces and parentheses, which corrupts string models and desynchronizes+-- the responses.+module HSMT.Backend.External+ ( -- * Solvers+ ExternalSolver (..)+ , Dialect (..)+ , z3Backend+ , solverFromCommand+ -- * Sessions+ , ExternalSession+ , newExternalSession+ , closeExternalSession+ , checkExternal+ ) where++import Control.Concurrent (forkIO)+import Control.Exception (Exception, IOException, SomeException, catch, throwIO, try)+import Control.Monad (foldM, forM, forM_, unless, void, when)+import Data.Char (isDigit)+import Data.Containers.ListUtils (nubOrd)+import Data.IORef+import Data.List (isPrefixOf)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe, mapMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.IO as T+import System.Environment (lookupEnv)+import System.FilePath (takeFileName)+import System.IO+import System.Process+import System.Timeout (timeout)+import GHC.Clock (getMonotonicTime)++import HSMT.Core.Eval+import HSMT.Core.Expr+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Value+import HSMT.SMT.Engine (CheckOptions (..), EngineResult (..))+import HSMT.SMTLib.Parser+import HSMT.SMTLib.Printer+import HSMT.SMTLib.Syntax++-------------------------------------------------------------------------------+-- Solvers++-- | How to run an external solver.+data ExternalSolver = ExternalSolver+ { solverPath :: FilePath+ -- ^ The executable. For @"z3"@, the environment variable @HSMT_Z3@+ -- takes precedence when set.+ , solverArgs :: [String]+ -- ^ Arguments that make the solver read SMT-LIB from the standard+ -- input interactively (@-in -smt2@ for Z3, @--incremental@ for CVC5).+ , solverDialect :: Dialect+ -- ^ Which options the solver understands.+ , solverLogic :: Text+ -- ^ The argument of @set-logic@.+ , solverIncremental :: Bool+ -- ^ Keep the assertion scopes as @push@ levels of the solver, so each+ -- check only sends what changed. Otherwise a check that drops formulas+ -- starts over with @(reset)@ and asserts the current ones again. Any+ -- @push@ puts Z3 in its incremental mode, which skips most+ -- preprocessing: a chain of 30 equality diamonds takes 10 ms without+ -- it and more than a minute with it. Hence the default is 'False'.+ }+ deriving (Eq, Show)++-- | The options an external solver understands beyond standard SMT-LIB.+data Dialect+ = Z3Dialect+ -- ^ Z3: @:timeout@ limits each check, @:sat.max_conflicts@ and+ -- @:smt.max_conflicts@ limit conflicts, and @:smt.core.minimize@+ -- minimizes cores.+ | StandardDialect+ -- ^ Only standard options: time limits are enforced by killing the+ -- process, conflict limits are ignored, and cores are minimized by+ -- removal, with one check per formula of the core.+ deriving (Eq, Show)++-- | Z3, found through @HSMT_Z3@ or the @PATH@, with logic @ALL@.+z3Backend :: ExternalSolver+z3Backend = ExternalSolver "z3" ["-in", "-smt2"] Z3Dialect "ALL" False++-- | A solver from a command line (executable and arguments). The dialect+-- is 'Z3Dialect' when the executable is named @z3@, and the command @z3@+-- alone gets Z3's interactive arguments.+solverFromCommand :: [String] -> Maybe ExternalSolver+solverFromCommand = \case+ [] -> Nothing+ [path] | isZ3 path -> Just z3Backend {solverPath = path}+ path : args ->+ Just (ExternalSolver path args (if isZ3 path then Z3Dialect else StandardDialect) "ALL" False)+ where+ isZ3 p = "z3" `isPrefixOf` takeFileName p++-------------------------------------------------------------------------------+-- Sessions++-- | A connection to an external solver, started on the first check and+-- restarted after a failure.+data ExternalSession = ExternalSession ExternalSolver (IORef (Maybe Proc))++-- | A session that has not started the solver yet.+newExternalSession :: ExternalSolver -> IO ExternalSession+newExternalSession s = ExternalSession s <$> newIORef Nothing++-- | Stop the solver process, if any.+closeExternalSession :: ExternalSession -> IO ()+closeExternalSession (ExternalSession _ ref) = do+ readIORef ref >>= mapM_ (\p -> void (try @SomeException (send p "(exit)")) >> kill p)+ writeIORef ref Nothing++data Proc = Proc+ { prIn :: Handle+ , prOut :: Handle+ , prHandle :: ProcessHandle+ , prStderr :: IORef [Text]+ -- ^ The last lines the solver wrote to its standard error, newest first.+ , prIncremental :: Bool+ -- ^ See 'solverIncremental'.+ , prLevels :: IORef [Level]+ -- ^ The assertion levels pushed in the solver, innermost first. Without+ -- 'solverIncremental', a single level that is not pushed.+ , prKnown :: IORef Bool+ -- ^ Whether the solver holds exactly the formulas of 'prLevels' (and+ -- not, for instance, those of a core computation).+ , prCounter :: IORef Int+ , prOptions :: IORef (Maybe Int, Maybe Int)+ -- ^ Timeout (ms) and conflict limit in effect.+ }++-- | One @push@ of the solver.+data Level = Level+ { lvFormulas :: [Expr]+ -- ^ Assertions, newest first.+ , lvDecls :: Set.Set Text+ -- ^ Declarations made at this level, as rendered.+ }++emptyLevel :: Level+emptyLevel = Level [] Set.empty++-- | A failure of the solver process: an error response, an unexpected+-- answer, or the process ending.+newtype Failure = Failure Text+ deriving (Show)++instance Exception Failure++-- | The answer of the main check of 'checkExternal'.+data Outcome+ = OSat Interpretation+ | OUnsat+ | OUnknown Text++-- | Decide the conjunction of the formulas, given as assertion levels+-- (outermost first, each in assertion order) and assumptions. An 'EUnsat'+-- answer carries positions in the levels followed by the assumptions, as+-- for 'HSMT.SMT.Engine.checkSession'.+--+-- The check itself tracks nothing: assertions are plain, and assumptions+-- are asserted in a level of their own. Tracking (named assertions or+-- @check-sat-assuming@) turns off much of Z3's preprocessing, which makes+-- some easy problems hard (a chain of 30 equality diamonds takes 10 ms+-- untracked and more than a minute tracked). A core is computed only after+-- an @unsat@ answer, by a tracked check limited to five times the duration+-- of the first one (at least one second, at most the timeout); when it+-- fails, the core is every formula.+checkExternal :: ExternalSession -> CheckOptions -> [[Expr]] -> [Expr] -> IO EngineResult+checkExternal sess@(ExternalSession solver _) opts levels0 assumed = do+ let levels = if null levels0 then [[]] else levels0+ formulas = concat levels <> assumed+ everything = [0 .. length formulas - 1]+ t0 <- getMonotonicTime+ main <- guarded sess (hardLimit (coTimeout opts)) (\p -> mainCheck solver p opts levels assumed)+ case main of+ Left why -> pure (EUnknown why)+ Right (OUnknown why) -> pure (EUnknown why)+ Right (OSat interp) ->+ pure $ case [e | e <- formulas, evalExpr interp e /= Right (VBool True)] of+ e : _+ | coValidate opts ->+ EUnknown ("the model of the external solver does not satisfy " <> renderExpr e)+ _ -> ESat interp+ Right OUnsat -> do+ elapsed <- subtract t0 <$> getMonotonicTime+ let budget = maybe id min (coTimeout opts) (max 1 (5 * elapsed))+ tracked <-+ if coNeedCore opts+ then guarded sess (Just (budget + 1)) (\p -> trackedCore solver p budget formulas)+ else pure (Left "no core wanted")+ let core = either (const everything) id tracked+ EUnsat <$> if coMinimizeCore opts then minimizeCore sess opts formulas core else pure core++-- | The hard limit for a check with the given timeout: the solver's own+-- timeout plus a margin.+hardLimit :: Maybe Double -> Maybe Double+hardLimit = fmap (\s -> s + max 0.5 (s / 2) + 1)++-- | Run an action on the solver process (started if needed) within a time+-- limit in seconds. A failure or the limit restarts the process on the+-- next use and is returned as 'Left'.+guarded :: ExternalSession -> Maybe Double -> (Proc -> IO a) -> IO (Either Text a)+guarded sess@(ExternalSession _ ref) limit act = do+ let run = ensureStarted sess >>= act+ r <- try (try (maybe (Just <$> run) (\s -> timeout (ceiling (s * 1e6)) run) limit))+ case r of+ Right (Right (Just x)) -> pure (Right x)+ Right (Right Nothing) -> restart >> pure (Left "timeout")+ Right (Left (Failure why)) -> restart >> pure (Left why)+ Left (e :: IOException) -> do+ err <- readIORef ref >>= maybe (pure []) (readIORef . prStderr)+ restart+ pure (Left ("external solver failed: " <> T.pack (show e) <> stderrNote err))+ where+ restart = do+ readIORef ref >>= mapM_ kill+ writeIORef ref Nothing+ stderrNote = \case+ [] -> ""+ ls -> " (" <> T.intercalate "; " (reverse ls) <> ")"++ensureStarted :: ExternalSession -> IO Proc+ensureStarted (ExternalSession solver ref) =+ readIORef ref >>= \case+ Just p -> pure p+ Nothing -> do+ p <- start solver+ writeIORef ref (Just p)+ pure p++start :: ExternalSolver -> IO Proc+start solver = do+ path <-+ if solverPath solver == "z3"+ then fromMaybe "z3" . mfilter' (not . null) <$> lookupEnv "HSMT_Z3"+ else pure (solverPath solver)+ (Just hin, Just hout, Just herr, ph) <-+ createProcess+ (proc path (solverArgs solver))+ { std_in = CreatePipe+ , std_out = CreatePipe+ , std_err = CreatePipe+ }+ forM_ [hin, hout, herr] (`hSetEncoding` utf8)+ errRef <- newIORef []+ let drain = do+ l <- T.hGetLine herr+ modifyIORef' errRef (take 20 . (l :))+ drain+ _ <- forkIO (drain `catch` \(_ :: IOException) -> pure ())+ p <-+ Proc hin hout ph errRef (solverIncremental solver)+ <$> newIORef []+ <*> newIORef True+ <*> newIORef 0+ <*> newIORef (Nothing, Nothing)+ initialize solver p+ pure p+ where+ mfilter' f = \case+ Just x | f x -> Just x+ _ -> Nothing++-- | Set the options and the logic of a solver that has just started or+-- been reset.+initialize :: ExternalSolver -> Proc -> IO ()+initialize solver p = do+ ack p "(set-option :print-success true)"+ ack p "(set-option :produce-models true)"+ ack p "(set-option :produce-unsat-cores true)"+ ack p ("(set-logic " <> solverLogic solver <> ")")+ writeIORef (prOptions p) (Nothing, Nothing)+ writeIORef (prLevels p) (if prIncremental p then [] else [emptyLevel])+ writeIORef (prKnown p) True++-- | Drop every assertion and declaration: pop all levels, or reset the+-- solver.+clear :: ExternalSolver -> Proc -> IO ()+clear solver p+ | prIncremental p = popAll p >> writeIORef (prKnown p) True+ | otherwise = ack p "(reset)" >> initialize solver p++-- | Run an action in a temporary context holding only what the action+-- asserts. Incremental solvers keep their levels below it; the others are+-- reset before the next check.+isolated :: ExternalSolver -> Proc -> IO a -> IO a+isolated solver p act+ | prIncremental p = do+ popAll p+ pushLevel p+ r <- act+ popLevels p 1+ pure r+ | otherwise = do+ clear solver p+ writeIORef (prKnown p) False+ act++kill :: Proc -> IO ()+kill p = do+ terminateProcess (prHandle p) `catch` \(_ :: SomeException) -> pure ()+ forM_ [prIn p, prOut p] $ \h -> hClose h `catch` \(_ :: SomeException) -> pure ()+ void (forkIO (void (waitForProcess (prHandle p)) `catch` \(_ :: SomeException) -> pure ()))++-------------------------------------------------------------------------------+-- Communication++send :: Proc -> Text -> IO ()+send p t = T.hPutStrLn (prIn p) t >> hFlush (prIn p)++-- | Read one response: lines until a complete S-expression.+recv :: Proc -> IO SExpr+recv p = go [] (0, Normal)+ where+ go acc st = do+ l <- T.hGetLine (prOut p)+ let acc' = l : acc+ st'@(depth, mode) = scanLine st l+ if depth <= 0 && mode == Normal+ then case parseSExprs (T.unlines (reverse acc')) of+ Right (e : _) -> pure e+ Right [] -> go [] (0, Normal)+ Left err -> throwIO (Failure ("unreadable solver output: " <> err))+ else go acc' st'++data Mode = Normal | InString | InQuoted+ deriving (Eq)++-- | Parenthesis depth after a line, outside strings, quoted symbols and+-- comments.+scanLine :: (Int, Mode) -> Text -> (Int, Mode)+scanLine st0 = go st0 . T.unpack+ where+ go st [] = st+ go (d, Normal) (c : cs) = case c of+ '(' -> go (d + 1, Normal) cs+ ')' -> go (d - 1, Normal) cs+ '"' -> go (d, InString) cs+ '|' -> go (d, InQuoted) cs+ ';' -> (d, Normal)+ _ -> go (d, Normal) cs+ go (d, InString) (c : cs)+ | c == '"' = case cs of+ '"' : cs' -> go (d, InString) cs'+ _ -> go (d, Normal) cs+ | otherwise = go (d, InString) cs+ go (d, InQuoted) (c : cs)+ | c == '|' = go (d, Normal) cs+ | otherwise = go (d, InQuoted) cs++-- | Send a command and read its response; error responses are failures.+ask :: Proc -> Text -> IO SExpr+ask p cmd = do+ send p cmd+ recv p >>= \case+ SList [SSym "error", SStr msg] -> throwIO (Failure ("external solver error: " <> msg))+ r -> pure r++-- | Send a command that answers @success@.+ack :: Proc -> Text -> IO ()+ack p cmd =+ ask p cmd >>= \case+ SSym "success" -> pure ()+ r -> throwIO (Failure ("unexpected answer to " <> cmd <> ": " <> showS r))++-------------------------------------------------------------------------------+-- Levels++freshName :: Proc -> Text -> IO Text+freshName p prefix = do+ n <- readIORef (prCounter p)+ writeIORef (prCounter p) (n + 1)+ pure ("hsmt!" <> prefix <> "!" <> T.pack (show n))++pushLevel :: Proc -> IO ()+pushLevel p = do+ ack p "(push 1)"+ modifyIORef' (prLevels p) (emptyLevel :)++popLevels :: Proc -> Int -> IO ()+popLevels p n = when (n > 0) $ do+ ack p ("(pop " <> T.pack (show n) <> ")")+ modifyIORef' (prLevels p) (drop n)++popAll :: Proc -> IO ()+popAll p = readIORef (prLevels p) >>= popLevels p . length++modifyTop :: Proc -> (Level -> Level) -> IO ()+modifyTop p f =+ modifyIORef' (prLevels p) $ \case+ l : rest -> f l : rest+ [] -> [f emptyLevel]++-- | Emit the declarations the expressions need that are not in scope.+declareFor :: Proc -> [Expr] -> IO ()+declareFor p es = do+ scope <- foldMap lvDecls <$> readIORef (prLevels p)+ let new = filter (`Set.notMember` scope) (nubOrd (map renderCommand (declarationsFor es)))+ forM_ new (ack p)+ modifyTop p (\l -> l {lvDecls = Set.union (Set.fromList new) (lvDecls l)})++assertPlain :: Proc -> Expr -> IO ()+assertPlain p e = do+ declareFor p [e]+ ack p (renderCommand (Assert e))+ modifyTop p (\l -> l {lvFormulas = e : lvFormulas l})++-- | Make the solver hold exactly the given levels, then the assumptions.+-- Incremental solvers pop only the levels that differ and get the+-- assumptions in a level of their own (see 'retract'); the others start+-- over unless the formulas only grow.+prepare :: ExternalSolver -> Proc -> [[Expr]] -> [Expr] -> IO ()+prepare solver p levels assumed+ | prIncremental p = do+ syncLevels p levels+ unless (null assumed) $ pushLevel p >> mapM_ (assertPlain p) assumed+ | otherwise = do+ known <- readIORef (prKnown p)+ held <- reverse . concatMap lvFormulas <$> readIORef (prLevels p)+ let target = concat levels <> assumed+ if known && held `isPrefixOf` target+ then mapM_ (assertPlain p) (drop (length held) target)+ else clear solver p >> mapM_ (assertPlain p) target++-- | Undo the level of assumptions made by @prepare@.+retract :: Proc -> [Expr] -> IO ()+retract p assumed = when (prIncremental p && not (null assumed)) (popLevels p 1)++-- | Make the solver's levels hold exactly the given formulas, popping only+-- the levels that differ.+syncLevels :: Proc -> [[Expr]] -> IO ()+syncLevels p target = do+ current <- reverse <$> readIORef (prLevels p)+ let held = map (reverse . lvFormulas) current+ same = length (takeWhile id (zipWith (==) held target))+ case (drop same held, drop same target) of+ (h : restH, t : restT) | h `isPrefixOf` t -> do+ popLevels p (length restH)+ mapM_ (assertPlain p) (drop (length h) t)+ fresh restT+ (hs, ts) -> do+ popLevels p (length hs)+ fresh ts+ where+ fresh = mapM_ (\fs -> pushLevel p >> mapM_ (assertPlain p) fs)++-------------------------------------------------------------------------------+-- Checks++-- | Set the time (seconds) and conflict limits of the next checks, for+-- solvers that understand them.+setLimits :: ExternalSolver -> Proc -> Maybe Double -> Maybe Int -> IO ()+setLimits solver p secs c = when (solverDialect solver == Z3Dialect) $ do+ (t0, c0) <- readIORef (prOptions p)+ let t = (\s -> max 1 (ceiling (s * 1000))) <$> secs+ when (t /= t0) $ ack p ("(set-option :timeout " <> T.pack (show (fromMaybe 0 t)) <> ")")+ when (c /= c0) $+ forM_ ["sat", "smt"] $ \k ->+ ack p ("(set-option :" <> k <> ".max_conflicts " <> T.pack (show (fromMaybe 4294967295 c)) <> ")")+ writeIORef (prOptions p) (t, c)++-- | The check proper, with the assumptions in a level of their own.+mainCheck :: ExternalSolver -> Proc -> CheckOptions -> [[Expr]] -> [Expr] -> IO Outcome+mainCheck solver p opts levels assumed = do+ setLimits solver p (coTimeout opts) (coConflictLimit opts)+ prepare solver p levels assumed+ r <-+ checkCommand p [] >>= \case+ "sat" -> OSat <$> readModel p (concat levels <> assumed)+ "unsat" -> pure OUnsat+ _ -> OUnknown <$> reasonUnknown p+ retract p assumed+ pure r++-- | Positions of an unsatisfiable subset of the formulas, from a check+-- that tracks each formula with an indicator constant, in an 'isolated'+-- context.+trackedCore :: ExternalSolver -> Proc -> Double -> [Expr] -> IO [Int]+trackedCore solver p budget formulas = isolated solver p $ do+ setLimits solver p (Just budget) Nothing+ inds <- forM formulas $ \e -> do+ declareFor p [e]+ name <- freshName p "s"+ let sym = Symbol name [] BoolSort+ ack p (renderCommand (DeclareFun sym))+ ack p (renderCommand (Assert (App Implies [App (Uninterpreted sym) [], e])))+ pure name+ answer <- checkCommand p inds+ unless (answer == "unsat") $ throwIO (Failure "no core")+ core <-+ ask p "(get-unsat-core)" >>= \case+ SList xs -> pure [s | SSym s <- xs]+ r -> throwIO (Failure ("unexpected unsatisfiable core: " <> showS r))+ let position = Map.fromList (zip inds [0 ..])+ pure (Set.toList (Set.fromList (mapMaybe (`Map.lookup` position) core)))++-- | Run @check-sat@ or @check-sat-assuming@ and return the answer.+checkCommand :: Proc -> [Text] -> IO Text+checkCommand p inds =+ ask p (if null inds then "(check-sat)" else "(check-sat-assuming (" <> T.unwords inds <> "))") >>= \case+ SSym a | a `elem` ["sat", "unsat", "unknown"] -> pure a+ SSym "timeout" -> pure "unknown"+ r -> throwIO (Failure ("unexpected answer to check-sat: " <> showS r))++reasonUnknown :: Proc -> IO Text+reasonUnknown p = do+ r <- ask p "(get-info :reason-unknown)"+ let why = case r of+ SList [SKey _, SStr s] -> s+ SList [SKey _, SSym s] -> s+ _ -> showS r+ lower = T.toLower why+ pure $+ if+ | any (`T.isInfixOf` lower) ["timeout", "canceled"] -> "timeout"+ | any (`T.isInfixOf` lower) ["conflict", "resource", "rlimit"] -> "resource limit reached"+ | T.null why -> "unknown"+ | otherwise -> why++-- | Shrink a core by removal: drop every formula whose removal keeps the+-- rest unsatisfiable, with untracked checks. A check that does not answer+-- @unsat@ (including a timeout) keeps the formula.+minimizeCore :: ExternalSession -> CheckOptions -> [Expr] -> [Int] -> IO [Int]+minimizeCore sess@(ExternalSession solver _) opts formulas core0 = foldM step core0 core0+ where+ fs = Map.fromList (zip [0 :: Int ..] formulas)+ step core i = do+ let rest = filter (/= i) core+ r <- guarded sess (hardLimit (coTimeout opts)) $ \p -> isolated solver p $ do+ setLimits solver p (coTimeout opts) (coConflictLimit opts)+ mapM_ (assertPlain p) [fs Map.! j | j <- rest]+ checkCommand p []+ pure (if r == Right "unsat" then rest else core)++-------------------------------------------------------------------------------+-- Models++-- | A function or constant definition of @get-model@: parameters, result+-- sort and body.+data Definition = Definition [(Text, SExpr)] SExpr SExpr++-- | Read the model of the last satisfiable check for the symbols of the+-- formulas.+readModel :: Proc -> [Expr] -> IO Interpretation+readModel p formulas = do+ ps0 <- either (throwIO . Failure) pure (declarationsState formulas)+ items <-+ ask p "(get-model)" >>= \case+ SList (SSym "model" : xs) -> pure xs+ SList xs -> pure xs+ r -> throwIO (Failure ("unexpected model: " <> showS r))+ let defs =+ Map.fromList+ [ (n, Definition [(x, s) | SList [SSym x, s] <- ps] res body)+ | SList [SSym "define-fun", SSym n, SList ps, res, body] <- items+ ]+ elems <-+ either (throwIO . Failure) pure $+ elements ps0 [(n, s) | SList [SSym "declare-fun", SSym n, SList [], s] <- items]+ let ctx = ModelCtx (declareConstants (map fst elems) ps0) (elemInterp elems) defs+ syms = Set.toList (foldMap symbols formulas)+ base <- forM syms $ \sym -> do+ fi <- case Map.lookup (symName sym) defs of+ Nothing -> pure (Right (constInterp (defaultValue (symResult sym))))+ Just (Definition params _ body) -> pure $ do+ sorts <- traverse (parseSort ps0 . snd) params+ tableOf ctx (zip (map fst params) sorts) body+ case fi of+ Right f -> pure (sym, f)+ Left err+ | null (symArgs sym) -> do+ -- Fall back on the value the solver gives for the constant.+ v <- valuesOf p ctx [App (Uninterpreted sym) []]+ case Map.elems v of+ [x] -> pure (sym, constInterp x)+ _ -> throwIO (Failure ("cannot read the model of " <> symName sym <> ": " <> err))+ | otherwise -> pure (sym, constInterp (defaultValue (symResult sym)))+ let pts = nubOrd (concatMap points formulas)+ terms = nubOrd (concat [args <> [t] | t@(App _ args) <- pts])+ vals <- if null terms then pure Map.empty else valuesOf p ctx terms+ let value e = Map.lookup e vals+ interp0 = emptyInterpretation {interpSymbols = Map.fromList base}+ pure (foldl (addPoint value) interp0 pts)+ where+ addPoint value interp t@(App op args) = fromMaybe interp $ do+ v <- value t+ vs <- traverse value args+ pure $ case op of+ Uninterpreted sym ->+ let fi = Map.findWithDefault (constInterp (defaultValue (symResult sym))) sym (interpSymbols interp)+ in interp {interpSymbols = Map.insert sym fi {fiTable = Map.insert vs v (fiTable fi)} (interpSymbols interp)}+ IntDiv | [a, VInt 0] <- vs -> interp {interpDivByZero = extend (interpDivByZero interp) [a] v}+ IntMod | [a, VInt 0] <- vs -> interp {interpModByZero = extend (interpModByZero interp) [a] v}+ IntDiv -> interp+ IntMod -> interp+ _ -> interp {interpUnspecified = Map.insert (op, vs) v (interpUnspecified interp)}+ extend fi k v = fi {fiTable = Map.insert k v (fiTable fi)}++-- | Applications whose value the model must take from the solver:+-- uninterpreted functions, division and remainder by a non-literal, and+-- floating-point operations with unspecified results.+points :: Expr -> [Expr]+points t@(App op args) = concatMap points args <> [t | wanted]+ where+ wanted = case (op, args) of+ (Uninterpreted _, _ : _) -> True+ (IntDiv, [_, App (IntConst n) []]) -> n == 0+ (IntMod, [_, App (IntConst n) []]) -> n == 0+ (IntDiv, _) -> True+ (IntMod, _) -> True+ (FPMin, _) -> True+ (FPMax, _) -> True+ (FPToUBV _, _) -> True+ (FPToSBV _, _) -> True+ _ -> False++-- | The parse state with the declarations of the formulas.+declarationsState :: [Expr] -> Either Text ParseState+declarationsState formulas = do+ ses <- parseSExprs (renderScript (declarationsFor formulas))+ foldM (\ps se -> fst <$> parseCommand ps se) initialParseState ses++-- | Elements of uninterpreted sorts, named as the solver names them+-- (@U!val!3@ is the element 3 of @U@).+elements :: ParseState -> [(Text, SExpr)] -> Either Text [(Symbol, Value)]+elements ps decls = do+ sorted <- forM decls $ \(n, s) -> (,) n <$> parseSort ps s+ let numbered = zipWith (\k (n, s) -> (Symbol n [] s, VUninterp s (fromMaybe k (number n)))) [1000000 ..] sorted+ pure numbered+ where+ number n =+ let digits = T.takeWhileEnd isDigit n+ in if not (T.null digits) && "!val!" `T.isSuffixOf` T.dropEnd (T.length digits) n+ then Just (read (T.unpack digits))+ else Nothing++elemInterp :: [(Symbol, Value)] -> Map Symbol FunInterp+elemInterp es = Map.fromList [(s, constInterp v) | (s, v) <- es]++data ModelCtx = ModelCtx+ { mcState :: ParseState+ -- ^ Declarations of the formulas and the elements of uninterpreted+ -- sorts.+ , mcElems :: Map Symbol FunInterp+ , mcDefs :: Map Text Definition+ }++-- | Ask the solver for the values of terms.+valuesOf :: Proc -> ModelCtx -> [Expr] -> IO (Map Expr Value)+valuesOf p ctx terms = do+ r <- ask p (renderCommand (GetValue terms))+ pairs <- case r of+ SList xs | length xs == length terms -> pure [v | SList [_, v] <- xs]+ _ -> throwIO (Failure ("unexpected answer to get-value: " <> showS r))+ vs <- either (throwIO . Failure) pure (traverse (valueOf ctx) pairs)+ pure (Map.fromList (zip terms vs))++-- | The value denoted by a ground term of a model.+valueOf :: ModelCtx -> SExpr -> Either Text Value+valueOf ctx se = do+ (se', extra) <- replaceSpecial ctx se+ let ps = declareConstants (map fst extra) (mcState ctx)+ interp =+ emptyInterpretation+ { interpSymbols = Map.union (Map.fromList [(s, constInterp v) | (s, v) <- extra]) (mcElems ctx)+ }+ (e, _) <- parseTerm ps se'+ either (\err -> Left ("cannot evaluate a model value: " <> eeMessage err)) Right (evalExpr interp e)++-- | Replace the array values given as functions (@as-array@ and @lambda@)+-- by fresh constants with their values.+replaceSpecial :: ModelCtx -> SExpr -> Either Text (SExpr, [(Symbol, Value)])+replaceSpecial ctx se = case se of+ SList [SSym "_", SSym "as-array", SSym g] -> case Map.lookup g (mcDefs ctx) of+ Just (Definition [(x, s)] res body) -> array [(x, s)] res body+ _ -> Left ("unsupported array value: " <> showS se)+ SList [SSym "lambda", SList [SList [SSym x, s]], body] -> do+ idx <- parseSort (mcState ctx) s+ fi <- tableOf ctx [(x, idx)] body+ constantFor (arrayOf idx fi)+ SList xs -> do+ rs <- traverse (replaceSpecial ctx) xs+ pure (SList (map fst rs), concatMap snd rs)+ -- Z3 names the elements of uninterpreted sorts S!val!k, and does not+ -- always declare them in the model.+ SSym n+ | (prefix, digits) <- T.breakOnEnd "!val!" n+ , Just sortName <- T.stripSuffix "!val!" prefix+ , not (T.null digits) && T.all isDigit digits+ , Right s@(UninterpretedSort _) <- parseSort (mcState ctx) (SSym sortName) ->+ constantFor (VUninterp s (read (T.unpack digits)))+ _ -> pure (se, [])+ where+ array params res body = do+ sorts <- traverse (parseSort (mcState ctx) . snd) params+ _ <- parseSort (mcState ctx) res+ fi <- tableOf ctx (zip (map fst params) sorts) body+ case sorts of+ [idx] -> constantFor (arrayOf idx fi)+ _ -> Left "array function of several arguments"+ arrayOf idx fi = mkArray idx (Map.fromList [(k, v) | ([k], v) <- Map.toList (fiTable fi)]) (fiDefault fi)+ -- Equal subterms denote equal values, so the name can be the term.+ constantFor v = do+ let sym = Symbol ("hsmt!v!" <> showS se) [] (valueSort v)+ pure (SSym (symName sym), [(sym, v)])++-- | The interpretation of a function from its body: an @ite@ chain whose+-- conditions fix every parameter, ending in a value.+tableOf :: ModelCtx -> [(Text, Sort)] -> SExpr -> Either Text FunInterp+tableOf ctx params = go+ where+ names = map fst params+ mentions = \case+ SSym s -> s `elem` names+ SList xs -> any mentions xs+ _ -> False+ go = \case+ SList [SSym "ite", c, v, rest] | mentions c && not (mentions v) -> do+ keys <- condition c+ val <- valueOf ctx v+ FunInterp tbl def <- go rest+ pure (FunInterp (foldr (`Map.insert` val) tbl keys) def)+ body+ | not (mentions body) -> constInterp <$> valueOf ctx body+ | otherwise -> Left ("unsupported function interpretation: " <> showS body)+ condition = \case+ SList (SSym "or" : cs) -> concat <$> traverse condition cs+ SList (SSym "and" : cs) -> traverse literal cs >>= assemble+ c -> literal c >>= assemble . pure+ literal = \case+ SList [SSym "=", SSym x, v] | x `elem` names, not (mentions v) -> (,) x <$> valueOf ctx v+ SList [SSym "=", v, SSym x] | x `elem` names, not (mentions v) -> (,) x <$> valueOf ctx v+ SSym x | x `elem` names -> Right (x, VBool True)+ SList [SSym "not", SSym x] | x `elem` names -> Right (x, VBool False)+ c -> Left ("unsupported condition in a function interpretation: " <> showS c)+ assemble lits+ | length lits == length names+ , Just key <- traverse (`lookup` lits) names =+ Right [key]+ | otherwise = Left "a condition does not fix every parameter"
+ src/HSMT/Core/Eval.hs view
@@ -0,0 +1,376 @@+-- | Reference evaluator for the core language.+--+-- This module defines the semantics of every operator, following the+-- SMT-LIB 2.6 standard. It is used to evaluate expressions under a model+-- and serves as the oracle that decision procedures are tested against.+module HSMT.Core.Eval+ ( Interpretation (..)+ , FunInterp (..)+ , emptyInterpretation+ , constInterp+ , evalExpr+ , applyOp+ , EvalError (..)+ ) where++import Data.Bits (complement, shiftL, shiftR, testBit, xor, (.&.), (.|.))+import Data.Char (isDigit)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as T++import HSMT.Core.Expr+import qualified HSMT.Core.Float as F+import qualified HSMT.Core.Regex as R+import HSMT.Core.Op+import HSMT.Core.Value++-- | Finite interpretation of a function: an explicit table plus a default+-- result for every other argument tuple.+data FunInterp = FunInterp+ { fiTable :: !(Map [Value] Value)+ , fiDefault :: !Value+ }+ deriving (Eq, Show)++-- | The interpretation that returns the given value for every argument tuple.+constInterp :: Value -> FunInterp+constInterp = FunInterp Map.empty++-- | An interpretation of uninterpreted symbols.+--+-- SMT-LIB leaves integer division and remainder by zero unspecified: they+-- behave as uninterpreted functions of the dividend. Their interpretation is+-- therefore part of a model as well. The same holds for the floating-point+-- results SMT-LIB leaves unspecified ('interpUnspecified').+data Interpretation = Interpretation+ { interpSymbols :: !(Map Symbol FunInterp)+ , interpDivByZero :: !FunInterp+ , interpModByZero :: !FunInterp+ , interpUnspecified :: !(Map (Op, [Value]) Value)+ -- ^ Results of @fp.min@ and @fp.max@ of zeros of different signs, and+ -- of @fp.to_ubv@ and @fp.to_sbv@ of NaN, infinities and values out of+ -- range, by operator and arguments. Missing entries are the first+ -- argument (for @fp.min@ and @fp.max@) and zero.+ }+ deriving (Eq, Show)++-- | The interpretation with no symbols, where division and remainder by zero+-- return @0@ and unspecified floating-point results take their defaults.+emptyInterpretation :: Interpretation+emptyInterpretation =+ Interpretation Map.empty (constInterp (VInt 0)) (constInterp (VInt 0)) Map.empty++-- | An evaluation failure: an operator applied to arguments it does not+-- accept (ill-sorted or otherwise invalid).+data EvalError = EvalError+ { eeOp :: Op+ -- ^ The operator being applied.+ , eeArgs :: [Value]+ -- ^ The argument values it received.+ , eeMessage :: Text+ -- ^ A human-readable description of the problem.+ }+ deriving (Eq, Show)++-- | Evaluate an expression. Symbols missing from the interpretation take the+-- default value of their sort.+evalExpr :: Interpretation -> Expr -> Either EvalError Value+evalExpr interp = go+ where+ go (App Ite [c, t, e]) =+ go c >>= \case+ VBool True -> go t+ VBool False -> go e+ v -> Left (EvalError Ite [v] "condition is not Boolean")+ go (App op args) = traverse go args >>= applyOp interp op++-- | Apply an operator to argument values.+applyOp :: Interpretation -> Op -> [Value] -> Either EvalError Value+applyOp interp op vs = case (op, vs) of+ (Uninterpreted sym, _) ->+ pure $ case Map.lookup sym (interpSymbols interp) of+ Just fi -> Map.findWithDefault (fiDefault fi) vs (fiTable fi)+ Nothing -> defaultValue (symResult sym)+ -- Booleans+ (BoolConst b, []) -> bool b+ (Not, [VBool a]) -> bool (not a)+ (And, _) -> VBool . and <$> traverse asBool vs+ (Or, _) -> VBool . or <$> traverse asBool vs+ (Xor, _) -> VBool . foldl' (/=) False <$> traverse asBool vs+ (Implies, _ : _) -> do+ bs <- traverse asBool vs+ -- Right associative: a => b => c is a => (b => c).+ pure (VBool (foldr1 (\a b -> not a || b) bs))+ (Ite, [VBool c, t, e]) -> pure (if c then t else e)+ -- Regular languages are equal when they have the same strings.+ (Eq, VRegLan r : rest) -> VBool . and <$> traverse (sameLanguage r) rest+ (Distinct, VRegLan _ : _) ->+ VBool . not . or+ <$> sequence [sameLanguage a (VRegLan b) | (i, VRegLan a) <- zip [0 :: Int ..] vs, VRegLan b <- drop (i + 1) vs]+ (Eq, x : rest) -> bool (all (== x) rest)+ (Distinct, _) -> bool (allDistinct vs)+ -- Integers+ (IntConst n, []) -> int n+ (Add, _) -> VInt . sum <$> traverse asInt vs+ (Mul, _) -> VInt . product <$> traverse asInt vs+ (Sub, _) -> traverse asInt vs >>= \case+ (x : xs) -> int (foldl' (-) x xs)+ [] -> bad "no arguments"+ (Neg, [VInt a]) -> int (negate a)+ (IntDiv, [VInt a, VInt b])+ | b == 0 -> pure (applyFun (interpDivByZero interp) [VInt a])+ | otherwise -> int (fst (euclidean a b))+ (IntMod, [VInt a, VInt b])+ | b == 0 -> pure (applyFun (interpModByZero interp) [VInt a])+ | otherwise -> int (snd (euclidean a b))+ (Abs, [VInt a]) -> int (abs a)+ (Le, _) -> chain (<=) =<< traverse asInt vs+ (Lt, _) -> chain (<) =<< traverse asInt vs+ (Ge, _) -> chain (>=) =<< traverse asInt vs+ (Gt, _) -> chain (>) =<< traverse asInt vs+ -- Bit-vectors+ (BVConst w x, []) -> pure (VBV w x)+ (BVNot, [VBV w a]) -> bv w (complement a)+ (BVNeg, [VBV w a]) -> bv w (negate a)+ (BVAnd, VBV w _ : _) -> bv w . foldr1 (.&.) =<< traverse asBV vs+ (BVOr, VBV w _ : _) -> bv w . foldr1 (.|.) =<< traverse asBV vs+ (BVXor, VBV w _ : _) -> bv w . foldr1 xor =<< traverse asBV vs+ (BVAdd, VBV w _ : _) -> bv w . sum =<< traverse asBV vs+ (BVMul, VBV w _ : _) -> bv w . product =<< traverse asBV vs+ (BVSub, [VBV w a, VBV _ b]) -> bv w (a - b)+ (BVUDiv, [VBV w a, VBV _ b]) -> bv w (udiv w a b)+ (BVURem, [VBV w a, VBV _ b]) -> bv w (urem a b)+ (BVSDiv, [VBV w a, VBV _ b]) -> bv w (sdiv w a b)+ (BVSRem, [VBV w a, VBV _ b]) -> bv w (srem w a b)+ (BVSMod, [VBV w a, VBV _ b]) -> bv w (smod w a b)+ (BVShl, [VBV w a, VBV _ b]) -> bv w (if b >= fromIntegral w then 0 else a `shiftL` fromIntegral b)+ (BVLShr, [VBV w a, VBV _ b]) -> bv w (if b >= fromIntegral w then 0 else a `shiftR` fromIntegral b)+ (BVAShr, [VBV w a, VBV _ b]) ->+ let sa = bvToSigned w a+ sh = if b >= fromIntegral w then w else fromIntegral b+ in bv w (sa `shiftR` sh)+ (BVConcat, _) -> do+ parts <- traverse (\case VBV w x -> Right (w, x); v -> badArg v) vs+ let w = sum (map fst parts)+ x = foldl' (\acc (wi, xi) -> (acc `shiftL` wi) .|. xi) 0 parts+ pure (VBV w x)+ (BVExtract h l, [VBV _ a]) -> pure (VBV (h - l + 1) ((a `shiftR` l) .&. bvMask (h - l + 1)))+ (BVZeroExtend k, [VBV w a]) -> pure (VBV (w + k) a)+ (BVSignExtend k, [VBV w a]) -> bv (w + k) (bvToSigned w a)+ (BVULt, [VBV _ a, VBV _ b]) -> bool (a < b)+ (BVULe, [VBV _ a, VBV _ b]) -> bool (a <= b)+ (BVUGt, [VBV _ a, VBV _ b]) -> bool (a > b)+ (BVUGe, [VBV _ a, VBV _ b]) -> bool (a >= b)+ (BVSLt, [VBV w a, VBV _ b]) -> bool (bvToSigned w a < bvToSigned w b)+ (BVSLe, [VBV w a, VBV _ b]) -> bool (bvToSigned w a <= bvToSigned w b)+ (BVSGt, [VBV w a, VBV _ b]) -> bool (bvToSigned w a > bvToSigned w b)+ (BVSGe, [VBV w a, VBV _ b]) -> bool (bvToSigned w a >= bvToSigned w b)+ -- Arrays+ (Select, [a@VArray {}, i]) -> pure (arraySelect a i)+ (Store, [a@VArray {}, i, e]) -> pure (arrayStore a i e)+ (ConstArray idx, [e]) -> pure (mkArray idx Map.empty e)+ -- Strings+ (StrConst s, []) -> str s+ (StrConcat, _) -> VString . T.concat <$> traverse asStr vs+ (StrLen, [VString s]) -> int (fromIntegral (T.length s))+ (StrAt, [VString s, VInt i]) -> str (substr s i 1)+ (StrSubstr, [VString s, VInt i, VInt n]) -> str (substr s i n)+ (StrContains, [VString s, VString t]) -> bool (t `T.isInfixOf` s)+ (StrPrefixOf, [VString s, VString t]) -> bool (s `T.isPrefixOf` t)+ (StrSuffixOf, [VString s, VString t]) -> bool (s `T.isSuffixOf` t)+ (StrIndexOf, [VString s, VString t, VInt i]) -> int (indexOf s t i)+ (StrReplace, [VString s, VString t, VString t']) -> str (replaceFirst s t t')+ (StrToInt, [VString s])+ | not (T.null s) && T.all isDigit s -> int (read (T.unpack s))+ | otherwise -> int (-1)+ (StrFromInt, [VInt n])+ | n >= 0 -> str (T.pack (show n))+ | otherwise -> str ""+ (StrLt, [VString s, VString t]) -> bool (s < t)+ (StrLe, [VString s, VString t]) -> bool (s <= t)+ -- Regular expressions+ (StrToRe, [VString s]) -> re (R.literal s)+ (StrInRe, [VString s, VRegLan r]) -> bool (R.matches r s)+ (ReNone, []) -> re R.none+ (ReAll, []) -> re R.everything+ (ReAllChar, []) -> re R.allChar+ (ReConcat, _) -> VRegLan . foldr1 R.cat <$> traverse asRe vs+ (ReUnion, _) -> VRegLan . R.union <$> traverse asRe vs+ (ReInter, _) -> VRegLan . R.inter <$> traverse asRe vs+ (ReStar, [VRegLan r]) -> re (R.star r)+ (RePlus, [VRegLan r]) -> re (R.plus r)+ (ReOpt, [VRegLan r]) -> re (R.opt r)+ (ReRange, [VString a, VString b]) -> re (R.range a b)+ (ReComp, [VRegLan r]) -> re (R.complement r)+ (ReDiff, VRegLan r : rest) -> VRegLan . foldl R.difference r <$> traverse asRe rest+ (ReLoop i j, [VRegLan r]) -> re (R.loop i j r)+ (RePower n, [VRegLan r]) -> re (R.power n r)+ -- Records+ (RecordMk names, _) -> pure (VRecord (zip names vs))+ (RecordGet f, [VRecord fs]) -> case lookup f fs of+ Just v -> pure v+ Nothing -> bad ("missing field " <> f)+ (RecordSet f, [VRecord fs, v]) ->+ pure (VRecord [(g, if g == f then v else u) | (g, u) <- fs])+ -- Floating point+ (FPConst eb sb x, []) -> pure (VFP eb sb x)+ (RMConst rm, []) -> pure (VRM rm)+ (FPFromFields, [VBV 1 sg, VBV eb e, VBV f m]) -> pure (VFP eb (f + 1) (F.fpFromFields eb (f + 1) sg e m))+ (FPAbs, [VFP eb sb x]) -> fp eb sb (F.fpAbs eb sb x)+ (FPNeg, [VFP eb sb x]) -> fp eb sb (F.fpNeg eb sb x)+ (FPAdd, [VRM rm, VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpAdd rm eb sb x y)+ (FPSub, [VRM rm, VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpSub rm eb sb x y)+ (FPMul, [VRM rm, VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpMul rm eb sb x y)+ (FPDiv, [VRM rm, VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpDiv rm eb sb x y)+ (FPFma, [VRM rm, VFP eb sb x, VFP _ _ y, VFP _ _ z]) -> fp eb sb (F.fpFma rm eb sb x y z)+ (FPSqrt, [VRM rm, VFP eb sb x]) -> fp eb sb (F.fpSqrt rm eb sb x)+ (FPRem, [VFP eb sb x, VFP _ _ y]) -> fp eb sb (F.fpRem F.RNE eb sb x y)+ (FPRoundToIntegral, [VRM rm, VFP eb sb x]) -> fp eb sb (F.fpRoundToIntegral rm eb sb x)+ (FPMin, [VFP eb sb x, VFP _ _ y]) -> unspecified (VFP eb sb x) (VFP eb sb <$> F.fpMin eb sb x y)+ (FPMax, [VFP eb sb x, VFP _ _ y]) -> unspecified (VFP eb sb x) (VFP eb sb <$> F.fpMax eb sb x y)+ (FPLeq, VFP eb sb _ : _) -> fpChain (F.fpLeq eb sb)+ (FPLt, VFP eb sb _ : _) -> fpChain (F.fpLt eb sb)+ (FPGeq, VFP eb sb _ : _) -> fpChain (flip (F.fpLeq eb sb))+ (FPGt, VFP eb sb _ : _) -> fpChain (flip (F.fpLt eb sb))+ (FPEq, VFP eb sb _ : _) -> fpChain (F.fpEq eb sb)+ (FPIsNormal, [VFP eb sb x]) -> bool (F.fpIsNormal eb sb x)+ (FPIsSubnormal, [VFP eb sb x]) -> bool (F.fpIsSubnormal eb sb x)+ (FPIsZero, [VFP eb sb x]) -> bool (case F.decode eb sb x of F.Zero _ -> True; _ -> False)+ (FPIsInfinite, [VFP eb sb x]) -> bool (case F.decode eb sb x of F.Inf _ -> True; _ -> False)+ (FPIsNaN, [VFP eb sb x]) -> bool (F.decode eb sb x == F.NaN)+ (FPIsNegative, [VFP eb sb x]) -> bool (fpSign eb sb x == Just True)+ (FPIsPositive, [VFP eb sb x]) -> bool (fpSign eb sb x == Just False)+ (ToFP eb sb, [VBV _ x]) -> pure (VFP eb sb (F.canonicalize eb sb x))+ (ToFP eb sb, [VRM rm, VFP eb' sb' x]) -> fp eb sb (F.fpConvert rm (eb', sb') (eb, sb) x)+ (ToFP eb sb, [VRM rm, VBV w x]) -> fp eb sb (F.fpFromInteger rm eb sb (bvToSigned w x))+ (ToFPUnsigned eb sb, [VRM rm, VBV _ x]) -> fp eb sb (F.fpFromInteger rm eb sb x)+ (FPToUBV w, [VRM rm, VFP eb sb x]) ->+ unspecified (VBV w 0) (VBV w <$> F.fpToInteger rm eb sb (0, bvMask w) x)+ (FPToSBV w, [VRM rm, VFP eb sb x]) ->+ unspecified (VBV w 0) (VBV w . bvNormalize w <$> F.fpToInteger rm eb sb (negate (2 ^ (w - 1)), 2 ^ (w - 1) - 1) x)+ _ -> bad "ill-sorted application"+ where+ fp eb sb x = pure (VFP eb sb x)+ unspecified def = \case+ Just v -> pure v+ Nothing -> pure (Map.findWithDefault def (op, vs) (interpUnspecified interp))+ fpChain rel = do+ xs <- traverse (\case VFP _ _ x -> Right x; v -> badArg v) vs+ bool (and (zipWith rel xs (drop 1 xs)))+ fpSign eb sb x = case F.decode eb sb x of+ F.NaN -> Nothing+ F.Inf neg -> Just neg+ F.Zero neg -> Just neg+ F.Finite neg _ -> Just neg+ bad msg = Left (EvalError op vs msg)+ re = pure . VRegLan+ asRe = \case+ VRegLan r -> pure r+ _ -> bad "expected a regular language"+ sameLanguage r = \case+ VRegLan r' -> case R.equivalent r r' of+ Just b -> pure b+ Nothing -> bad "regular expressions too large to compare"+ _ -> bad "expected a regular language"+ badArg v = Left (EvalError op vs ("unexpected argument " <> prettyValue v))+ bool = pure . VBool+ int = pure . VInt+ str = pure . VString+ bv w x = pure (VBV w (bvNormalize w x))++ asBool = \case VBool b -> Right b; v -> badArg v+ asInt = \case VInt n -> Right n; v -> badArg v+ asStr = \case VString s -> Right s; v -> badArg v+ asBV = \case VBV _ x -> Right x; v -> badArg v++ chain rel xs = bool (and (zipWith rel xs (drop 1 xs)))++ allDistinct [] = True+ allDistinct (x : xs) = notElem x xs && allDistinct xs++applyFun :: FunInterp -> [Value] -> Value+applyFun fi args = Map.findWithDefault (fiDefault fi) args (fiTable fi)++-- | Euclidean division: @a = b * q + r@ with @0 <= r < |b|@.+euclidean :: Integer -> Integer -> (Integer, Integer)+euclidean a b =+ let r = a `mod` abs b+ in ((a - r) `div` b, r)++udiv :: Int -> Integer -> Integer -> Integer+udiv w a b+ | b == 0 = bvMask w+ | otherwise = a `div` b++urem :: Integer -> Integer -> Integer+urem a b+ | b == 0 = a+ | otherwise = a `mod` b++msb :: Int -> Integer -> Bool+msb w x = testBit x (w - 1)++bvNegate :: Int -> Integer -> Integer+bvNegate w x = bvNormalize w (negate x)++sdiv :: Int -> Integer -> Integer -> Integer+sdiv w s t = case (msb w s, msb w t) of+ (False, False) -> udiv w s t+ (True, False) -> bvNegate w (udiv w (bvNegate w s) t)+ (False, True) -> bvNegate w (udiv w s (bvNegate w t))+ (True, True) -> udiv w (bvNegate w s) (bvNegate w t)++srem :: Int -> Integer -> Integer -> Integer+srem w s t = case (msb w s, msb w t) of+ (False, False) -> urem s t+ (True, False) -> bvNegate w (urem (bvNegate w s) t)+ (False, True) -> urem s (bvNegate w t)+ (True, True) -> bvNegate w (urem (bvNegate w s) (bvNegate w t))++smod :: Int -> Integer -> Integer -> Integer+smod w s t =+ let absS = if msb w s then bvNegate w s else s+ absT = if msb w t then bvNegate w t else t+ u = urem absS absT+ in if u == 0+ then u+ else case (msb w s, msb w t) of+ (False, False) -> u+ (True, False) -> bvNormalize w (bvNegate w u + t)+ (False, True) -> bvNormalize w (u + t)+ (True, True) -> bvNegate w u++-- | SMT-LIB @str.substr@: empty unless the offset is within bounds and the+-- length is positive.+substr :: Text -> Integer -> Integer -> Text+substr s i n+ | i < 0 || n <= 0 || i >= len = ""+ | otherwise = T.take (fromIntegral (min n (len - i))) (T.drop (fromIntegral i) s)+ where+ len = fromIntegral (T.length s)++-- | SMT-LIB @str.indexof@.+indexOf :: Text -> Text -> Integer -> Integer+indexOf s t i+ | i < 0 || i > len = -1+ | T.null t = i+ | otherwise =+ -- Note: 'T.breakOn' rejects an empty pattern, handled above.+ case T.breakOn t (T.drop (fromIntegral i) s) of+ (before, after)+ | T.null after -> -1+ | otherwise -> i + fromIntegral (T.length before)+ where+ len = fromIntegral (T.length s)++-- | SMT-LIB @str.replace@: replaces the first occurrence; an empty pattern+-- prepends the replacement.+replaceFirst :: Text -> Text -> Text -> Text+replaceFirst s t t'+ | T.null t = t' <> s+ | otherwise = case T.breakOn t s of+ (before, after)+ | T.null after -> s+ | otherwise -> before <> t' <> T.drop (T.length t) after
+ src/HSMT/Core/Expr.hs view
@@ -0,0 +1,37 @@+-- | Untyped core expressions.+--+-- Core expressions are plain trees. They are produced by the typed API and by+-- front-ends, and are interned into a hash-consed DAG ('HSMT.Core.Term')+-- before solving.+module HSMT.Core.Expr+ ( Expr (..)+ , app+ , constant+ , symbols+ ) where++import qualified Data.Set as Set++import HSMT.Core.Op++-- | An operator applied to its arguments.+data Expr = App !Op [Expr]+ deriving (Eq, Ord, Show)++-- | Apply an operator to a list of arguments (no sort checking).+app :: Op -> [Expr] -> Expr+app = App++-- | A nullary operator.+constant :: Op -> Expr+constant op = App op []++-- | All uninterpreted symbols occurring in an expression.+symbols :: Expr -> Set.Set Symbol+symbols = go Set.empty+ where+ go acc (App op args) =+ let acc' = case op of+ Uninterpreted s -> Set.insert s acc+ _ -> acc+ in foldl go acc' args
+ src/HSMT/Core/Float.hs view
@@ -0,0 +1,467 @@+-- | Reference semantics of the SMT-LIB theory of floating-point numbers+-- (IEEE 754-2008, binary formats).+--+-- A floating-point value of the format @(eb, sb)@ (exponent width @eb@,+-- significand width @sb@ including the hidden bit, both at least 2) is kept+-- as its IEEE bit pattern of @eb + sb@ bits. SMT-LIB has a single NaN, so+-- every NaN pattern is replaced by the canonical one ('canonicalNaN'):+-- equal values then have equal patterns.+--+-- Operations are computed exactly on rationals and rounded once, which is+-- the definition of IEEE arithmetic. Results that SMT-LIB leaves+-- unspecified (@fp.min@ and @fp.max@ of zeros of different signs,+-- conversions to bit-vectors of NaN, infinities and values out of range)+-- are 'Nothing'.+module HSMT.Core.Float+ ( RoundingMode (..)+ , allRoundingModes+ , rmName+ -- * Bit patterns+ , FP (..)+ , decode+ , encode+ , canonicalNaN+ , canonicalize+ , isNaNBits+ , fpWidth+ , fpBias+ , fpFromFields+ , fpToRational+ -- * Rounding+ , roundRational+ , roundToInteger+ -- * Operations+ , fpAbs+ , fpNeg+ , fpAdd+ , fpSub+ , fpMul+ , fpDiv+ , fpFma+ , fpSqrt+ , fpRem+ , fpRoundToIntegral+ , fpMin+ , fpMax+ , fpLeq+ , fpLt+ , fpEq+ , fpIsNormal+ , fpIsSubnormal+ , fpConvert+ , fpFromInteger+ , fpToInteger+ ) where++import Data.Bits (shiftL, shiftR, testBit, (.&.), (.|.))+import Data.Ratio (denominator, numerator, (%))+import Data.Text (Text)++-- | The five IEEE rounding modes.+data RoundingMode+ = RNE+ -- ^ Round to nearest, ties to even.+ | RNA+ -- ^ Round to nearest, ties away from zero.+ | RTP+ -- ^ Round towards positive infinity.+ | RTN+ -- ^ Round towards negative infinity.+ | RTZ+ -- ^ Round towards zero.+ deriving (Eq, Ord, Show, Enum, Bounded)++-- | Every rounding mode, in declaration order.+allRoundingModes :: [RoundingMode]+allRoundingModes = [minBound .. maxBound]++-- | The SMT-LIB short name of a rounding mode.+rmName :: RoundingMode -> Text+rmName = \case+ RNE -> "RNE"+ RNA -> "RNA"+ RTP -> "RTP"+ RTN -> "RTN"+ RTZ -> "RTZ"++-- | A decoded floating-point value. The flag is the sign (True for+-- negative); finite magnitudes are positive.+data FP+ = NaN+ -- ^ Not a number (SMT-LIB has a single NaN).+ | Inf Bool+ -- ^ An infinity of the given sign.+ | Zero Bool+ -- ^ A zero of the given sign.+ | Finite Bool Rational+ -- ^ A nonzero finite value: sign and (positive) magnitude.+ deriving (Eq, Show)++-- | Total bit width @eb + sb@ of the format @(eb, sb)@.+fpWidth :: Int -> Int -> Int+fpWidth eb sb = eb + sb++-- | Exponent bias @2^(eb-1) - 1@ for an exponent width @eb@.+fpBias :: Int -> Integer+fpBias eb = 2 ^ (eb - 1) - 1++-- | Smallest normal exponent and largest exponent.+eMin, eMax :: Int -> Integer+eMin eb = 1 - fpBias eb+eMax eb = fpBias eb++-- | Largest finite magnitude.+maxFinite :: Int -> Int -> Rational+maxFinite eb sb = fromInteger (2 ^ sb - 1) * pow2 (eMax eb - fromIntegral (sb - 1))++pow2 :: Integer -> Rational+pow2 k+ | k >= 0 = fromInteger (2 ^ k)+ | otherwise = 1 % (2 ^ negate k)++-- | The canonical NaN: positive, all-ones exponent, quiet bit set.+canonicalNaN :: Int -> Int -> Integer+canonicalNaN eb sb = ((2 ^ eb - 1) `shiftL` (sb - 1)) .|. (1 `shiftL` (sb - 2))++-- | Whether a bit pattern of the format @(eb, sb)@ is any NaN.+isNaNBits :: Int -> Int -> Integer -> Bool+isNaNBits eb sb bits = case decode eb sb bits of+ NaN -> True+ _ -> False++-- | Replace any NaN pattern by 'canonicalNaN'; other patterns are+-- unchanged.+canonicalize :: Int -> Int -> Integer -> Integer+canonicalize eb sb bits+ | isNaNBits eb sb bits = canonicalNaN eb sb+ | otherwise = bits++-- | The value of the @fp@ constructor: sign bit, biased exponent and+-- trailing significand.+fpFromFields :: Int -> Int -> Integer -> Integer -> Integer -> Integer+fpFromFields eb sb s e f =+ canonicalize eb sb ((s `shiftL` (eb + sb - 1)) .|. (e `shiftL` (sb - 1)) .|. f)++-- | Decode a bit pattern of the format @(eb, sb)@ (every NaN pattern+-- decodes to 'NaN').+decode :: Int -> Int -> Integer -> FP+decode eb sb bits+ | e == 2 ^ eb - 1 = if f == 0 then Inf s else NaN+ | e == 0 = if f == 0 then Zero s else Finite s (fromInteger f * pow2 (eMin eb - q))+ | otherwise = Finite s (fromInteger (2 ^ (sb - 1) + f) * pow2 (e - fpBias eb - q))+ where+ s = testBit bits (eb + sb - 1)+ e = (bits `shiftR` (sb - 1)) .&. (2 ^ eb - 1)+ f = bits .&. (2 ^ (sb - 1) - 1)+ q = fromIntegral (sb - 1)++-- | The bit pattern of a value. Finite magnitudes must be representable.+encode :: Int -> Int -> FP -> Integer+encode eb sb = \case+ NaN -> canonicalNaN eb sb+ Inf s -> signBit s .|. ((2 ^ eb - 1) `shiftL` (sb - 1))+ Zero s -> signBit s+ Finite s m+ | m < pow2 (eMin eb) ->+ -- Subnormal: exponent field zero.+ signBit s .|. exactInteger (m / pow2 (eMin eb - q))+ | otherwise ->+ let e = floorLog2 m+ sig = exactInteger (m / pow2 (e - q))+ in signBit s .|. ((e + fpBias eb) `shiftL` (sb - 1)) .|. (sig - 2 ^ (sb - 1))+ where+ signBit s = if s then 1 `shiftL` (eb + sb - 1) else 0+ q = fromIntegral (sb - 1)+ exactInteger r+ | denominator r == 1 = numerator r+ | otherwise = error "hsmt: encode: value not representable"++-- | @floorLog2 r@ for a positive rational: the @e@ with @2^e <= r < 2^(e+1)@.+floorLog2 :: Rational -> Integer+floorLog2 r = adjust (bitLength (numerator r) - bitLength (denominator r))+ where+ adjust e+ | pow2 e > r = adjust (e - 1)+ | pow2 (e + 1) <= r = adjust (e + 1)+ | otherwise = e+ bitLength :: Integer -> Integer+ bitLength n = go 0 n+ where+ go acc 0 = acc+ go acc k = go (acc + 1) (k `shiftR` 1)++-- | The real value of a finite or zero value.+fpToRational :: FP -> Maybe Rational+fpToRational = \case+ Zero _ -> Just 0+ Finite s m -> Just (if s then negate m else m)+ _ -> Nothing++-------------------------------------------------------------------------------+-- Rounding++-- | Round a non-negative magnitude to an integer, for a value of the given+-- sign.+roundToInteger :: RoundingMode -> Bool -> Rational -> Integer+roundToInteger rm neg n = case rm of+ RTZ -> fl+ RNE+ | fr > 1 % 2 -> fl + 1+ | fr < 1 % 2 -> fl+ | otherwise -> if even fl then fl else fl + 1+ RNA -> if fr >= 1 % 2 then fl + 1 else fl+ RTP -> if neg then fl else up+ RTN -> if neg then up else fl+ where+ fl = floor n+ fr = n - fromInteger fl+ up = if fr == 0 then fl else fl + 1++-- | Round a signed magnitude (positive) into the format.+roundRational :: RoundingMode -> Int -> Int -> Bool -> Rational -> FP+roundRational rm eb sb neg m+ | k == 0 = Zero neg+ | v > maxFinite eb sb = overflow+ | otherwise = Finite neg v+ where+ e = max (floorLog2 m) (eMin eb)+ quantum = pow2 (e - fromIntegral (sb - 1))+ k = roundToInteger rm neg (m / quantum)+ v = fromInteger k * quantum+ overflow = case rm of+ RNE -> Inf neg+ RNA -> Inf neg+ RTZ -> Finite neg (maxFinite eb sb)+ RTP -> if neg then Finite neg (maxFinite eb sb) else Inf neg+ RTN -> if neg then Inf neg else Finite neg (maxFinite eb sb)++-- | Round a signed rational; zero results take the given sign.+roundSigned :: RoundingMode -> Int -> Int -> Bool -> Rational -> FP+roundSigned rm eb sb zeroSign r+ | r == 0 = Zero zeroSign+ | otherwise = roundRational rm eb sb (r < 0) (abs r)++-------------------------------------------------------------------------------+-- Operations++type Fmt = (Int, Int)++lift1 :: Fmt -> (FP -> FP) -> Integer -> Integer+lift1 (eb, sb) f x = encode eb sb (f (decode eb sb x))++lift2 :: Fmt -> (FP -> FP -> FP) -> Integer -> Integer -> Integer+lift2 (eb, sb) f x y = encode eb sb (f (decode eb sb x) (decode eb sb y))++-- | @fp.abs@ and @fp.neg@: clear or flip the sign (NaN stays NaN).+fpAbs, fpNeg :: Int -> Int -> Integer -> Integer+fpAbs eb sb = lift1 (eb, sb) $ \case+ Inf _ -> Inf False+ Zero _ -> Zero False+ Finite _ m -> Finite False m+ NaN -> NaN+fpNeg eb sb = lift1 (eb, sb) $ \case+ Inf s -> Inf (not s)+ Zero s -> Zero (not s)+ Finite s m -> Finite (not s) m+ NaN -> NaN++-- | @fp.add@, @fp.sub@, @fp.mul@, @fp.div@ and @fp.rem@ on bit patterns.+-- @fp.rem@ is the IEEE remainder (quotient rounded to nearest even), which+-- is exact, so its rounding mode argument is ignored.+fpAdd, fpSub, fpMul, fpDiv, fpRem :: RoundingMode -> Int -> Int -> Integer -> Integer -> Integer+fpAdd rm eb sb = lift2 (eb, sb) (addFP rm eb sb)+fpSub rm eb sb x y = fpAdd rm eb sb x (fpNeg eb sb y)+fpMul rm eb sb = lift2 (eb, sb) $ \a b -> case (a, b) of+ (NaN, _) -> NaN+ (_, NaN) -> NaN+ (Inf _, Zero _) -> NaN+ (Zero _, Inf _) -> NaN+ (Inf s, _) -> Inf (s /= signOf b)+ (_, Inf s) -> Inf (s /= signOf a)+ (Zero s, _) -> Zero (s /= signOf b)+ (_, Zero s) -> Zero (s /= signOf a)+ (Finite s m, Finite t n) -> roundRational rm eb sb (s /= t) (m * n)+fpDiv rm eb sb = lift2 (eb, sb) $ \a b -> case (a, b) of+ (NaN, _) -> NaN+ (_, NaN) -> NaN+ (Inf _, Inf _) -> NaN+ (Zero _, Zero _) -> NaN+ (Inf s, _) -> Inf (s /= signOf b)+ (_, Inf s) -> Zero (s /= signOf a)+ (_, Zero s) -> Inf (s /= signOf a)+ (Zero s, _) -> Zero (s /= signOf b)+ (Finite s m, Finite t n) -> roundRational rm eb sb (s /= t) (m / n)+fpRem _ eb sb = lift2 (eb, sb) $ \a b -> case (a, b) of+ (NaN, _) -> NaN+ (_, NaN) -> NaN+ (Inf _, _) -> NaN+ (_, Zero _) -> NaN+ (_, Inf _) -> a+ (Zero _, _) -> a+ (Finite s m, Finite t n) ->+ let x = if s then negate m else m+ y = if t then negate n else n+ q = x / y+ k = roundToInteger RNE (q < 0) (abs q)+ r = x - y * fromInteger (if q < 0 then negate k else k)+ in -- The remainder is exact; a zero remainder has the sign of x.+ roundSigned RNE eb sb s r++signOf :: FP -> Bool+signOf = \case+ Inf s -> s+ Zero s -> s+ Finite s _ -> s+ NaN -> False++addFP :: RoundingMode -> Int -> Int -> FP -> FP -> FP+addFP rm eb sb a b = case (a, b) of+ (NaN, _) -> NaN+ (_, NaN) -> NaN+ (Inf s, Inf t) -> if s == t then Inf s else NaN+ (Inf s, _) -> Inf s+ (_, Inf t) -> Inf t+ (Zero s, Zero t) -> Zero (if s == t then s else rm == RTN)+ (Zero _, _) -> b+ (_, Zero _) -> a+ _ -> case (fpToRational a, fpToRational b) of+ (Just x, Just y) -> roundSigned rm eb sb (rm == RTN) (x + y)+ _ -> error "unreachable"++-- | @fp.fma@: fused multiply-add @x * y + z@ with a single rounding.+fpFma :: RoundingMode -> Int -> Int -> Integer -> Integer -> Integer -> Integer+fpFma rm eb sb x y z = encode eb sb $ case (decode eb sb x, decode eb sb y, decode eb sb z) of+ (NaN, _, _) -> NaN+ (_, NaN, _) -> NaN+ (_, _, NaN) -> NaN+ (Inf _, Zero _, _) -> NaN+ (Zero _, Inf _, _) -> NaN+ (a, b, c)+ | isInf a || isInf b ->+ let ps = signOf a /= signOf b+ in case c of+ Inf t | t /= ps -> NaN+ _ -> Inf ps+ | isInf c -> c+ | otherwise ->+ let ps = signOf a /= signOf b+ p = maybe 0 id ((*) <$> fpToRational a <*> fpToRational b)+ in case (p == 0, c) of+ (True, Zero t) -> Zero (if ps == t then t else rm == RTN)+ (True, _) -> c+ (False, Zero _) -> roundSigned rm eb sb ps p+ (False, _) -> roundSigned rm eb sb (rm == RTN) (p + maybe 0 id (fpToRational c))+ where+ isInf = \case+ Inf _ -> True+ _ -> False++-- | @fp.sqrt@: correctly rounded square root (NaN for negative operands;+-- @-0@ maps to @-0@).+fpSqrt :: RoundingMode -> Int -> Int -> Integer -> Integer+fpSqrt rm eb sb = lift1 (eb, sb) $ \case+ NaN -> NaN+ Zero s -> Zero s+ Inf False -> Inf False+ Inf True -> NaN+ Finite True _ -> NaN+ Finite False m ->+ -- m = mi * 2^e with an even e; the root of mi * 4^k is computed with+ -- enough bits (k > sb + 2) that replacing an inexact root by the+ -- midpoint of its integer interval does not change the rounding.+ let e0 = negate (floorLog2' (denominator m))+ mi0 = numerator m+ (mi, e) = if odd e0 then (2 * mi0, e0 - 1) else (mi0, e0)+ k = fromIntegral sb + 3+ big = mi * 4 ^ k+ r = isqrt big+ root = if r * r == big then fromInteger r else fromInteger r + 1 % 2+ in roundRational rm eb sb False (root * pow2 (e `div` 2 - k))+ where+ -- Denominators of finite values are powers of two.+ floorLog2' d = floorLog2 (fromInteger d)++-- | Integer square root (floor).+isqrt :: Integer -> Integer+isqrt 0 = 0+isqrt n = go n+ where+ go x =+ let y = (x + n `div` x) `div` 2+ in if y >= x then x else go y++-- | @fp.roundToIntegral@: round to an integral value in the same format,+-- keeping the sign of zero results.+fpRoundToIntegral :: RoundingMode -> Int -> Int -> Integer -> Integer+fpRoundToIntegral rm eb sb = lift1 (eb, sb) $ \case+ Finite s m ->+ let k = roundToInteger rm s m+ in if k == 0 then Zero s else Finite s (fromInteger k)+ v -> v++-- | @fp.min@ and @fp.max@; zeros of different signs are unspecified.+fpMin, fpMax :: Int -> Int -> Integer -> Integer -> Maybe Integer+fpMin eb sb = minMax eb sb True+fpMax eb sb = minMax eb sb False++minMax :: Int -> Int -> Bool -> Integer -> Integer -> Maybe Integer+minMax eb sb isMin x y = case (decode eb sb x, decode eb sb y) of+ (NaN, _) -> Just y+ (_, NaN) -> Just x+ (Zero s, Zero t) | s /= t -> Nothing+ (a, b)+ | isMin -> Just (if fpLess b a then y else x)+ | otherwise -> Just (if fpLess a b then y else x)++-- | Strict order on non-NaN values (zeros are equal).+fpLess :: FP -> FP -> Bool+fpLess a b = case (ext a, ext b) of+ (Just u, Just v) -> u < v+ _ -> False+ where+ ext :: FP -> Maybe (Int, Rational)+ ext = \case+ NaN -> Nothing+ Inf s -> Just (if s then -1 else 1, 0)+ v -> (,) 0 <$> fpToRational v++-- | @fp.leq@, @fp.lt@ and @fp.eq@: IEEE comparisons (false whenever an+-- operand is NaN; zeros of either sign are equal).+fpLeq, fpLt, fpEq :: Int -> Int -> Integer -> Integer -> Bool+fpLt eb sb x y = fpLess (decode eb sb x) (decode eb sb y)+fpEq eb sb x y = case (decode eb sb x, decode eb sb y) of+ (NaN, _) -> False+ (_, NaN) -> False+ (a, b) -> not (fpLess a b) && not (fpLess b a)+fpLeq eb sb x y = fpLt eb sb x y || fpEq eb sb x y++-- | @fp.isNormal@ and @fp.isSubnormal@ (both false for zeros, infinities+-- and NaN).+fpIsNormal, fpIsSubnormal :: Int -> Int -> Integer -> Bool+fpIsNormal eb sb x = case decode eb sb x of+ Finite _ m -> m >= pow2 (eMin eb)+ _ -> False+fpIsSubnormal eb sb x = case decode eb sb x of+ Finite _ m -> m < pow2 (eMin eb)+ _ -> False++-- | Conversion between formats.+fpConvert :: RoundingMode -> (Int, Int) -> (Int, Int) -> Integer -> Integer+fpConvert rm (eb, sb) (eb', sb') x = encode eb' sb' $ case decode eb sb x of+ Finite s m -> roundRational rm eb' sb' s m+ v -> v++-- | Conversion from an integer (signed or unsigned bit-vector value).+fpFromInteger :: RoundingMode -> Int -> Int -> Integer -> Integer+fpFromInteger rm eb sb n = encode eb sb (roundSigned rm eb sb False (fromInteger n))++-- | Conversion to an integer in the given (inclusive) range; unspecified+-- for NaN, infinities and out of range values.+fpToInteger :: RoundingMode -> Int -> Int -> (Integer, Integer) -> Integer -> Maybe Integer+fpToInteger rm eb sb (lo, hi) x = case decode eb sb x of+ Zero _ -> Just 0+ Finite s m ->+ let k = roundToInteger rm s m+ v = if s then negate k else k+ in if lo <= v && v <= hi then Just v else Nothing+ _ -> Nothing
+ src/HSMT/Core/Op.hs view
@@ -0,0 +1,295 @@+-- | Operators of the core term language.+--+-- Every term in the core is an operator applied to a (possibly empty) list+-- of arguments. Constants and declared symbols are nullary operators.+module HSMT.Core.Op+ ( Op (..)+ , Symbol (..)+ , opName+ ) where++import Data.Text (Text)+import qualified Data.Text as T++import HSMT.Core.Float (RoundingMode, rmName)+import HSMT.Core.Sort++-- | A user-declared symbol: a constant (no arguments) or an uninterpreted+-- function.+data Symbol = Symbol+ { symName :: !Text+ , symArgs :: ![Sort]+ , symResult :: !Sort+ }+ deriving (Eq, Ord, Show)++-- | An operator of the core language: an uninterpreted symbol, a literal+-- constant, or a built-in function of one of the supported theories.+data Op+ = -- Uninterpreted symbols+ Uninterpreted !Symbol+ | -- Core (Boolean) theory+ BoolConst !Bool+ | Not+ | And+ | Or+ | Xor+ | Implies+ | Ite+ | Eq+ | Distinct+ | -- Integers+ IntConst !Integer+ | Add+ | Sub+ | Neg+ | Mul+ | IntDiv+ -- ^ Euclidean division, as in SMT-LIB.+ | IntMod+ -- ^ Euclidean remainder, always non-negative.+ | Abs+ | Le+ | Lt+ | Ge+ | Gt+ | -- Bit-vectors+ BVConst !Int !Integer+ -- ^ Width and unsigned value, with @0 <= value < 2^width@.+ | BVNot+ | BVAnd+ | BVOr+ | BVXor+ | BVNeg+ | BVAdd+ | BVSub+ | BVMul+ | BVUDiv+ | BVURem+ | BVSDiv+ | BVSRem+ | BVSMod+ | BVShl+ | BVLShr+ | BVAShr+ | BVConcat+ | BVExtract !Int !Int+ -- ^ @BVExtract hi lo@ selects bits @hi@ down to @lo@ (inclusive).+ | BVZeroExtend !Int+ | BVSignExtend !Int+ | BVULt+ | BVULe+ | BVUGt+ | BVUGe+ | BVSLt+ | BVSLe+ | BVSGt+ | BVSGe+ | -- Arrays+ Select+ | Store+ | ConstArray !Sort+ -- ^ Constant array; the argument is the index sort.+ | -- Strings+ StrConst !Text+ | StrConcat+ | StrLen+ | StrAt+ | StrSubstr+ | StrContains+ | StrPrefixOf+ | StrSuffixOf+ | StrIndexOf+ | StrReplace+ | StrToInt+ | StrFromInt+ | StrLt+ | StrLe+ | -- Regular expressions+ StrToRe+ -- ^ @str.to_re@: the language of one string.+ | StrInRe+ -- ^ @str.in_re@: membership of a string in a language.+ | ReNone+ | ReAll+ | ReAllChar+ | ReConcat+ | ReUnion+ | ReInter+ | ReStar+ | RePlus+ | ReOpt+ | ReRange+ | ReComp+ | ReDiff+ | ReLoop !Int !Int+ -- ^ @(_ re.loop i j)@: between @i@ and @j@ repetitions.+ | RePower !Int+ -- ^ @(_ re.^ n)@: exactly @n@ repetitions.+ | -- Records+ RecordMk ![Text]+ -- ^ Record construction; the field names, in order.+ | RecordGet !Text+ | RecordSet !Text+ | -- Floating point+ FPConst !Int !Int !Integer+ -- ^ Format and bit pattern (NaN is always the canonical pattern, see+ -- 'HSMT.Core.Float.canonicalNaN').+ | RMConst !RoundingMode+ | FPFromFields+ -- ^ The @fp@ constructor: sign, biased exponent and trailing+ -- significand bit-vectors.+ | FPAbs+ | FPNeg+ | FPAdd+ | FPSub+ | FPMul+ | FPDiv+ | FPFma+ | FPSqrt+ | FPRem+ | FPRoundToIntegral+ | FPMin+ | FPMax+ | FPLeq+ | FPLt+ | FPGeq+ | FPGt+ | FPEq+ | FPIsNormal+ | FPIsSubnormal+ | FPIsZero+ | FPIsInfinite+ | FPIsNaN+ | FPIsNegative+ | FPIsPositive+ | ToFP !Int !Int+ -- ^ @(_ to_fp eb sb)@: from a bit pattern (one bit-vector argument),+ -- from another format or from a signed bit-vector (a rounding mode+ -- and the value).+ | ToFPUnsigned !Int !Int+ | FPToUBV !Int+ | FPToSBV !Int+ deriving (Eq, Ord, Show)++-- | SMT-LIB-like name of an operator, used for diagnostics and printing.+opName :: Op -> Text+opName = \case+ Uninterpreted s -> symName s+ BoolConst b -> if b then "true" else "false"+ Not -> "not"+ And -> "and"+ Or -> "or"+ Xor -> "xor"+ Implies -> "=>"+ Ite -> "ite"+ Eq -> "="+ Distinct -> "distinct"+ IntConst n -> T.pack (show n)+ Add -> "+"+ Sub -> "-"+ Neg -> "-"+ Mul -> "*"+ IntDiv -> "div"+ IntMod -> "mod"+ Abs -> "abs"+ Le -> "<="+ Lt -> "<"+ Ge -> ">="+ Gt -> ">"+ BVConst w v -> "(_ bv" <> T.pack (show v) <> " " <> T.pack (show w) <> ")"+ BVNot -> "bvnot"+ BVAnd -> "bvand"+ BVOr -> "bvor"+ BVXor -> "bvxor"+ BVNeg -> "bvneg"+ BVAdd -> "bvadd"+ BVSub -> "bvsub"+ BVMul -> "bvmul"+ BVUDiv -> "bvudiv"+ BVURem -> "bvurem"+ BVSDiv -> "bvsdiv"+ BVSRem -> "bvsrem"+ BVSMod -> "bvsmod"+ BVShl -> "bvshl"+ BVLShr -> "bvlshr"+ BVAShr -> "bvashr"+ BVConcat -> "concat"+ BVExtract h l -> "(_ extract " <> T.pack (show h) <> " " <> T.pack (show l) <> ")"+ BVZeroExtend k -> "(_ zero_extend " <> T.pack (show k) <> ")"+ BVSignExtend k -> "(_ sign_extend " <> T.pack (show k) <> ")"+ BVULt -> "bvult"+ BVULe -> "bvule"+ BVUGt -> "bvugt"+ BVUGe -> "bvuge"+ BVSLt -> "bvslt"+ BVSLe -> "bvsle"+ BVSGt -> "bvsgt"+ BVSGe -> "bvsge"+ Select -> "select"+ Store -> "store"+ ConstArray _ -> "const"+ StrConst s -> T.pack (show s)+ StrConcat -> "str.++"+ StrLen -> "str.len"+ StrAt -> "str.at"+ StrSubstr -> "str.substr"+ StrContains -> "str.contains"+ StrPrefixOf -> "str.prefixof"+ StrSuffixOf -> "str.suffixof"+ StrIndexOf -> "str.indexof"+ StrReplace -> "str.replace"+ StrToInt -> "str.to_int"+ StrFromInt -> "str.from_int"+ StrLt -> "str.<"+ StrLe -> "str.<="+ StrToRe -> "str.to_re"+ StrInRe -> "str.in_re"+ ReNone -> "re.none"+ ReAll -> "re.all"+ ReAllChar -> "re.allchar"+ ReConcat -> "re.++"+ ReUnion -> "re.union"+ ReInter -> "re.inter"+ ReStar -> "re.*"+ RePlus -> "re.+"+ ReOpt -> "re.opt"+ ReRange -> "re.range"+ ReComp -> "re.comp"+ ReDiff -> "re.diff"+ ReLoop i j -> "(_ re.loop " <> T.pack (show i) <> " " <> T.pack (show j) <> ")"+ RePower n -> "(_ re.^ " <> T.pack (show n) <> ")"+ RecordMk _ -> "record"+ RecordGet f -> "get." <> f+ RecordSet f -> "set." <> f+ FPConst eb sb x -> "(fp " <> T.pack (show (eb, sb, x)) <> ")"+ RMConst rm -> rmName rm+ FPFromFields -> "fp"+ FPAbs -> "fp.abs"+ FPNeg -> "fp.neg"+ FPAdd -> "fp.add"+ FPSub -> "fp.sub"+ FPMul -> "fp.mul"+ FPDiv -> "fp.div"+ FPFma -> "fp.fma"+ FPSqrt -> "fp.sqrt"+ FPRem -> "fp.rem"+ FPRoundToIntegral -> "fp.roundToIntegral"+ FPMin -> "fp.min"+ FPMax -> "fp.max"+ FPLeq -> "fp.leq"+ FPLt -> "fp.lt"+ FPGeq -> "fp.geq"+ FPGt -> "fp.gt"+ FPEq -> "fp.eq"+ FPIsNormal -> "fp.isNormal"+ FPIsSubnormal -> "fp.isSubnormal"+ FPIsZero -> "fp.isZero"+ FPIsInfinite -> "fp.isInfinite"+ FPIsNaN -> "fp.isNaN"+ FPIsNegative -> "fp.isNegative"+ FPIsPositive -> "fp.isPositive"+ ToFP eb sb -> "(_ to_fp " <> T.pack (show eb) <> " " <> T.pack (show sb) <> ")"+ ToFPUnsigned eb sb -> "(_ to_fp_unsigned " <> T.pack (show eb) <> " " <> T.pack (show sb) <> ")"+ FPToUBV w -> "(_ fp.to_ubv " <> T.pack (show w) <> ")"+ FPToSBV w -> "(_ fp.to_sbv " <> T.pack (show w) <> ")"
+ src/HSMT/Core/Regex.hs view
@@ -0,0 +1,445 @@+-- | Regular expressions over the SMT-LIB 2.6 alphabet (code points @0@ to+-- @0x2FFFF@), as the values of the sort @RegLan@.+--+-- Expressions are kept in a normal form by the smart constructors in this+-- module (as in Owens, Reppy and Turon, "Regular-expression derivatives+-- re-examined", 2009): concatenation is right-nested, unions and+-- intersections are sets, the characters of a union are merged into one+-- character set, and the usual identities (@none . r = none@, @(r*)* =+-- r*@, @~~r = r@...) are applied. With this normal form, the Brzozowski+-- derivatives of an expression are finitely many, so they give a+-- deterministic automaton; complement and intersection need no special+-- construction.+--+-- Membership ('matches') follows the derivatives along the string; the+-- automaton ('toDfa') groups characters into classes that have the same+-- derivative everywhere ('charClasses').+module HSMT.Core.Regex+ ( -- * Character sets+ CharSet+ , maxChar+ , fullSet+ , memberSet+ , -- * Expressions+ Regex (..)+ , none+ , epsilon+ , allChar+ , everything+ , charSet+ , range+ , literal+ , cat+ , union+ , inter+ , star+ , plus+ , opt+ , loop+ , power+ , complement+ , difference+ -- * Semantics+ , nullable+ , derivative+ , matches+ , charClasses+ -- * Automata+ , Dfa (..)+ , maxStates+ , toDfa+ , isEmpty+ , equivalent+ , minLength+ , maxLength+ , liveStates+ -- * Rendering+ , prettyRegex+ ) where++import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IntMap+import qualified Data.IntSet as IntSet+import Data.List (sortOn)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import Numeric (showHex)++-------------------------------------------------------------------------------+-- Character sets++-- | A set of code points: sorted, disjoint and non-adjacent inclusive+-- ranges.+type CharSet = [(Int, Int)]++-- | The largest code point of SMT-LIB strings.+maxChar :: Int+maxChar = 0x2FFFF++-- | Every code point.+fullSet :: CharSet+fullSet = [(0, maxChar)]++-- | Whether a code point belongs to a set.+memberSet :: Int -> CharSet -> Bool+memberSet c = any (\(lo, hi) -> lo <= c && c <= hi)++normalizeSet :: [(Int, Int)] -> CharSet+normalizeSet = merge . sortOn fst . filter (uncurry (<=)) . map clip+ where+ clip (lo, hi) = (max 0 lo, min maxChar hi)+ merge ((a, b) : (c, d) : rest)+ | c <= b + 1 = merge ((a, max b d) : rest)+ | otherwise = (a, b) : merge ((c, d) : rest)+ merge rs = rs++unionSet :: CharSet -> CharSet -> CharSet+unionSet a b = normalizeSet (a <> b)++interSet :: CharSet -> CharSet -> CharSet+interSet a b = normalizeSet [(max lo lo', min hi hi') | (lo, hi) <- a, (lo', hi') <- b]++complementSet :: CharSet -> CharSet+complementSet cs = normalizeSet (go 0 cs)+ where+ go next [] = [(next, maxChar)]+ go next ((lo, hi) : rest) = (next, lo - 1) : go (hi + 1) rest++-------------------------------------------------------------------------------+-- Expressions++-- | A regular expression in normal form. Build expressions with the smart+-- constructors, which keep the invariants documented on each constructor.+data Regex+ = RSet CharSet+ -- ^ One character of the set (the empty set is the empty language).+ | REps+ -- ^ The empty string.+ | RCat Regex Regex+ -- ^ Concatenation; neither part is empty, the empty string or a+ -- concatenation itself (concatenation is right-nested).+ | RAlt (Set Regex)+ -- ^ Union of at least two expressions, none a union itself or empty,+ -- with at most one character set.+ | RAnd (Set Regex)+ -- ^ Intersection of at least two expressions, none an intersection+ -- itself or the universal language.+ | RStar Regex+ -- ^ Kleene star of an expression that is not a star, the empty string+ -- or empty.+ | RNot Regex+ -- ^ Complement of an expression that is not a complement.+ deriving (Eq, Ord, Show)++-- | The empty language.+none :: Regex+none = RSet []++-- | The language of the empty string.+epsilon :: Regex+epsilon = REps++-- | Every string of one character.+allChar :: Regex+allChar = RSet fullSet++-- | Every string.+everything :: Regex+everything = RNot none++-- | One character of a set.+charSet :: [(Int, Int)] -> Regex+charSet = RSet . normalizeSet++-- | @re.range@: the characters between two one-character strings, or the+-- empty language when an argument is not a single character.+range :: Text -> Text -> Regex+range a b = case (T.unpack a, T.unpack b) of+ ([x], [y]) -> charSet [(fromEnum x, fromEnum y)]+ _ -> none++-- | @str.to_re@: the language of one string.+literal :: Text -> Regex+literal = foldr (\ch r -> cat (charSet [(fromEnum ch, fromEnum ch)]) r) REps . T.unpack++-- | Concatenation.+cat :: Regex -> Regex -> Regex+cat a b+ | a == none || b == none = none+ | otherwise = case (a, b) of+ (REps, _) -> b+ (_, REps) -> a+ (RCat x y, _) -> cat x (cat y b)+ _ -> RCat a b++-- | Union of a list (the empty language when empty).+union :: [Regex] -> Regex+union rs+ | everything `Set.member` members = everything+ | otherwise = case Set.toList (withSet members) of+ [] -> none+ [r] -> r+ _ -> RAlt (withSet members)+ where+ members = Set.fromList (filter (/= none) (concatMap flat rs))+ flat = \case+ RAlt xs -> Set.toList xs+ r -> [r]+ -- All character sets merged into one.+ withSet xs =+ let (sets, others) = Set.partition isSet xs+ merged = foldl' unionSet [] [cs | RSet cs <- Set.toList sets]+ in if null merged then others else Set.insert (RSet merged) others+ isSet = \case+ RSet _ -> True+ _ -> False++-- | Intersection of a list (every string when empty).+inter :: [Regex] -> Regex+inter rs+ | none `Set.member` members = none+ | otherwise = case Set.toList (withSet members) of+ [] -> everything+ [r] -> r+ _ -> RAnd (withSet members)+ where+ members = Set.fromList (filter (/= everything) (concatMap flat rs))+ flat = \case+ RAnd xs -> Set.toList xs+ r -> [r]+ withSet xs =+ let (sets, others) = Set.partition isSet xs+ in case [cs | RSet cs <- Set.toList sets] of+ [] -> others+ css -> case foldl1 interSet css of+ [] -> Set.singleton none+ cs -> Set.insert (RSet cs) others+ isSet = \case+ RSet _ -> True+ _ -> False++-- | Kleene star.+star :: Regex -> Regex+star = \case+ r@(RStar _) -> r+ REps -> REps+ RSet [] -> REps+ RSet cs | cs == fullSet -> everything+ r -> RStar r++-- | One or more repetitions.+plus :: Regex -> Regex+plus r = cat r (star r)++-- | Zero or one occurrence.+opt :: Regex -> Regex+opt r = union [REps, r]++-- | @(_ re.loop i j)@: between @i@ and @j@ repetitions (the empty language+-- when @j < i@).+loop :: Int -> Int -> Regex -> Regex+loop i j r+ | j < i = none+ | otherwise = foldr cat optional (replicate i r)+ where+ optional = foldr (\_ acc -> opt (cat r acc)) REps [1 .. j - i]++-- | @(_ re.^ n)@: exactly @n@ repetitions.+power :: Int -> Regex -> Regex+power n = loop n n++-- | Complement.+complement :: Regex -> Regex+complement = \case+ RNot r -> r+ r -> RNot r++-- | @re.diff@: the strings of the first language not in the second.+difference :: Regex -> Regex -> Regex+difference a b = inter [a, complement b]++-------------------------------------------------------------------------------+-- Semantics++-- | Whether the language contains the empty string.+nullable :: Regex -> Bool+nullable = \case+ RSet _ -> False+ REps -> True+ RCat a b -> nullable a && nullable b+ RAlt xs -> any nullable xs+ RAnd xs -> all nullable xs+ RStar _ -> True+ RNot r -> not (nullable r)++-- | The Brzozowski derivative by a code point: the strings @w@ such that+-- @c w@ is in the language.+derivative :: Int -> Regex -> Regex+derivative c = \case+ RSet cs -> if memberSet c cs then REps else none+ REps -> none+ RCat a b ->+ let first = cat (derivative c a) b+ in if nullable a then union [first, derivative c b] else first+ RAlt xs -> union (map (derivative c) (Set.toList xs))+ RAnd xs -> inter (map (derivative c) (Set.toList xs))+ r@(RStar a) -> cat (derivative c a) r+ RNot a -> complement (derivative c a)++-- | Whether a string belongs to the language.+matches :: Regex -> Text -> Bool+matches r = nullable . T.foldl' (\acc ch -> derivative (fromEnum ch) acc) r++-- | A partition of the alphabet into classes of code points whose+-- derivatives are equal.+charClasses :: Regex -> [CharSet]+charClasses = \case+ RSet cs -> filter (not . null) [cs, complementSet cs]+ REps -> [fullSet]+ RCat a b+ | nullable a -> meet (charClasses a) (charClasses b)+ | otherwise -> charClasses a+ RAlt xs -> foldl' meet [fullSet] (map charClasses (Set.toList xs))+ RAnd xs -> foldl' meet [fullSet] (map charClasses (Set.toList xs))+ RStar a -> charClasses a+ RNot a -> charClasses a+ where+ meet p q = [s | x <- p, y <- q, let s = interSet x y, not (null s)]++-------------------------------------------------------------------------------+-- Automata++-- | A deterministic automaton. States are @0 .. n-1@ and @0@ is the initial+-- state; the transitions of each state are labelled with disjoint+-- character sets that cover the alphabet.+data Dfa = Dfa+ { dfaStates :: !Int+ , dfaDelta :: !(IntMap [(CharSet, Int)])+ , dfaAccepting :: !IntSet.IntSet+ }+ deriving (Show)++-- | The largest automaton 'toDfa' builds.+maxStates :: Int+maxStates = 2000++-- | The automaton of the derivatives of an expression, or 'Nothing' when it+-- has more than 'maxStates' states.+toDfa :: Regex -> Maybe Dfa+toDfa r0 = go (Map.singleton r0 0) [r0] IntMap.empty+ where+ go known [] delta =+ let accepting = IntSet.fromList [i | (r, i) <- Map.toList known, nullable r]+ in Just (Dfa (Map.size known) delta accepting)+ go known (r : todo) delta+ | Map.size known > maxStates = Nothing+ | otherwise =+ let i = known Map.! r+ step (k, new, edges) cls =+ let d = derivative (representative cls) r+ in case Map.lookup d k of+ Just j -> (k, new, (cls, j) : edges)+ Nothing ->+ let j = Map.size k+ in (Map.insert d j k, d : new, (cls, j) : edges)+ (known', new', edges') = foldl' step (known, [], []) (charClasses r)+ in go known' (todo <> reverse new') (IntMap.insert i (mergeEdges edges') delta)+ representative = \case+ (lo, _) : _ -> lo+ [] -> 0+ -- One transition per target state.+ mergeEdges edges =+ [(cs, j) | (j, cs) <- Map.toList (Map.fromListWith unionSet [(j, cs) | (cs, j) <- edges])]++-- | States from which an accepting state can be reached.+liveStates :: Dfa -> IntSet.IntSet+liveStates dfa = fixpoint (dfaAccepting dfa)+ where+ fixpoint live =+ let live' =+ IntSet.union live $+ IntSet.fromList+ [i | (i, edges) <- IntMap.toList (dfaDelta dfa), any ((`IntSet.member` live) . snd) edges]+ in if live' == live then live else fixpoint live'++-- | Whether the language is empty ('Nothing' when the automaton is too+-- large).+isEmpty :: Regex -> Maybe Bool+isEmpty r = IntSet.null . dfaAccepting <$> toDfa r++-- | Whether two expressions denote the same language ('Nothing' when the+-- automaton of their symmetric difference is too large).+equivalent :: Regex -> Regex -> Maybe Bool+equivalent a b+ | a == b = Just True+ | otherwise = isEmpty (union [difference a b, difference b a])++-- | Length of the shortest string of the language, if it is not empty.+minLength :: Dfa -> Maybe Int+minLength dfa = bfs (IntSet.singleton 0) [0] 0+ where+ bfs seen frontier d+ | null frontier = Nothing+ | any (`IntSet.member` dfaAccepting dfa) frontier = Just d+ | otherwise =+ let next = IntSet.toList (IntSet.fromList [j | i <- frontier, (_, j) <- edgesOf i, not (IntSet.member j seen)])+ in bfs (IntSet.union seen (IntSet.fromList next)) next (d + 1)+ edgesOf i = fromMaybe [] (IntMap.lookup i (dfaDelta dfa))++-- | Length of the longest string of the language, when the language is+-- finite and not empty.+maxLength :: Dfa -> Maybe Int+maxLength dfa+ | not (IntSet.member 0 live) = Nothing+ | otherwise = longest IntMap.empty [] 0 >>= \(_, l) -> l+ where+ live = liveStates dfa+ edgesOf i = [j | (_, j) <- fromMaybe [] (IntMap.lookup i (dfaDelta dfa)), IntSet.member j live]+ -- Longest path to an accepting state from each live state, by depth-first+ -- search; a cycle through live states makes the language infinite.+ longest memo path i+ | i `elem` path = Nothing+ | Just l <- IntMap.lookup i memo = Just (memo, Just l)+ | otherwise = do+ (memo', ls) <- foldlM (\(m, acc) j -> fmap (\(m', l) -> (m', l : acc)) (longest m (i : path) j)) (memo, []) (edgesOf i)+ let here = if IntSet.member i (dfaAccepting dfa) then Just 0 else Nothing+ best = maximumMaybe (here : [(+ 1) <$> l | l <- ls])+ pure (maybe memo' (\b -> IntMap.insert i b memo') best, best)+ maximumMaybe xs = case [x | Just x <- xs] of+ [] -> Nothing+ ys -> Just (maximum ys)+ foldlM f z = \case+ [] -> Just z+ (y : ys) -> f z y >>= \z' -> foldlM f z' ys++-------------------------------------------------------------------------------+-- Rendering++-- | The expression in SMT-LIB syntax.+prettyRegex :: Regex -> Text+prettyRegex = \case+ RSet [] -> "re.none"+ RSet cs+ | cs == fullSet -> "re.allchar"+ | otherwise -> case map rangeText cs of+ [t] -> t+ ts -> app "re.union" ts+ REps -> app "str.to_re" ["\"\""]+ RCat a b -> app "re.++" [prettyRegex a, prettyRegex b]+ RAlt xs -> app "re.union" (map prettyRegex (Set.toList xs))+ RAnd xs -> app "re.inter" (map prettyRegex (Set.toList xs))+ RStar r -> app "re.*" [prettyRegex r]+ RNot (RSet []) -> "re.all"+ RNot r -> app "re.comp" [prettyRegex r]+ where+ app f args = "(" <> T.unwords (f : args) <> ")"+ rangeText (lo, hi)+ | lo == hi = app "str.to_re" [charLit lo]+ | otherwise = app "re.range" [charLit lo, charLit hi]+ charLit c+ | c >= 32 && c < 127 && c /= 34 && c /= 92 = T.pack ['"', toEnum c, '"']+ | otherwise = "\"\\u{" <> T.pack (showHex c "") <> "}\""
+ src/HSMT/Core/Sort.hs view
@@ -0,0 +1,68 @@+-- | Run-time representation of sorts used by the untyped core.+module HSMT.Core.Sort+ ( Sort (..)+ , prettySort+ , finiteCardinality+ ) where++import Data.Text (Text)+import qualified Data.Text as T++-- | Sorts of the core language.+data Sort+ = BoolSort+ | IntSort+ | StringSort+ | BVSort !Int+ -- ^ Fixed-width bit-vectors; the width is always positive.+ | ArraySort Sort Sort+ -- ^ @ArraySort index element@.+ | RecordSort [(Text, Sort)]+ -- ^ Records with named fields, in declaration order.+ | UninterpretedSort Text+ -- ^ User-declared uninterpreted sort.+ | FPSort !Int !Int+ -- ^ Floating-point numbers with the given exponent and significand+ -- widths (the significand width counts the hidden bit); both are at+ -- least 2.+ | RoundingModeSort+ | RegLanSort+ -- ^ Regular languages (SMT-LIB @RegLan@).+ deriving (Eq, Ord, Show)++-- | Render a sort using SMT-LIB 2 syntax. Records have no native SMT-LIB+-- syntax, so they are rendered as a quoted symbol describing their fields.+prettySort :: Sort -> Text+prettySort = \case+ BoolSort -> "Bool"+ IntSort -> "Int"+ StringSort -> "String"+ BVSort n -> "(_ BitVec " <> tshow n <> ")"+ ArraySort i e -> "(Array " <> prettySort i <> " " <> prettySort e <> ")"+ RecordSort fs ->+ "|Record{" <> T.intercalate "," [f <> ":" <> prettySort s | (f, s) <- fs] <> "}|"+ UninterpretedSort n -> n+ FPSort eb sb -> "(_ FloatingPoint " <> tshow eb <> " " <> tshow sb <> ")"+ RoundingModeSort -> "RoundingMode"+ RegLanSort -> "RegLan"+ where+ tshow = T.pack . show++-- | Number of elements of a sort, when it is finite.+--+-- Uninterpreted sorts are treated as infinite: the solver never assumes a+-- bound on their size.+finiteCardinality :: Sort -> Maybe Integer+finiteCardinality = \case+ BoolSort -> Just 2+ BVSort n -> Just (2 ^ n)+ -- Every NaN pattern stands for the single NaN.+ FPSort eb sb -> Just (2 ^ (eb + sb) - 2 * (2 ^ (sb - 1) - 1) + 1)+ RoundingModeSort -> Just 5+ RecordSort fs -> product <$> traverse (finiteCardinality . snd) fs+ ArraySort i e -> do+ ci <- finiteCardinality i+ ce <- finiteCardinality e+ -- Guard against astronomically large exponents.+ if ci <= 64 then Just (ce ^ ci) else Nothing+ _ -> Nothing
+ src/HSMT/Core/Term.hs view
@@ -0,0 +1,117 @@+-- | Hash-consed term DAG.+--+-- Interning maps structurally equal expressions to the same t'TermId', so+-- that decision procedures can compare terms in constant time and share+-- work between occurrences of the same sub-term.+module HSMT.Core.Term+ ( TermId (..)+ , TermNode (..)+ , TermStore+ , emptyStore+ , storeSize+ , intern+ , internNode+ , lookupNode+ , termSort+ , termOp+ , termArgs+ , toExpr+ ) where++import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IntMap+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map++import HSMT.Core.Expr+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Typing++-- | Identifier of an interned term, valid only in the t'TermStore' that+-- created it.+newtype TermId = TermId {unTermId :: Int}+ deriving (Eq, Ord, Show)++-- | A node of the DAG: an operator applied to interned arguments.+data TermNode = TermNode+ { nodeOp :: !Op+ -- ^ The operator.+ , nodeArgs :: ![TermId]+ -- ^ The arguments, in order.+ , nodeSort :: !Sort+ -- ^ The sort of the term, inferred when it was interned.+ }+ deriving (Eq, Show)++-- | The hash-consing table: the nodes indexed by t'TermId' and the reverse+-- index from structure to identifier.+data TermStore = TermStore+ { tsNodes :: !(IntMap TermNode)+ , tsIndex :: !(Map (Op, [TermId]) TermId)+ , tsNext :: !Int+ }++-- | A store with no terms.+emptyStore :: TermStore+emptyStore = TermStore IntMap.empty Map.empty 0++-- | Number of distinct terms in the store.+storeSize :: TermStore -> Int+storeSize = tsNext++-- | Intern an expression, sort-checking every new node.+intern :: Expr -> TermStore -> Either SortError (TermId, TermStore)+intern (App op args) st0 = do+ (ids, st1) <- internAll args st0+ internNode op ids st1+ where+ internAll [] st = Right ([], st)+ internAll (e : es) st = do+ (i, st') <- intern e st+ (is, st'') <- internAll es st'+ pure (i : is, st'')++-- | Intern an operator applied to already interned arguments.+internNode :: Op -> [TermId] -> TermStore -> Either SortError (TermId, TermStore)+internNode op ids st =+ case Map.lookup (op, ids) (tsIndex st) of+ Just tid -> Right (tid, st)+ Nothing -> do+ s <- inferSort op (map (termSort st) ids)+ let tid = TermId (tsNext st)+ node = TermNode op ids s+ Right+ ( tid+ , st+ { tsNodes = IntMap.insert (unTermId tid) node (tsNodes st)+ , tsIndex = Map.insert (op, ids) tid (tsIndex st)+ , tsNext = tsNext st + 1+ }+ )++-- | The node of a term. Calls 'error' if the identifier is not in the store.+lookupNode :: TermStore -> TermId -> TermNode+lookupNode st (TermId i) =+ case IntMap.lookup i (tsNodes st) of+ Just n -> n+ Nothing -> error ("HSMT.Core.Term.lookupNode: unknown term " <> show i)++-- | The sort of a term.+termSort :: TermStore -> TermId -> Sort+termSort st = nodeSort . lookupNode st++-- | The operator at the root of a term.+termOp :: TermStore -> TermId -> Op+termOp st = nodeOp . lookupNode st++-- | The arguments of a term.+termArgs :: TermStore -> TermId -> [TermId]+termArgs st = nodeArgs . lookupNode st++-- | Expand a term back into a tree. This can be exponentially larger than+-- the DAG and is meant for debugging and printing small terms.+toExpr :: TermStore -> TermId -> Expr+toExpr st tid =+ let TermNode op args _ = lookupNode st tid+ in App op (map (toExpr st) args)
+ src/HSMT/Core/Typing.hs view
@@ -0,0 +1,259 @@+-- | Dynamic sort checking for the core language.+--+-- The typed API produces only well-sorted expressions, but front-ends such as+-- the SMT-LIB parser and the dynamic API rely on this module to reject+-- ill-sorted input.+module HSMT.Core.Typing+ ( SortError (..)+ , inferSort+ , sortOf+ ) where++import Control.Monad (unless, when)+import Data.List (nub)+import Data.Text (Text)+import qualified Data.Text as T++import HSMT.Core.Expr+import HSMT.Core.Op+import HSMT.Core.Sort++-- | A sort error, with the offending operator and argument sorts.+data SortError = SortError+ { seOp :: Op+ , seArgs :: [Sort]+ , seMessage :: Text+ }+ deriving (Eq, Show)++-- | Sort of an expression, checking every sub-expression.+sortOf :: Expr -> Either SortError Sort+sortOf (App op args) = traverse sortOf args >>= inferSort op++-- | Result sort of an operator applied to arguments of the given sorts.+inferSort :: Op -> [Sort] -> Either SortError Sort+inferSort op ss = case op of+ Uninterpreted sym -> do+ unless (ss == symArgs sym) $ bad "argument sorts do not match the declaration"+ pure (symResult sym)+ BoolConst _ -> nullary BoolSort+ Not -> exactly [BoolSort] BoolSort+ And -> allOf BoolSort 0 BoolSort+ Or -> allOf BoolSort 0 BoolSort+ Xor -> allOf BoolSort 2 BoolSort+ Implies -> allOf BoolSort 2 BoolSort+ Ite -> case ss of+ [BoolSort, a, b] | a == b -> pure a+ _ -> bad "expected (ite Bool s s)"+ Eq -> sameSorts 2 >> pure BoolSort+ Distinct -> sameSorts 2 >> pure BoolSort+ IntConst _ -> nullary IntSort+ Add -> allOf IntSort 2 IntSort+ Sub -> allOf IntSort 2 IntSort+ Neg -> exactly [IntSort] IntSort+ Mul -> allOf IntSort 2 IntSort+ IntDiv -> exactly [IntSort, IntSort] IntSort+ IntMod -> exactly [IntSort, IntSort] IntSort+ Abs -> exactly [IntSort] IntSort+ Le -> allOf IntSort 2 BoolSort+ Lt -> allOf IntSort 2 BoolSort+ Ge -> allOf IntSort 2 BoolSort+ Gt -> allOf IntSort 2 BoolSort+ BVConst w v -> do+ when (w <= 0) $ bad "bit-vector width must be positive"+ when (v < 0 || v >= 2 ^ w) $ bad "bit-vector literal out of range"+ nullary (BVSort w)+ BVNot -> bvUnary+ BVNeg -> bvUnary+ BVAnd -> bvNary+ BVOr -> bvNary+ BVXor -> bvNary+ BVAdd -> bvNary+ BVMul -> bvNary+ BVSub -> bvBinary+ BVUDiv -> bvBinary+ BVURem -> bvBinary+ BVSDiv -> bvBinary+ BVSRem -> bvBinary+ BVSMod -> bvBinary+ BVShl -> bvBinary+ BVLShr -> bvBinary+ BVAShr -> bvBinary+ BVConcat -> do+ ws <- traverse width ss+ when (length ws < 2) $ bad "concat expects at least two arguments"+ pure (BVSort (sum ws))+ BVExtract h l -> case ss of+ [BVSort w] | 0 <= l && l <= h && h < w -> pure (BVSort (h - l + 1))+ _ -> bad "invalid extract indices"+ BVZeroExtend k -> extendBy k+ BVSignExtend k -> extendBy k+ BVULt -> bvPred+ BVULe -> bvPred+ BVUGt -> bvPred+ BVUGe -> bvPred+ BVSLt -> bvPred+ BVSLe -> bvPred+ BVSGt -> bvPred+ BVSGe -> bvPred+ Select -> case ss of+ [ArraySort i e, i'] | i == i' -> pure e+ _ -> bad "expected (select (Array i e) i)"+ Store -> case ss of+ [ArraySort i e, i', e'] | i == i' && e == e' -> pure (ArraySort i e)+ _ -> bad "expected (store (Array i e) i e)"+ ConstArray i -> case ss of+ [e] -> pure (ArraySort i e)+ _ -> bad "const array expects one argument"+ StrConst _ -> nullary StringSort+ StrConcat -> allOf StringSort 2 StringSort+ StrLen -> exactly [StringSort] IntSort+ StrAt -> exactly [StringSort, IntSort] StringSort+ StrSubstr -> exactly [StringSort, IntSort, IntSort] StringSort+ StrContains -> exactly [StringSort, StringSort] BoolSort+ StrPrefixOf -> exactly [StringSort, StringSort] BoolSort+ StrSuffixOf -> exactly [StringSort, StringSort] BoolSort+ StrIndexOf -> exactly [StringSort, StringSort, IntSort] IntSort+ StrReplace -> exactly [StringSort, StringSort, StringSort] StringSort+ StrToInt -> exactly [StringSort] IntSort+ StrFromInt -> exactly [IntSort] StringSort+ StrLt -> exactly [StringSort, StringSort] BoolSort+ StrLe -> exactly [StringSort, StringSort] BoolSort+ StrToRe -> exactly [StringSort] RegLanSort+ StrInRe -> exactly [StringSort, RegLanSort] BoolSort+ ReNone -> nullary RegLanSort+ ReAll -> nullary RegLanSort+ ReAllChar -> nullary RegLanSort+ ReConcat -> allOf RegLanSort 2 RegLanSort+ ReUnion -> allOf RegLanSort 2 RegLanSort+ ReInter -> allOf RegLanSort 2 RegLanSort+ ReStar -> exactly [RegLanSort] RegLanSort+ RePlus -> exactly [RegLanSort] RegLanSort+ ReOpt -> exactly [RegLanSort] RegLanSort+ ReRange -> exactly [StringSort, StringSort] RegLanSort+ ReComp -> exactly [RegLanSort] RegLanSort+ ReDiff -> allOf RegLanSort 2 RegLanSort+ ReLoop i j -> do+ when (i < 0 || j < 0) $ bad "negative repetition count"+ exactly [RegLanSort] RegLanSort+ RePower n -> do+ when (n < 0) $ bad "negative repetition count"+ exactly [RegLanSort] RegLanSort+ RecordMk names -> do+ unless (length names == length ss) $ bad "wrong number of record fields"+ unless (length (nub names) == length names) $ bad "duplicated record field"+ pure (RecordSort (zip names ss))+ RecordGet f -> case ss of+ [RecordSort fs] | Just s <- lookup f fs -> pure s+ _ -> bad ("no field " <> f)+ RecordSet f -> case ss of+ [r@(RecordSort fs), s] | lookup f fs == Just s -> pure r+ _ -> bad ("cannot update field " <> f)+ FPConst eb sb x -> do+ format eb sb+ when (x < 0 || x >= 2 ^ (eb + sb)) $ bad "floating-point pattern out of range"+ nullary (FPSort eb sb)+ RMConst _ -> nullary RoundingModeSort+ FPFromFields -> case ss of+ [BVSort 1, BVSort eb, BVSort f] | eb >= 2 && f >= 1 -> pure (FPSort eb (f + 1))+ _ -> bad "expected (fp (_ BitVec 1) (_ BitVec eb) (_ BitVec sb-1))"+ FPAbs -> fpUnary+ FPNeg -> fpUnary+ FPAdd -> rmThen 2+ FPSub -> rmThen 2+ FPMul -> rmThen 2+ FPDiv -> rmThen 2+ FPFma -> rmThen 3+ FPSqrt -> rmThen 1+ FPRoundToIntegral -> rmThen 1+ FPRem -> fpSame 2 2+ FPMin -> fpSame 2 2+ FPMax -> fpSame 2 2+ FPLeq -> fpSame 2 maxBound >> pure BoolSort+ FPLt -> fpSame 2 maxBound >> pure BoolSort+ FPGeq -> fpSame 2 maxBound >> pure BoolSort+ FPGt -> fpSame 2 maxBound >> pure BoolSort+ FPEq -> fpSame 2 maxBound >> pure BoolSort+ FPIsNormal -> fpPred+ FPIsSubnormal -> fpPred+ FPIsZero -> fpPred+ FPIsInfinite -> fpPred+ FPIsNaN -> fpPred+ FPIsNegative -> fpPred+ FPIsPositive -> fpPred+ ToFP eb sb -> do+ format eb sb+ case ss of+ [BVSort w] | w == eb + sb -> pure (FPSort eb sb)+ [RoundingModeSort, FPSort _ _] -> pure (FPSort eb sb)+ [RoundingModeSort, BVSort _] -> pure (FPSort eb sb)+ _ -> bad "expected a bit-vector of the format's width, or a rounding mode and a floating-point number or bit-vector"+ ToFPUnsigned eb sb -> do+ format eb sb+ case ss of+ [RoundingModeSort, BVSort _] -> pure (FPSort eb sb)+ _ -> bad "expected a rounding mode and a bit-vector"+ FPToUBV w -> toBV w+ FPToSBV w -> toBV w+ where+ bad :: Text -> Either SortError a+ bad msg = Left (SortError op ss msg)++ nullary s = exactly [] s++ exactly expected result+ | ss == expected = pure result+ | otherwise =+ bad ("expected arguments " <> T.intercalate ", " (map prettySort expected))++ allOf s minArgs result = do+ when (length ss < minArgs) $ bad "too few arguments"+ unless (all (== s) ss) $ bad ("all arguments must have sort " <> prettySort s)+ pure result++ sameSorts minArgs = case ss of+ (s : rest) | length ss >= minArgs && all (== s) rest -> pure ()+ _ -> bad "arguments must have the same sort"++ width = \case+ BVSort w -> pure w+ _ -> bad "expected a bit-vector argument"++ bvUnary = case ss of+ [s@(BVSort _)] -> pure s+ _ -> bad "expected one bit-vector argument"++ bvBinary = case ss of+ [s@(BVSort _), s'] | s == s' -> pure s+ _ -> bad "expected two bit-vectors of the same width"++ bvNary = case ss of+ (s@(BVSort _) : rest) | not (null rest) && all (== s) rest -> pure s+ _ -> bad "expected bit-vectors of the same width"++ bvPred = bvBinary >> pure BoolSort++ format eb sb = unless (eb >= 2 && sb >= 2) $ bad "floating-point widths must be at least 2"++ fpUnary = case ss of+ [s@(FPSort _ _)] -> pure s+ _ -> bad "expected one floating-point argument"++ fpSame :: Int -> Int -> Either SortError Sort+ fpSame lo hi = case ss of+ (s@(FPSort _ _) : rest) | all (== s) rest && length ss >= lo && length ss <= hi -> pure s+ _ -> bad "expected floating-point arguments of the same format"++ rmThen n = case ss of+ (RoundingModeSort : s@(FPSort _ _) : rest) | length rest == n - 1 && all (== s) rest -> pure s+ _ -> bad "expected a rounding mode and floating-point arguments of the same format"++ fpPred = fpUnary >> pure BoolSort++ toBV w = case ss of+ [RoundingModeSort, FPSort _ _] | w >= 1 -> pure (BVSort w)+ _ -> bad "expected a rounding mode and a floating-point argument"++ extendBy k = case ss of+ [BVSort w] | k >= 0 -> pure (BVSort (w + k))+ _ -> bad "invalid extension"
+ src/HSMT/Core/Value.hs view
@@ -0,0 +1,198 @@+-- | Concrete values of the core language, used in models.+module HSMT.Core.Value+ ( Value (..)+ , mkArray+ , arraySelect+ , arrayStore+ , defaultValue+ , valueSortMatches+ , prettyValue+ -- * Bit-vector helpers+ , bvMask+ , bvNormalize+ , bvToSigned+ , bvFromSigned+ ) where++import Data.Bits (shiftL)+import Data.List (sortOn)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as T++import HSMT.Core.Float (FP (..), RoundingMode, canonicalNaN, decode, isNaNBits, rmName)+import HSMT.Core.Regex (Regex, prettyRegex)+import qualified HSMT.Core.Regex as R+import HSMT.Core.Sort++-- | A concrete value.+--+-- Array values are kept in a canonical form (see 'mkArray'), so the derived+-- 'Eq' instance coincides with extensional equality.+data Value+ = VBool !Bool+ | VInt !Integer+ | VString !Text+ | VBV !Int !Integer+ -- ^ Width and unsigned value.+ | VArray !Sort !(Map Value Value) !Value+ -- ^ Index sort, explicit entries and default element.+ | VRecord ![(Text, Value)]+ | VUninterp !Sort !Int+ -- ^ The @n@-th abstract element of an uninterpreted sort.+ | VFP !Int !Int !Integer+ -- ^ Format and bit pattern; NaN is always the canonical pattern.+ | VRM !RoundingMode+ | VRegLan !Regex+ -- ^ A regular language. 'Eq' compares expressions, not languages (see+ -- 'HSMT.Core.Regex.equivalent').+ deriving (Eq, Ord, Show)++-- | Build an array value in canonical form.+--+-- For infinite index sorts the default is observable, so the canonical form+-- simply drops entries equal to the default. For finite index sorts every+-- entry may be overridden; in that case the default is chosen as the least+-- element of the array's image, making the representation unique.+mkArray :: Sort -> Map Value Value -> Value -> Value+mkArray idx entries def =+ case finiteCardinality idx of+ Nothing -> canon def entries+ Just card+ | fromIntegral (Map.size entries) >= card ->+ canon (minimum (Map.elems entries)) entries+ | Just keys <- enumerateSort idx ->+ let full = Map.union entries (Map.fromList [(k, def) | k <- keys])+ in canon (minimum (Map.elems full)) full+ -- Domains too large to enumerate cannot have every key overridden in+ -- practice, so the default is observable and already canonical.+ | otherwise -> canon def entries+ where+ canon d es = VArray idx (Map.filter (/= d) es) d++-- | Enumerate the elements of a small finite sort.+enumerateSort :: Sort -> Maybe [Value]+enumerateSort s = case finiteCardinality s of+ Just n | n <= 4096 -> go s+ _ -> Nothing+ where+ go = \case+ BoolSort -> Just [VBool False, VBool True]+ BVSort w -> Just [VBV w v | v <- [0 .. bvMask w]]+ FPSort eb sb ->+ Just+ [ VFP eb sb v+ | v <- [0 .. bvMask (eb + sb)]+ , not (isNaNBits eb sb v) || v == canonicalNaN eb sb+ ]+ RoundingModeSort -> Just (map VRM [minBound .. maxBound])+ RecordSort fs -> do+ vss <- traverse (go . snd) fs+ pure [VRecord (zip (map fst fs) vs) | vs <- sequence vss]+ ArraySort i e -> do+ is <- go i+ es <- go e+ case es of+ [] -> Nothing+ (e0 : _) -> pure [mkArray i (Map.fromList (zip is es')) e0 | es' <- mapM (const es) is]+ _ -> Nothing++-- | Read an array value at an index. The first argument must be a 'VArray'.+arraySelect :: Value -> Value -> Value+arraySelect (VArray _ entries def) i = Map.findWithDefault def i entries+arraySelect v _ = error ("arraySelect: not an array: " <> show v)++-- | Update an array value at an index, keeping the canonical form. The+-- first argument must be a 'VArray'.+arrayStore :: Value -> Value -> Value -> Value+arrayStore (VArray idx entries def) i e = mkArray idx (Map.insert i e entries) def+arrayStore v _ _ = error ("arrayStore: not an array: " <> show v)++-- | The value used to complete models for symbols the solver did not need to+-- constrain.+defaultValue :: Sort -> Value+defaultValue = \case+ BoolSort -> VBool False+ IntSort -> VInt 0+ StringSort -> VString ""+ BVSort w -> VBV w 0+ ArraySort i e -> mkArray i Map.empty (defaultValue e)+ RecordSort fs -> VRecord [(f, defaultValue s) | (f, s) <- fs]+ s@(UninterpretedSort _) -> VUninterp s 0+ FPSort eb sb -> VFP eb sb 0+ RoundingModeSort -> VRM minBound+ RegLanSort -> VRegLan R.none++-- | Check whether a value inhabits a sort.+valueSortMatches :: Sort -> Value -> Bool+valueSortMatches s v = case (s, v) of+ (BoolSort, VBool _) -> True+ (IntSort, VInt _) -> True+ (StringSort, VString _) -> True+ (BVSort w, VBV w' x) -> w == w' && 0 <= x && x <= bvMask w+ (ArraySort i e, VArray i' entries def) ->+ i == i'+ && valueSortMatches e def+ && all (valueSortMatches i) (Map.keys entries)+ && all (valueSortMatches e) (Map.elems entries)+ (RecordSort fs, VRecord vs) ->+ map fst fs == map fst vs && and (zipWith valueSortMatches (map snd fs) (map snd vs))+ (UninterpretedSort _, VUninterp s' _) -> s == s'+ (FPSort eb sb, VFP eb' sb' x) ->+ eb == eb' && sb == sb' && 0 <= x && x <= bvMask (eb + sb)+ && (not (isNaNBits eb sb x) || x == canonicalNaN eb sb)+ (RoundingModeSort, VRM _) -> True+ (RegLanSort, VRegLan _) -> True+ _ -> False++-- | Render a value as an SMT-LIB term.+prettyValue :: Value -> Text+prettyValue = \case+ VBool b -> if b then "true" else "false"+ VInt n+ | n < 0 -> "(- " <> tshow (negate n) <> ")"+ | otherwise -> tshow n+ VString s -> "\"" <> T.replace "\"" "\"\"" s <> "\""+ VBV w x -> "#b" <> T.pack [if odd (x `div` (2 ^ i)) then '1' else '0' | i <- [w - 1, w - 2 .. 0]]+ VArray idx entries def ->+ let base = "((as const (Array " <> prettySort idx <> " " <> "_)) " <> prettyValue def <> ")"+ in foldl+ (\acc (k, e) -> "(store " <> acc <> " " <> prettyValue k <> " " <> prettyValue e <> ")")+ base+ (sortOn fst (Map.toList entries))+ VRecord fs -> "(record " <> T.unwords [f <> "=" <> prettyValue v | (f, v) <- fs] <> ")"+ VUninterp s n -> "(as @" <> prettySort s <> "_" <> tshow n <> ")"+ VFP eb sb x -> case decode eb sb x of+ NaN -> "(_ NaN " <> tshow eb <> " " <> tshow sb <> ")"+ Inf neg -> "(_ " <> (if neg then "-" else "+") <> "oo " <> tshow eb <> " " <> tshow sb <> ")"+ Zero neg -> "(_ " <> (if neg then "-" else "+") <> "zero " <> tshow eb <> " " <> tshow sb <> ")"+ Finite {} ->+ "(fp " <> binary 1 (x `div` 2 ^ (eb + sb - 1)) <> " "+ <> binary eb ((x `div` 2 ^ (sb - 1)) `mod` 2 ^ eb) <> " "+ <> binary (sb - 1) (x `mod` 2 ^ (sb - 1)) <> ")"+ VRM rm -> rmName rm+ VRegLan r -> prettyRegex r+ where+ binary w v = prettyValue (VBV w v)+ tshow :: Show a => a -> Text+ tshow = T.pack . show++-- | Largest unsigned value of the given width.+bvMask :: Int -> Integer+bvMask w = (1 `shiftL` w) - 1++-- | Reduce an integer modulo @2^w@.+bvNormalize :: Int -> Integer -> Integer+bvNormalize w x = x `mod` (1 `shiftL` w)++-- | Two's complement interpretation of an unsigned value.+bvToSigned :: Int -> Integer -> Integer+bvToSigned w x+ | x >= 1 `shiftL` (w - 1) = x - (1 `shiftL` w)+ | otherwise = x++-- | Unsigned value of the given width representing a (two's complement)+-- signed integer; inverse of 'bvToSigned'.+bvFromSigned :: Int -> Integer -> Integer+bvFromSigned = bvNormalize
+ src/HSMT/SAT/Dimacs.hs view
@@ -0,0 +1,56 @@+-- | Reading CNF formulas in DIMACS format.+module HSMT.SAT.Dimacs+ ( Cnf (..)+ , parseDimacs+ , loadCnf+ ) where++import Control.Monad (forM_, replicateM_)+import qualified Data.Text as T++import HSMT.SAT.Solver+import HSMT.SAT.Types++-- | A CNF formula as read from a DIMACS file.+data Cnf = Cnf+ { cnfVars :: !Int+ -- ^ Number of variables declared in the @p cnf@ header.+ , cnfClauses :: [[Int]]+ -- ^ Clauses using DIMACS numbering (non-zero, sign is polarity).+ }+ deriving (Eq, Show)++-- | Parse DIMACS CNF text. Comment lines (starting with @c@ or @%@) are+-- skipped; the clause count in the header is not checked.+parseDimacs :: T.Text -> Either String Cnf+parseDimacs txt = do+ let ls = filter (not . skip) (map T.strip (T.lines txt))+ skip l = T.null l || T.head l == 'c' || T.head l == '%'+ case ls of+ (hdr : body) -> case T.words hdr of+ ["p", "cnf", nv, _] -> do+ n <- readInt nv+ lits <- mapM readInt (concatMap T.words body)+ pure (Cnf n (splitZero lits))+ _ -> Left "missing 'p cnf' header"+ [] -> Left "empty input"+ where+ readInt t = case reads (T.unpack t) of+ [(n, "")] -> Right n+ _ -> Left ("not an integer: " <> T.unpack t)+ splitZero xs = case break (== 0) xs of+ ([], []) -> []+ (c, []) -> [c]+ (c, _ : rest) -> c : splitZero rest++-- | Load a CNF into a fresh solver. Returns 'False' if it is trivially+-- unsatisfiable.+loadCnf :: Solver -> Cnf -> IO Bool+loadCnf s (Cnf n clauses) = do+ existing <- numVars s+ replicateM_ (max 0 (maxVar - existing)) (newVar s)+ forM_ clauses $ \c -> addClause s (map toLit c)+ isOkay s+ where+ maxVar = maximum (n : [abs l | c <- clauses, l <- c])+ toLit l = mkLit (abs l - 1) (l < 0)
+ src/HSMT/SAT/Solver.hs view
@@ -0,0 +1,919 @@+{-# LANGUAGE BangPatterns #-}++-- | A CDCL SAT solver with support for theory solvers (DPLL(T)).+--+-- Features: two watched literals, first-UIP clause learning with local+-- clause minimization, VSIDS branching with phase saving, Luby restarts,+-- LBD-based deletion of learnt clauses, incremental solving under+-- assumptions with failed-assumption extraction, and clause addition from+-- theories during search.+module HSMT.SAT.Solver+ ( Solver+ , newSolver+ , newVar+ , setPhase+ , numVars+ , addClause+ , solve+ , solveWith+ , SolveOptions (..)+ , defaultSolveOptions+ , modelValue+ , getModel+ , litValueNow+ , failedAssumptions+ , deliveredLits+ , setTheory+ , isOkay+ , decisionLevel+ , Stats (..)+ , getStats+ ) where++import Control.Monad+import Data.Bits (shiftR, xor, (.&.), (.|.))+import Data.IORef+import Data.Int (Int8)+import qualified Data.IntSet as IntSet+import Data.List (nub, sortOn)+import qualified Data.Vector as V+import GHC.Clock (getMonotonicTime)+import qualified Data.Vector.Unboxed.Mutable as MU++import HSMT.SAT.Types+import HSMT.Util.GrowVec++-------------------------------------------------------------------------------+-- Clauses++-- | A clause is a mutable vector of integers with a two-slot header:+-- slot 0 holds flags, slot 1 the LBD, and literals start at slot 2.+-- The first two literals are the watched ones.+data Clause = Clause+ { clId :: !Int+ , clData :: !(MU.IOVector Int)+ }++instance Eq Clause where+ a == b = clId a == clId b++flagLearnt, flagDeleted :: Int+flagLearnt = 1+flagDeleted = 2++clauseSize :: Clause -> Int+clauseSize c = MU.length (clData c) - 2+{-# INLINE clauseSize #-}++clauseLit :: Clause -> Int -> IO Int+clauseLit c i = MU.unsafeRead (clData c) (i + 2)+{-# INLINE clauseLit #-}++clauseLits :: Clause -> IO [Int]+clauseLits c = mapM (clauseLit c) [0 .. clauseSize c - 1]++isDeleted :: Clause -> IO Bool+isDeleted c = do+ f <- MU.unsafeRead (clData c) 0+ pure (f .&. flagDeleted /= 0)+{-# INLINE isDeleted #-}++isNoClause :: Clause -> Bool+isNoClause c = clId c < 0+{-# INLINE isNoClause #-}++-------------------------------------------------------------------------------+-- Solver state++-- | Search statistics, cumulative over the life of a solver.+data Stats = Stats+ { statConflicts :: !Int+ -- ^ Conflicts encountered.+ , statDecisions :: !Int+ -- ^ Branching decisions (assumptions not included).+ , statPropagations :: !Int+ -- ^ Literals propagated.+ , statRestarts :: !Int+ -- ^ Restarts performed.+ , statLearnts :: !Int+ -- ^ Learnt clauses currently in the database.+ }+ deriving (Eq, Show)++-- | Mutable state of a CDCL solver instance.+data Solver = Solver+ { sOk :: !(IORef Bool)+ , sNumVars :: !(IORef Int)+ , sAssigns :: !(UVec Int8)+ , sLevel :: !(UVec Int)+ , sReason :: !(BVec Clause)+ , sPolarity :: !(UVec Bool)+ , sActivity :: !(UVec Double)+ , sSeen :: !(UVec Bool)+ , sWatches :: !(BVec (BVec Clause))+ , sTrail :: !(UVec Int)+ , sTrailLim :: !(UVec Int)+ , sQHead :: !(IORef Int)+ , sTheoryHead :: !(IORef Int)+ , sClauses :: !(BVec Clause)+ , sLearnts :: !(BVec Clause)+ , sNextId :: !(IORef Int)+ , sHeap :: !(UVec Int)+ , sHeapIndex :: !(UVec Int)+ , sVarInc :: !(IORef Double)+ , sTheory :: !(IORef (Maybe TheoryHooks))+ , sLemmaQueue :: !(IORef [Lemma])+ -- ^ Permanent theory lemmas not added yet because an earlier lemma of+ -- the same batch was conflicting.+ , sModel :: !(UVec Int8)+ , sFailed :: !(IORef [Lit])+ , sMaxLearnts :: !(IORef Double)+ , sNoClause :: !Clause+ , sCounters :: !(MU.IOVector Int)+ -- ^ Conflicts, decisions, propagations and restarts.+ }++-- | Create a solver with no variables and no clauses.+newSolver :: IO Solver+newSolver = do+ noData <- MU.replicate 2 0+ Solver+ <$> newIORef True+ <*> newIORef 0+ <*> newUVec 64+ <*> newUVec 64+ <*> newBVec 64+ <*> newUVec 64+ <*> newUVec 64+ <*> newUVec 64+ <*> newBVec 128+ <*> newUVec 64+ <*> newUVec 64+ <*> newIORef 0+ <*> newIORef 0+ <*> newBVec 64+ <*> newBVec 64+ <*> newIORef 0+ <*> newUVec 64+ <*> newUVec 64+ <*> newIORef 1+ <*> newIORef Nothing+ <*> newIORef []+ <*> newUVec 64+ <*> newIORef []+ <*> newIORef 2000+ <*> pure (Clause (-1) noData)+ <*> MU.replicate 4 0++-- | Install theory hooks. Must be called before solving.+setTheory :: Solver -> TheoryHooks -> IO ()+setTheory s th = writeIORef (sTheory s) (Just th)++-- | 'False' once the clause set is known to be unsatisfiable at decision+-- level 0 (independently of assumptions).+isOkay :: Solver -> IO Bool+isOkay = readIORef . sOk++-- | Number of variables created so far.+numVars :: Solver -> IO Int+numVars = readIORef . sNumVars++-- | Snapshot of the solver statistics.+getStats :: Solver -> IO Stats+getStats s =+ Stats+ <$> MU.read (sCounters s) cConflicts+ <*> MU.read (sCounters s) cDecisions+ <*> MU.read (sCounters s) cPropagations+ <*> MU.read (sCounters s) cRestarts+ <*> bSize (sLearnts s)++cConflicts, cDecisions, cPropagations, cRestarts :: Int+cConflicts = 0+cDecisions = 1+cPropagations = 2+cRestarts = 3++bumpStat :: Solver -> Int -> IO ()+bumpStat s c = MU.unsafeModify (sCounters s) (+ 1) c+{-# INLINE bumpStat #-}++-- | Create a fresh variable. Safe to call during search (from theory hooks).+newVar :: Solver -> IO Var+newVar s = do+ v <- readIORef (sNumVars s)+ writeIORef (sNumVars s) (v + 1)+ uPush (sAssigns s) 0+ uPush (sLevel s) 0+ bPush (sReason s) (sNoClause s)+ uPush (sPolarity s) True+ uPush (sActivity s) 0+ uPush (sSeen s) False+ uPush (sModel s) 0+ uPush (sHeapIndex s) (-1)+ newBVec 4 >>= bPush (sWatches s)+ newBVec 4 >>= bPush (sWatches s)+ heapInsert s v+ pure v++-- | Set the value the variable is tried with first when it is decided.+-- Phase saving overrides it once the variable has been assigned.+setPhase :: Solver -> Var -> Bool -> IO ()+setPhase s v b = uWrite (sPolarity s) v (not b)++-------------------------------------------------------------------------------+-- Assignment++-- | The current decision level (0 outside of search).+decisionLevel :: Solver -> IO Int+decisionLevel s = uSize (sTrailLim s)+{-# INLINE decisionLevel #-}++-- | Value of a literal as 1 (true), -1 (false) or 0 (unassigned).+litVal :: Solver -> Int -> IO Int8+litVal s l = do+ a <- uRead (sAssigns s) (l `shiftR` 1)+ pure (if odd l then negate a else a)+{-# INLINE litVal #-}++-- | Current value of a literal (during search or right after adding+-- clauses).+litValueNow :: Solver -> Lit -> IO LBool+litValueNow s (Lit l) = toLBool <$> litVal s l++toLBool :: Int8 -> LBool+toLBool 1 = LTrue+toLBool 0 = LUndef+toLBool _ = LFalse++enqueue :: Solver -> Int -> Clause -> IO ()+enqueue s l reason = do+ let v = l `shiftR` 1+ uWrite (sAssigns s) v (if odd l then -1 else 1)+ dl <- decisionLevel s+ uWrite (sLevel s) v dl+ bWrite (sReason s) v reason+ uPush (sTrail s) l+{-# INLINE enqueue #-}++newDecisionLevel :: Solver -> IO ()+newDecisionLevel s = do+ n <- uSize (sTrail s)+ uPush (sTrailLim s) n+ withTheory s $ \th -> thNewLevel th++withTheory :: Solver -> (TheoryHooks -> IO ()) -> IO ()+withTheory s k = readIORef (sTheory s) >>= mapM_ k+{-# INLINE withTheory #-}++-- | Undo all assignments above the given level.+cancelUntil :: Solver -> Int -> IO ()+cancelUntil s lvl = do+ dl <- decisionLevel s+ when (dl > lvl) $ do+ lim <- uRead (sTrailLim s) lvl+ n <- uSize (sTrail s)+ forM_ [n - 1, n - 2 .. lim] $ \i -> do+ l <- uRead (sTrail s) i+ let v = l `shiftR` 1+ uWrite (sAssigns s) v 0+ bWrite (sReason s) v (sNoClause s)+ uWrite (sPolarity s) v (odd l)+ heapInsert s v+ uShrink (sTrail s) lim+ writeIORef (sQHead s) lim+ modifyIORef' (sTheoryHead s) (min lim)+ uShrink (sTrailLim s) lvl+ withTheory s $ \th -> thBacktrack th lvl++-------------------------------------------------------------------------------+-- Clause database++mkClause :: Solver -> Bool -> [Int] -> IO Clause+mkClause s learnt lits = do+ i <- readIORef (sNextId s)+ writeIORef (sNextId s) (i + 1)+ d <- MU.new (length lits + 2)+ MU.write d 0 (if learnt then flagLearnt else 0)+ MU.write d 1 0+ zipWithM_ (\k l -> MU.write d (k + 2) l) [0 ..] lits+ pure (Clause i d)++attach :: Solver -> Clause -> IO ()+attach s c = do+ l0 <- clauseLit c 0+ l1 <- clauseLit c 1+ bRead (sWatches s) l0 >>= (`bPush` c)+ bRead (sWatches s) l1 >>= (`bPush` c)++-- | Add a problem clause. Must be called outside of search. Returns 'False'+-- if the clause set became trivially unsatisfiable.+addClause :: Solver -> [Lit] -> IO Bool+addClause s lits0 = do+ ok <- readIORef (sOk s)+ if not ok+ then pure False+ else do+ cancelUntil s 0+ let lits = nub (map unLit lits0)+ if any (\l -> (l `xor` 1) `elem` lits) lits+ then pure True+ else do+ vals <- mapM (litVal s) lits+ if 1 `elem` vals+ then pure True+ else case [l | (l, v) <- zip lits vals, v == 0] of+ [] -> writeIORef (sOk s) False >> pure False+ [l] -> do+ enqueue s l (sNoClause s)+ propagate s >>= \case+ Nothing -> pure True+ Just _ -> writeIORef (sOk s) False >> pure False+ ls -> do+ c <- mkClause s False ls+ attach s c+ bPush (sClauses s) c+ pure True++-------------------------------------------------------------------------------+-- Propagation++-- | Unit propagation over watched literals. Returns a conflicting clause.+propagate :: Solver -> IO (Maybe Clause)+propagate s = loop+ where+ loop = do+ qh <- readIORef (sQHead s)+ n <- uSize (sTrail s)+ if qh >= n+ then pure Nothing+ else do+ writeIORef (sQHead s) (qh + 1)+ p <- uRead (sTrail s) qh+ bumpStat s cPropagations+ let falseLit = p `xor` 1+ ws <- bRead (sWatches s) falseLit+ r <- propagateWatches s falseLit ws+ case r of+ Nothing -> loop+ Just c -> do+ uSize (sTrail s) >>= writeIORef (sQHead s)+ pure (Just c)++propagateWatches :: Solver -> Int -> BVec Clause -> IO (Maybe Clause)+propagateWatches s falseLit ws = do+ n <- bSize ws+ let go !i !j+ | i >= n = bShrink ws j >> pure Nothing+ | otherwise = do+ c <- bRead ws i+ del <- isDeleted c+ if del+ then go (i + 1) j+ else do+ let d = clData c+ l0 <- MU.unsafeRead d 2+ when (l0 == falseLit) $ do+ l1 <- MU.unsafeRead d 3+ MU.unsafeWrite d 2 l1+ MU.unsafeWrite d 3 l0+ first <- MU.unsafeRead d 2+ v0 <- litVal s first+ if v0 == 1+ then bWrite ws j c >> go (i + 1) (j + 1)+ else do+ k <- findWatch d 4 (MU.length d)+ if k >= 0+ then do+ lk <- MU.unsafeRead d k+ MU.unsafeWrite d 3 lk+ MU.unsafeWrite d k falseLit+ bRead (sWatches s) lk >>= (`bPush` c)+ go (i + 1) j+ else do+ bWrite ws j c+ if v0 == -1+ then do+ -- Conflict: keep the remaining watchers.+ forM_ [i + 1 .. n - 1] $ \t ->+ bRead ws t >>= bWrite ws (j + 1 + t - (i + 1))+ bShrink ws (j + 1 + n - (i + 1))+ pure (Just c)+ else do+ enqueue s first c+ go (i + 1) (j + 1)+ findWatch d !k len+ | k >= len = pure (-1)+ | otherwise = do+ l <- MU.unsafeRead d k+ v <- litVal s l+ if v /= -1 then pure k else findWatch d (k + 1) len+ go 0 0++-------------------------------------------------------------------------------+-- Conflict analysis++-- | First-UIP analysis. Returns the learnt clause (asserting literal first),+-- the backjump level and the clause's LBD.+analyze :: Solver -> Clause -> IO ([Int], Int, Int)+analyze s confl = do+ dl <- decisionLevel s+ outRef <- newIORef []+ idxStart <- subtract 1 <$> uSize (sTrail s)+ let loop c pathC p idx = do+ lits <- clauseLits c+ let lits' = if p < 0 then lits else drop 1 lits+ pathC' <-+ foldM+ ( \pc q -> do+ let v = q `shiftR` 1+ seen <- uRead (sSeen s) v+ lvl <- uRead (sLevel s) v+ if not seen && lvl > 0+ then do+ bumpVar s v+ uWrite (sSeen s) v True+ if lvl >= dl+ then pure (pc + 1)+ else modifyIORef' outRef (q :) >> pure pc+ else pure pc+ )+ pathC+ lits'+ idx' <- nextSeen idx+ p' <- uRead (sTrail s) idx'+ let v' = p' `shiftR` 1+ c' <- bRead (sReason s) v'+ uWrite (sSeen s) v' False+ if pathC' - 1 > 0+ then loop c' (pathC' - 1) p' (idx' - 1)+ else pure p'+ nextSeen i = do+ l <- uRead (sTrail s) i+ seen <- uRead (sSeen s) (l `shiftR` 1)+ if seen then pure i else nextSeen (i - 1)+ uip <- loop confl (0 :: Int) (-1) idxStart+ out <- readIORef outRef+ -- Local minimization: drop literals implied by other literals of the+ -- clause (or by level-0 facts).+ kept <- filterM (fmap not . redundant) out+ forM_ out $ \q -> uWrite (sSeen s) (q `shiftR` 1) False+ lvls <- mapM (\q -> uRead (sLevel s) (q `shiftR` 1)) kept+ let learnt = case sortOn (negate . fst) (zip lvls kept) of+ [] -> [uip `xor` 1]+ ((_, q) : rest) -> (uip `xor` 1) : q : map snd rest+ bt = if null lvls then 0 else maximum lvls+ lbd = IntSet.size (IntSet.fromList (dl : lvls))+ pure (learnt, bt, lbd)+ where+ redundant q = do+ r <- bRead (sReason s) (q `shiftR` 1)+ if isNoClause r+ then pure False+ else do+ lits <- drop 1 <$> clauseLits r+ andM+ [ do+ seen <- uRead (sSeen s) (l `shiftR` 1)+ lvl <- uRead (sLevel s) (l `shiftR` 1)+ pure (seen || lvl == 0)+ | l <- lits+ ]+ andM [] = pure True+ andM (m : ms) = m >>= \b -> if b then andM ms else pure False++-- | Compute a subset of the assumptions responsible for the falsification of+-- the assumption @p@ (which is currently false). Decisions found on the trail+-- are assumptions, since this runs during the assumption phase.+analyzeFinal :: Solver -> Int -> IO [Lit]+analyzeFinal s p = do+ dl <- decisionLevel s+ if dl == 0+ then pure [Lit p]+ else do+ uWrite (sSeen s) (p `shiftR` 1) True+ lim <- uRead (sTrailLim s) 0+ n <- uSize (sTrail s)+ core <-+ foldM+ ( \acc i -> do+ l <- uRead (sTrail s) i+ let v = l `shiftR` 1+ seen <- uRead (sSeen s) v+ if not seen+ then pure acc+ else do+ uWrite (sSeen s) v False+ r <- bRead (sReason s) v+ if isNoClause r+ then pure (Lit l : acc)+ else do+ lits <- drop 1 <$> clauseLits r+ forM_ lits $ \q -> do+ lvl <- uRead (sLevel s) (q `shiftR` 1)+ when (lvl > 0) $ uWrite (sSeen s) (q `shiftR` 1) True+ pure acc+ )+ []+ [n - 1, n - 2 .. lim]+ uWrite (sSeen s) (p `shiftR` 1) False+ pure (nub (Lit p : core))++-- | Learn a clause from a conflict and backjump.+learnFromConflict :: Solver -> Clause -> IO ()+learnFromConflict s confl = do+ bumpStat s cConflicts+ (learnt, bt, lbd) <- analyze s confl+ cancelUntil s bt+ case learnt of+ [l] -> enqueue s l (sNoClause s)+ l : _ -> do+ c <- mkClause s True learnt+ MU.write (clData c) 1 lbd+ attach s c+ bPush (sLearnts s) c+ enqueue s l c+ [] -> error "learnFromConflict: empty learnt clause"+ varDecay s++-------------------------------------------------------------------------------+-- Theory lemmas++data LemmaOutcome = LemmaOk | LemmaConflict Clause | LemmaUnsat++-- | Integrate a clause produced during search. Permanent clauses join the+-- problem clauses; the others are subject to learnt clause deletion.+addLemma :: Solver -> Bool -> [Lit] -> IO LemmaOutcome+addLemma s isPermanent lits0 = do+ let lits1 = nub (map unLit lits0)+ if any (\l -> (l `xor` 1) `elem` lits1) lits1+ then pure LemmaOk+ else do+ info <- forM lits1 $ \l -> do+ v <- litVal s l+ lvl <- uRead (sLevel s) (l `shiftR` 1)+ pure (l, v, lvl)+ if any (\(_, v, lvl) -> v == 1 && lvl == 0) info+ then pure LemmaOk+ else do+ let lits = [(l, v, lvl) | (l, v, lvl) <- info, not (v == -1 && lvl == 0)]+ key (_, v, lvl)+ | v == 1 = (0 :: Int, negate lvl)+ | v == 0 = (1, 0)+ | otherwise = (2, negate lvl)+ sorted = sortOn key lits+ case sorted of+ [] -> writeIORef (sOk s) False >> pure LemmaUnsat+ [(l, _, _)] -> do+ cancelUntil s 0+ enqueue s l (sNoClause s)+ pure LemmaOk+ (l0, v0, lvl0) : (_, v1, _) : _ -> do+ c <- mkClause s (not isPermanent) [l | (l, _, _) <- sorted]+ MU.write (clData c) 1 (length sorted)+ attach s c+ bPush (if isPermanent then sClauses s else sLearnts s) c+ if v0 == -1+ then do+ cancelUntil s lvl0+ pure (LemmaConflict c)+ else do+ when (v0 == 0 && v1 == -1) $ enqueue s l0 c+ pure LemmaOk++data TheoryOutcome = TOk | TAdded | TConflict Clause | TUnsat++-- | Hand pending literals to the theory and run one of its checks.+runTheory :: Solver -> (TheoryHooks -> IO TheoryResult) -> IO TheoryOutcome+runTheory s check =+ readIORef (sTheory s) >>= \case+ Nothing -> pure TOk+ Just th -> do+ h <- readIORef (sTheoryHead s)+ n <- uSize (sTrail s)+ forM_ [h .. n - 1] $ \i -> uRead (sTrail s) i >>= thAssert th . Lit+ writeIORef (sTheoryHead s) n+ -- Lemmas left over from an earlier batch come first.+ queued <- readIORef (sLemmaQueue s)+ writeIORef (sLemmaQueue s) []+ if not (null queued)+ then addAll queued+ else+ check th >>= \case+ TheoryOk -> pure TOk+ TheoryConflict ls -> outcome <$> addLemma s False (map litNeg ls)+ TheoryLemmas [] -> pure TOk+ TheoryLemmas cls -> addAll cls+ where+ outcome = \case+ LemmaOk -> TAdded+ LemmaConflict c -> TConflict c+ LemmaUnsat -> TUnsat+ addAll [] = pure TAdded+ addAll (Lemma isPermanent c : cs) =+ addLemma s isPermanent c >>= \case+ LemmaOk -> addAll cs+ LemmaConflict cl -> do+ -- Permanent lemmas may never be produced again, so the remaining+ -- ones are added after the conflict is resolved; removable ones+ -- can be recomputed by the theory and are dropped.+ modifyIORef' (sLemmaQueue s) (filter lemmaPermanent cs <>)+ pure (TConflict cl)+ LemmaUnsat -> pure TUnsat++-------------------------------------------------------------------------------+-- VSIDS++bumpVar :: Solver -> Int -> IO ()+bumpVar s v = do+ inc <- readIORef (sVarInc s)+ a <- (+ inc) <$> uRead (sActivity s) v+ uWrite (sActivity s) v a+ when (a > 1e100) $ do+ n <- readIORef (sNumVars s)+ forM_ [0 .. n - 1] $ \u -> uModify (sActivity s) u (* 1e-100)+ writeIORef (sVarInc s) (inc * 1e-100)+ idx <- uRead (sHeapIndex s) v+ when (idx >= 0) $ percolateUp s idx++varDecay :: Solver -> IO ()+varDecay s = modifyIORef' (sVarInc s) (/ 0.95)++heapInsert :: Solver -> Int -> IO ()+heapInsert s v = do+ idx <- uRead (sHeapIndex s) v+ when (idx < 0) $ do+ n <- uSize (sHeap s)+ uPush (sHeap s) v+ uWrite (sHeapIndex s) v n+ percolateUp s n++percolateUp :: Solver -> Int -> IO ()+percolateUp s i0 = do+ v <- uRead (sHeap s) i0+ av <- uRead (sActivity s) v+ let go i+ | i == 0 = place i+ | otherwise = do+ let p = (i - 1) `div` 2+ pv <- uRead (sHeap s) p+ aParent <- uRead (sActivity s) pv+ if av > aParent+ then do+ uWrite (sHeap s) i pv+ uWrite (sHeapIndex s) pv i+ go p+ else place i+ place i = uWrite (sHeap s) i v >> uWrite (sHeapIndex s) v i+ go i0++percolateDown :: Solver -> Int -> IO ()+percolateDown s i0 = do+ n <- uSize (sHeap s)+ v <- uRead (sHeap s) i0+ av <- uRead (sActivity s) v+ let go i = do+ let l = 2 * i + 1+ r = l + 1+ if l >= n+ then place i+ else do+ lv <- uRead (sHeap s) l+ al <- uRead (sActivity s) lv+ (c, cv, ac) <-+ if r < n+ then do+ rv <- uRead (sHeap s) r+ ar <- uRead (sActivity s) rv+ pure (if ar > al then (r, rv, ar) else (l, lv, al))+ else pure (l, lv, al)+ if ac > av+ then do+ uWrite (sHeap s) i cv+ uWrite (sHeapIndex s) cv i+ go c+ else place i+ place i = uWrite (sHeap s) i v >> uWrite (sHeapIndex s) v i+ go i0++heapPop :: Solver -> IO (Maybe Int)+heapPop s = do+ n <- uSize (sHeap s)+ if n == 0+ then pure Nothing+ else do+ top <- uRead (sHeap s) 0+ lastV <- uPop (sHeap s)+ uWrite (sHeapIndex s) top (-1)+ when (n > 1) $ do+ uWrite (sHeap s) 0 lastV+ uWrite (sHeapIndex s) lastV 0+ percolateDown s 0+ pure (Just top)++pickBranchLit :: Solver -> IO (Maybe Int)+pickBranchLit s =+ heapPop s >>= \case+ Nothing -> pure Nothing+ Just v -> do+ a <- uRead (sAssigns s) v+ if a /= 0+ then pickBranchLit s+ else do+ neg <- uRead (sPolarity s) v+ pure (Just (2 * v + fromEnum neg))++-------------------------------------------------------------------------------+-- Learnt clause deletion++reduceDB :: Solver -> IO ()+reduceDB s = do+ ls <- bToList (sLearnts s)+ scored <- forM ls $ \c -> do+ lbd <- MU.read (clData c) 1+ pure (lbd, c)+ let sorted = sortOn (\(lbd, c) -> (negate lbd, negate (clauseSize c))) scored+ half = length sorted `div` 2+ bClear (sLearnts s)+ forM_ (zip [0 :: Int ..] sorted) $ \(i, (lbd, c)) -> do+ locked <- isLocked c+ if i < half && lbd > 2 && not locked+ then MU.modify (clData c) (.|. flagDeleted) 0+ else bPush (sLearnts s) c+ modifyIORef' (sMaxLearnts s) (* 1.1)+ where+ isLocked c = do+ l0 <- clauseLit c 0+ r <- bRead (sReason s) (l0 `shiftR` 1)+ v <- litVal s l0+ pure (r == c && v == 1)++-------------------------------------------------------------------------------+-- Search++-- | Resource limits for 'solveWith'.+data SolveOptions = SolveOptions+ { optConflictLimit :: Maybe Int+ -- ^ Give up with 'Unknown' after this many conflicts.+ , optDeadline :: Maybe Double+ -- ^ Give up with 'Unknown' once the monotonic clock+ -- ('GHC.Clock.getMonotonicTime') passes this time, in seconds. The+ -- clock is read at every conflict and every final theory check.+ }++-- | No conflict limit and no deadline.+defaultSolveOptions :: SolveOptions+defaultSolveOptions = SolveOptions Nothing Nothing++data SearchResult = SRSat | SRUnsat | SRRestart | SRBudget++search :: Solver -> V.Vector Lit -> Int -> Int -> Maybe Double -> IO SearchResult+search s assumps restartAfter globalLimit deadline = go 0+ where+ go :: Int -> IO SearchResult+ go !nConfl =+ propagate s >>= \case+ Just c -> onConflict nConfl c+ Nothing ->+ runTheory s thPropagate >>= \case+ TConflict c -> onConflict nConfl c+ TUnsat -> pure SRUnsat+ TAdded -> go nConfl+ TOk -> decide nConfl++ onConflict nConfl c = do+ dl <- decisionLevel s+ if dl == 0+ then writeIORef (sOk s) False >> pure SRUnsat+ else do+ learnFromConflict s c+ total <- MU.read (sCounters s) cConflicts+ late <- pastDeadline+ if total >= globalLimit || late+ then pure SRBudget+ else+ if nConfl + 1 >= restartAfter+ then pure SRRestart+ else go (nConfl + 1)++ decide nConfl = do+ nl <- bSize (sLearnts s)+ nt <- uSize (sTrail s)+ maxL <- readIORef (sMaxLearnts s)+ when (fromIntegral (nl - nt) >= maxL) $ reduceDB s+ dl <- decisionLevel s+ if dl < V.length assumps+ then do+ let Lit p = assumps V.! dl+ litVal s p >>= \case+ 1 -> newDecisionLevel s >> go nConfl+ -1 -> do+ analyzeFinal s p >>= writeIORef (sFailed s)+ pure SRUnsat+ _ -> do+ newDecisionLevel s+ enqueue s p (sNoClause s)+ go nConfl+ else+ pickBranchLit s >>= \case+ Just l -> do+ bumpStat s cDecisions+ newDecisionLevel s+ enqueue s l (sNoClause s)+ go nConfl+ Nothing ->+ pastDeadline >>= \case+ True -> pure SRBudget+ False -> finalCheck nConfl++ finalCheck nConfl =+ runTheory s thFinalCheck >>= \case+ -- The theory may have created new variables (for instance to+ -- branch on): the assignment is complete only when they are+ -- assigned too.+ TOk ->+ pickBranchLit s >>= \case+ Nothing -> pure SRSat+ Just l -> do+ bumpStat s cDecisions+ newDecisionLevel s+ enqueue s l (sNoClause s)+ go nConfl+ TConflict c -> onConflict nConfl c+ TUnsat -> pure SRUnsat+ TAdded -> go nConfl++ pastDeadline = case deadline of+ Nothing -> pure False+ Just d -> (> d) <$> getMonotonicTime++-- | The Luby sequence scaled by @y@.+luby :: Double -> Int -> Double+luby y x0 =+ let (size0, sq0) = grow 1 0+ grow size sq+ | size < x0 + 1 = grow (2 * size + 1) (sq + 1)+ | otherwise = (size, sq)+ shrink size sq x+ | size - 1 /= x = let size' = (size - 1) `div` 2 in shrink size' (sq - 1) (x `mod` size')+ | otherwise = sq+ in y ^^ (shrink size0 sq0 x0 :: Int)++-- | Solve the current clause set.+solve :: Solver -> IO SatResult+solve s = solveWith s defaultSolveOptions []++-- | Solve under assumptions. On 'Unsat', 'failedAssumptions' returns a subset+-- of the assumptions that is sufficient for unsatisfiability (empty when the+-- clause set itself is unsatisfiable).+solveWith :: Solver -> SolveOptions -> [Lit] -> IO SatResult+solveWith s opts assumptions = do+ writeIORef (sFailed s) []+ ok <- readIORef (sOk s)+ if not ok+ then pure Unsat+ else do+ cancelUntil s 0+ start <- MU.read (sCounters s) cConflicts+ let limit = maybe maxBound (+ start) (optConflictLimit opts)+ assumps = V.fromList assumptions+ loop i = do+ let restartAfter = round (luby 2 i * 100) :: Int+ r <- search s assumps restartAfter limit (optDeadline opts)+ case r of+ SRRestart -> do+ bumpStat s cRestarts+ cancelUntil s 0+ loop (i + 1)+ SRSat -> do+ n <- readIORef (sNumVars s)+ forM_ [0 .. n - 1] $ \v -> uRead (sAssigns s) v >>= uWrite (sModel s) v+ cancelUntil s 0+ pure Sat+ SRUnsat -> cancelUntil s 0 >> pure Unsat+ SRBudget -> cancelUntil s 0 >> pure Unknown+ loop 0++-- | Value of a variable in the last model. Variables left unassigned+-- (possible only when created after solving) are reported as 'False'.+modelValue :: Solver -> Var -> IO Bool+modelValue s v = (== 1) <$> uRead (sModel s) v++-- | The values of all variables in the last model, indexed by variable.+getModel :: Solver -> IO [Bool]+getModel s = do+ n <- readIORef (sNumVars s)+ mapM (modelValue s) [0 .. n - 1]++-- | After an 'Unsat' answer of 'solveWith', a subset of the assumptions+-- sufficient for unsatisfiability (see 'solveWith').+failedAssumptions :: Solver -> IO [Lit]+failedAssumptions = readIORef . sFailed++-- | Literals already handed to the theory hooks, in assignment order. Call+-- it outside of search: hooks installed later can be brought up to date+-- with these literals (the others reach them through 'thAssert').+deliveredLits :: Solver -> IO [Lit]+deliveredLits s = do+ n <- readIORef (sTheoryHead s)+ mapM (fmap Lit . uRead (sTrail s)) [0 .. n - 1]
+ src/HSMT/SAT/Types.hs view
@@ -0,0 +1,133 @@+-- | Basic types shared by the SAT solver and its clients.+module HSMT.SAT.Types+ ( Var+ , Lit (..)+ , mkLit+ , posLit+ , negLit+ , litVar+ , litSign+ , litNeg+ , LBool (..)+ , SatResult (..)+ , TheoryResult (..)+ , Lemma (..)+ , removable+ , permanent+ , TheoryHooks (..)+ , noTheory+ ) where++-- | Propositional variables are numbered from 0.+type Var = Int++-- | A literal is encoded as @2 * var + sign@, where sign 1 means negated.+newtype Lit = Lit {unLit :: Int}+ deriving (Eq, Ord)++instance Show Lit where+ show l+ | litSign l = "-" <> show (litVar l + 1)+ | otherwise = show (litVar l + 1)++-- | @mkLit v True@ is the negative literal of @v@.+mkLit :: Var -> Bool -> Lit+mkLit v neg = Lit (2 * v + fromEnum neg)+{-# INLINE mkLit #-}++-- | The positive literal of a variable.+posLit :: Var -> Lit+posLit v = Lit (2 * v)+{-# INLINE posLit #-}++-- | The negative literal of a variable.+negLit :: Var -> Lit+negLit v = Lit (2 * v + 1)+{-# INLINE negLit #-}++-- | The variable of a literal.+litVar :: Lit -> Var+litVar (Lit l) = l `div` 2+{-# INLINE litVar #-}++-- | True for negative literals.+litSign :: Lit -> Bool+litSign (Lit l) = odd l+{-# INLINE litSign #-}++-- | The complementary literal (same variable, opposite sign).+litNeg :: Lit -> Lit+litNeg (Lit l) = Lit (if even l then l + 1 else l - 1)+{-# INLINE litNeg #-}++-- | Three-valued Booleans.+data LBool = LTrue | LFalse | LUndef+ deriving (Eq, Show)++-- | Outcome of a call to the SAT solver.+data SatResult+ = Sat+ -- ^ A satisfying assignment was found.+ | Unsat+ -- ^ The clauses are unsatisfiable (under the given assumptions).+ | Unknown+ -- ^ The resource budget was exhausted.+ deriving (Eq, Show)++-- | Answer of a theory solver to the SAT engine.+data TheoryResult+ = TheoryOk+ | TheoryConflict [Lit]+ -- ^ A set of currently true literals that is inconsistent with the+ -- theory. The engine learns the clause made of their negations.+ | TheoryLemmas [Lemma]+ -- ^ Clauses implied by the theory. They may mention fresh variables and+ -- may be unit or conflicting under the current assignment; implied+ -- (propagated) literals must come first in their clause.+ deriving (Eq, Show)++-- | A clause produced by a theory.+data Lemma = Lemma+ { lemmaPermanent :: !Bool+ -- ^ Permanent lemmas are never deleted. Use them for clauses the theory+ -- will not produce again (for instance because they introduce new+ -- atoms); explanations that can be recomputed should be removable.+ , lemmaClause :: [Lit]+ -- ^ The literals of the clause.+ }+ deriving (Eq, Show)++-- | Build a removable or a permanent lemma from a clause.+removable, permanent :: [Lit] -> Lemma+removable = Lemma False+permanent = Lemma True++-- | Callbacks that connect a theory solver to the CDCL engine (DPLL(T)).+--+-- The engine delivers assigned literals in batches, in trail order, through+-- 'thAssert' right before calling 'thPropagate' or 'thFinalCheck'. Every+-- literal delivered after the last 'thNewLevel' belongs to the current+-- decision level.+data TheoryHooks = TheoryHooks+ { thNewLevel :: IO ()+ -- ^ A new decision level was opened.+ , thBacktrack :: Int -> IO ()+ -- ^ Undo everything above the given decision level.+ , thAssert :: Lit -> IO ()+ -- ^ A literal became true.+ , thPropagate :: IO TheoryResult+ -- ^ Cheap consistency check after Boolean propagation.+ , thFinalCheck :: IO TheoryResult+ -- ^ Complete check once every variable is assigned.+ }++-- | Hooks for pure propositional solving.+noTheory :: TheoryHooks+noTheory =+ TheoryHooks+ { thNewLevel = pure ()+ , thBacktrack = \_ -> pure ()+ , thAssert = \_ -> pure ()+ , thPropagate = pure TheoryOk+ , thFinalCheck = pure TheoryOk+ }
+ src/HSMT/SMT/Engine.hs view
@@ -0,0 +1,2260 @@+-- | The solving engine (DPLL(T)).+--+-- Assertions are interned, their Boolean structure is Tseitin-encoded for+-- the SAT solver, and theory atoms are handed to the theory solvers through+-- 'HSMT.SAT.Types.TheoryHooks'.+--+-- Supported fragment: Boolean structure, equalities, @distinct@ and @ite@+-- over terms built from uninterpreted functions and constants, literal+-- values of the Bool, Int, String and uninterpreted sorts, linear integer+-- arithmetic, bit-vectors, arrays, records and strings (QF_AUFLIA and+-- QF_AUFBV, plus records and QF_SLIA without regular expressions).+-- Bit-vector terms are bit-blasted ('HSMT.Theory.BitBlast'); array and+-- record axioms are instantiated over congruence closure (see @arrayTerm@,+-- @arrayCheck@ and @recordTerm@); strings have a bounded encoding into+-- arithmetic and bits (see @SE@), so problems whose answer depends on+-- strings longer than @maxStringBound@ are answered 'EUnknown'. Floating-point+-- and rounding-mode terms are bit-blasted too ('HSMT.Theory.FloatBlast'). Integer+-- division and remainder are supported for literal divisors (division by+-- zero is uninterpreted, as in SMT-LIB). Other theory operators make the+-- engine answer 'EUnknown'.+--+-- EUF is combined with LIA and with bit-vectors by model-based theory+-- combination (de Moura and Bjørner, 2008): integer and bit-vector terms+-- shared with uninterpreted functions are compared in the arithmetic model+-- or in the current assignment of their bits, and equalities between them+-- are introduced and decided on demand.+--+-- Checks run in incremental sessions (t'Session'): formulas are SAT+-- assumptions, which gives unsatisfiable cores, and the encoding serves+-- later checks.+module HSMT.SMT.Engine+ ( EngineResult (..)+ , solveAssertions+ , Session+ , newSession+ , checkSession+ , CheckOptions (..)+ , defaultCheckOptions+ ) where++import Control.Monad (forM, forM_, replicateM, unless, void, when, zipWithM)+import Control.Monad.Except (ExceptT, runExceptT, throwError)+import Control.Monad.IO.Class (liftIO)+import Data.IORef+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Lazy as LazyMap+import qualified Data.IntMap.Strict as IntMap+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import qualified Data.IntSet as IntSet+import Data.Ratio (denominator, numerator)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import System.IO.Unsafe (unsafePerformIO)+import System.Timeout (timeout)+import GHC.Clock (getMonotonicTime)+import Data.Containers.ListUtils (nubOrd)++import HSMT.Core.Eval+import HSMT.Core.Expr+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Term+import HSMT.Core.Typing+import HSMT.Core.Value+import HSMT.SAT.Solver+import HSMT.SAT.Types+import HSMT.Theory.Arith+import HSMT.Theory.BitBlast (Bits, Circuit)+import qualified HSMT.Theory.FloatBlast as FB+import qualified HSMT.Core.Float as F+import qualified HSMT.Core.Regex as R+import qualified HSMT.Theory.BitBlast as BB+import HSMT.Theory.EUF++-- | Answer of the engine to a satisfiability check.+data EngineResult+ = ESat Interpretation+ -- ^ Satisfiable, with a model of the formulas.+ | EUnsat [Int]+ -- ^ The positions, in the checked list, of formulas whose conjunction+ -- is unsatisfiable (an unsatisfiable core).+ | EUnknown Text+ -- ^ The engine gave up; the text gives the reason (unsupported+ -- operator, timeout, resource limit, ...).+ deriving (Show)++type Enc a = ExceptT Text IO a++data Env = Env+ { envSolver :: Solver+ , envStore0 :: TermStore+ -- ^ The terms of the assertions.+ , envStore :: IORef TermStore+ -- ^ Extends 'envStore0'; only grows, as array axioms create terms+ -- during search.+ , envCache :: IORef (IntMap Lit)+ -- ^ Tseitin literal of each Boolean term.+ , envEqs :: IORef (Map (Int, Int) Lit)+ -- ^ Equality atoms.+ , envBoolSyms :: IORef [(Symbol, Var)]+ -- ^ Boolean constants and their variables.+ , envEUF :: EUF+ , envArith :: Arith+ , envTrue :: Lit+ , envLin :: IORef (IntMap LinExpr)+ -- ^ Linear form of each integer term.+ , envShared :: IORef IntSet.IntSet+ -- ^ Integer and bit-vector terms whose equalities matter to congruence+ -- closure: results and arguments of uninterpreted functions.+ , envDivMod :: IORef (Map (Int, Integer) (LinExpr, LinExpr))+ -- ^ Quotient and remainder variables of each division by a literal.+ , envCircuit :: Circuit+ , envBits :: IORef (IntMap Bits)+ -- ^ Bits of each bit-vector term.+ , envPending :: IORef [Lemma]+ -- ^ Clauses produced during search, waiting for the SAT solver.+ , envArrays :: Arrays+ , envStrBound :: Int+ -- ^ Number of character positions of each string term (see @SE@).+ , envBound :: Lit+ -- ^ Assumption that every string term fits in 'envStrBound' characters.+ , envStrings :: IORef (IntMap SE)+ -- ^ Encoding of each string term.+ , envNoSurrogates :: Lit+ -- ^ Assumption excluding surrogate code points from strings.+ , envLess :: IORef (Map (Int, Int) Lit)+ -- ^ Literals of @str.<@ by pair of arguments.+ , envRegexAtoms :: IORef (IntMap [(R.Regex, Lit)])+ -- ^ The @str.in_re@ atoms of each string term, with their expressions.+ }++-- | State of the array theory.+data Arrays = Arrays+ { axStoreCounts :: Map Sort Int+ -- ^ Number of @store@ terms of the problem per index sort.+ , axDone :: IORef (Set.Set (Int, Int))+ -- ^ Instantiated axioms: (store or constant array, index term).+ , axDefault :: IORef (IntMap Int)+ -- ^ The default-value term of each array term (see @arrayTerm@).+ , axInternal :: IORef (Set.Set Symbol)+ -- ^ Symbols introduced by the engine, hidden from models.+ , axFresh :: IORef Int+ , axShared :: IORef IntSet.IntSet+ -- ^ Array terms whose identity matters to congruence closure: arguments+ -- of uninterpreted functions and indices of other arrays.+ }++-- | Options of one satisfiability check.+data CheckOptions = CheckOptions+ { coValidate :: Bool+ -- ^ Check every model against the formulas before returning it.+ , coTimeout :: Maybe Double+ -- ^ Answer 'EUnknown' after this many seconds.+ , coConflictLimit :: Maybe Int+ -- ^ Answer 'EUnknown' after about this many conflicts of the SAT+ -- solver.+ , coMinimizeCore :: Bool+ -- ^ Shrink unsatisfiable cores until removing any formula makes the+ -- rest satisfiable (or the check gives up on it).+ , coNeedCore :: Bool+ -- ^ Whether an unsatisfiable answer needs a small core. The engine+ -- computes cores anyway; external solvers (see "HSMT.Backend") report+ -- every formula when this is off, which saves a tracked check.+ }+ deriving (Show)++-- | No model validation, no timeout, no conflict limit and no core+-- minimization; cores are wanted.+defaultCheckOptions :: CheckOptions+defaultCheckOptions = CheckOptions False Nothing Nothing False True++-- | An incremental solving session: a sequence of satisfiability checks of+-- formula lists that usually share most formulas (as with @push@ and+-- @pop@). The session keeps one encoding across checks, so the terms,+-- clauses, learnt clauses and theory lemmas of a check serve the next ones.+--+-- Every formula of a check is a SAT assumption (its Tseitin literal), never+-- a unit clause: the clause database only holds definitions and valid+-- theory lemmas, so it is satisfiable together with any formula list, and+-- the failed assumptions of a refutation give an unsatisfiable core.+-- Formulas of earlier checks that are no longer checked stay encoded but+-- unconstrained. The encoding is rebuilt from the current formulas when it+-- cannot serve them: a larger string bound is needed, a finite index sort+-- must now be expanded (see @expands@), too many formulas are no longer+-- checked, or an earlier check was interrupted.+newtype Session = Session (IORef (Maybe Encoding))++data Encoding = Encoding+ { encEnv :: Env+ , encHooks :: IORef (Bool, Bool)+ -- ^ Whether the EUF and the arithmetic hooks are installed. Once+ -- installed they stay.+ , encRoots :: IORef IntSet.IntSet+ -- ^ Formulas encoded so far.+ }++-- | A session with no encoding yet; the first check builds it.+newSession :: IO Session+newSession = Session <$> newIORef Nothing++-- | Decide the conjunction of the given assertions in a new session. When+-- the flag is set, models are checked against the assertions before being+-- returned.+solveAssertions :: Bool -> [Expr] -> IO EngineResult+solveAssertions validate as = do+ sess <- newSession+ checkSession sess defaultCheckOptions {coValidate = validate} as++-- | Decide the conjunction of the formulas. An 'EUnsat' answer carries the+-- positions of an unsatisfiable subset of the formulas.+--+-- Strings are encoded with a bounded number of characters (see @SE@). The+-- bound is an assumption: when it takes part in a refutation the formulas+-- are encoded again with a larger bound, up to @maxStringBound@.+checkSession :: Session -> CheckOptions -> [Expr] -> IO EngineResult+checkSession sess@(Session ref) opts formulas = case coTimeout opts of+ Nothing -> checkWith sess opts Nothing formulas+ Just secs -> do+ start <- getMonotonicTime+ -- The SAT solver stops by itself at the deadline; the hard limit also+ -- interrupts encoding and model construction, which leave the encoding+ -- in an unknown state, so it is dropped.+ let hard = secs + max 0.5 (secs / 2)+ timeout (ceiling (hard * 1e6)) (checkWith sess opts (Just (start + secs)) formulas) >>= \case+ Just r -> pure r+ Nothing -> EUnknown "timeout" <$ writeIORef ref Nothing++-- | The interned formulas of a check, in a store of their own.+data Problem = Problem+ { pRoots :: [TermId]+ , pStore :: TermStore+ , pTrue :: TermId+ , pFalse :: TermId+ }++checkWith :: Session -> CheckOptions -> Maybe Double -> [Expr] -> IO EngineResult+checkWith (Session ref) opts deadline formulas = case prepare of+ Left err -> pure (EUnknown ("ill-sorted assertion: " <> seMessage err))+ Right prob -> do+ current <- readIORef ref+ let needed = neededBound (pStore prob)+ reused <- case current of+ Just enc -> adopt enc needed+ Nothing -> pure Nothing+ case reused of+ Just (enc, roots) -> solveIn enc roots+ Nothing -> do+ -- A larger bound found by an earlier check is kept.+ let previous = maybe 0 (envStrBound . encEnv) current+ bound = if needed > 0 then max needed previous else 0+ fresh prob bound+ where+ prepare = do+ (roots, st1) <- internAll emptyStore formulas+ (tId, st2) <- internNode (BoolConst True) [] st1+ (fId, st3) <- internNode (BoolConst False) [] st2+ pure (Problem roots st3 tId fId)++ fresh prob bound = do+ enc <- newEncoding prob bound+ writeIORef ref (Just enc)+ solveIn enc (pRoots prob)++ -- Reuse the current encoding when it can serve the formulas.+ adopt enc needed = do+ let env = encEnv enc+ st <- readIORef (envStore env)+ done <- readIORef (encRoots enc)+ case internAll st formulas of+ Left _ -> pure Nothing+ Right (roots, st') -> do+ let counts = storeCounts st'+ expandsNow idx = expandsWith counts idx && not (expands env idx)+ live = IntSet.fromList (map unTermId roots)+ dead = IntSet.size (IntSet.difference done live)+ ok =+ (needed == 0 || envStrBound env >= needed)+ && not (any expandsNow (Map.keys counts))+ && dead <= max 16 (IntSet.size live)+ if ok+ then Just (enc, roots) <$ writeIORef (envStore env) st'+ else pure Nothing++ solveIn enc roots = do+ let env = encEnv enc+ s = envSolver env+ arith = envArith env+ resetBranching arith+ -- Clauses go straight to the solver while encoding (no search runs).+ BB.setSink (envCircuit env) (void . addClause s)+ leftover <- readIORef (envPending env)+ writeIORef (envPending env) []+ mapM_ (addClause s . lemmaClause) (reverse leftover)+ encoded <- runExceptT (mapM (encode env) roots)+ pendingLemmas arith >>= mapM_ (addClause s . lemmaClause)+ -- During search, clauses are handed to the solver as lemmas.+ BB.setSink (envCircuit env) (\c -> modifyIORef' (envPending env) (permanent c :))+ case encoded of+ Left why -> do+ -- A partial encoding is not worth keeping.+ writeIORef ref Nothing+ pure (EUnknown why)+ Right lits -> do+ modifyIORef' (encRoots enc) (IntSet.union (IntSet.fromList (map unTermId roots)))+ useEUF <- installHooks enc+ c0 <- statConflicts <$> getStats s+ let solveOpts = do+ used <- subtract c0 . statConflicts <$> getStats s+ pure+ defaultSolveOptions+ { optConflictLimit = (\l -> max 0 (l - used)) <$> coConflictLimit opts+ , optDeadline = deadline+ }+ sat assumed = solveOpts >>= \o -> solveWith s o assumed+ assumptions = nubOrd (filter (/= envTrue env) lits)+ gaveUp = do+ now <- getMonotonicTime+ pure . EUnknown $+ if maybe False (now >) deadline then "timeout" else "resource limit reached"+ -- The relaxation first: its refutations hold for strings of any+ -- length, and its models are exact when every string fits in the+ -- bound. Otherwise the bound is assumed.+ sat assumptions >>= \case+ Unsat -> EUnsat <$> core env sat lits+ Unknown -> gaveUp+ Sat ->+ allFit env >>= \case+ True -> finish env useEUF sat assumptions+ False ->+ sat (assumptions <> [envBound env]) >>= \case+ Unknown -> gaveUp+ Sat -> finish env useEUF sat (assumptions <> [envBound env])+ Unsat+ | 2 * envStrBound env <= maxStringBound ->+ either (error "unreachable") (`fresh` (2 * envStrBound env)) prepare+ | otherwise -> pure (EUnknown "string length bound reached")++ -- Install the hooks of the theories the formulas need. Hooks installed+ -- now must first learn the literals already handed to the others.+ installHooks enc = do+ let env = encEnv enc+ s = envSolver env+ st <- readIORef (envStore env)+ needEUF <- hasNodes (envEUF env)+ -- Arithmetic is only involved when the problem mentions integers+ -- (array axioms may create integer terms during search).+ needArith <-+ or+ <$> sequence+ [ hasArithVars (envArith env)+ , not . IntMap.null <$> readIORef (envLin env)+ , pure (mentionsInt st)+ ]+ (hadEUF, hadArith) <- readIORef (encHooks enc)+ let useEUF = hadEUF || needEUF+ useArith = hadArith || needArith+ when ((useEUF, useArith) /= (hadEUF, hadArith)) $ do+ delivered <- deliveredLits s+ when (useEUF && not hadEUF) $ mapM_ (thAssert (eufHooks (envEUF env))) delivered+ when (useArith && not hadArith) $ mapM_ (thAssert (arithHooks (envArith env))) delivered+ writeIORef (encHooks enc) (useEUF, useArith)+ setTheory s (combinedHooks env useEUF useArith)+ pure useEUF++ -- The positions of the failed assumptions, minimized on request.+ core env sat lits = do+ failed <- Set.fromList <$> failedAssumptions (envSolver env)+ let indexed = zip [0 ..] lits+ if Set.null failed+ then pure (map fst indexed) -- the clause set itself is unsatisfiable+ else do+ let initial = [(i, l) | (i, l) <- indexed, Set.member l failed]+ map fst <$> if coMinimizeCore opts then minimize env sat initial else pure initial++ -- Deletion-based minimization: drop each formula in turn and keep it+ -- only when the others are not refuted without it. A refutation of the+ -- others shrinks them to its own failed assumptions.+ minimize env sat = go []+ where+ go keep [] = pure keep+ go keep (c : rest) =+ sat (nubOrd [l | (_, l) <- keep <> rest, l /= envTrue env]) >>= \case+ Unsat -> do+ failed <- Set.fromList <$> failedAssumptions (envSolver env)+ let inCore (_, l) = Set.null failed || Set.member l failed+ go (filter inCore keep) (filter inCore rest)+ _ -> go (keep <> [c]) rest++ allFit env = do+ strings <- readIORef (envStrings env)+ and <$> mapM (modelLit env . seFits) (IntMap.elems strings)++ finish env useEUF sat assumed = do+ let s = envSolver env+ arith = envArith env+ strings <- IntMap.elems <$> readIORef (envStrings env)+ codes <- mapM (stringCodes env (modelLit env)) strings+ if any (any isSurrogate) codes && notElem (envNoSurrogates env) assumed+ then do+ -- Code points without a Text representation: look for a model+ -- without them.+ let c = envCircuit env+ noSurrogate ch = do+ below <- BB.bvULt c ch (BB.constBits c charWidth 0xD800)+ above <- BB.bvULt c (BB.constBits c charWidth 0xDFFF) ch+ BB.orG c below above+ BB.setSink c (void . addClause s)+ forM_ (concatMap seChars strings) $ \ch ->+ noSurrogate ch >>= \l -> addClause s [litNeg (envNoSurrogates env), l]+ BB.setSink c (\cl -> modifyIORef' (envPending env) (permanent cl :))+ let assumed' = envNoSurrogates env : assumed+ sat assumed' >>= \case+ Sat -> finish env useEUF sat assumed'+ _ -> pure (EUnknown "the model needs a surrogate code point, which has no Text representation")+ else+ isUnbranchable arith >>= \case+ True -> pure (EUnknown "branch-and-bound limit reached")+ False ->+ buildModel env useEUF >>= \case+ Left why -> pure (EUnknown why)+ Right interp -> do+ when (coValidate opts) (checkModel interp formulas)+ pure (ESat interp)++ modelLit env l = (/= litSign l) <$> modelValue (envSolver env) (litVar l)++internAll :: TermStore -> [Expr] -> Either SortError ([TermId], TermStore)+internAll st0 = go [] st0+ where+ go acc st [] = Right (reverse acc, st)+ go acc st (e : es) = do+ (tid, st') <- intern e st+ go (tid : acc) st' es++storeNodes :: TermStore -> [TermNode]+storeNodes st = [lookupNode st (TermId i) | i <- [0 .. storeSize st - 1]]++-- | Number of @store@ terms per index sort.+storeCounts :: TermStore -> Map Sort Int+storeCounts st =+ Map.fromListWith (+) [(i, 1) | TermNode Store _ (ArraySort i _) <- storeNodes st]++mentionsInt :: TermStore -> Bool+mentionsInt st = any (hasInt . nodeSort) (storeNodes st)+ where+ hasInt = \case+ IntSort -> True+ StringSort -> True+ ArraySort i e -> hasInt i || hasInt e+ RecordSort fs -> any (hasInt . snd) fs+ _ -> False++-- | The string bound the terms need: zero without strings, otherwise at+-- least 8 characters and enough for every literal.+neededBound :: TermStore -> Int+neededBound st+ | any (hasString . nodeSort) nodes =+ until (>= maximum (0 : [T.length w | TermNode (StrConst w) _ _ <- nodes])) (* 2) 8+ | otherwise = 0+ where+ nodes = storeNodes st+ hasString = \case+ StringSort -> True+ ArraySort i e -> hasString i || hasString e+ RecordSort fs -> any (hasString . snd) fs+ _ -> False++-- | Largest number of characters of the string encoding.+maxStringBound :: Int+maxStringBound = 32++-- | A new encoding of the problem's terms (the formulas are encoded by the+-- check), with the given string bound.+newEncoding :: Problem -> Int -> IO Encoding+newEncoding prob bound = do+ let store = pStore prob+ tId = pTrue prob+ fId = pFalse prob+ s <- newSolver+ tv <- newVar s+ void (addClause s [posLit tv])+ euf <- newEUF (unTermId tId) (unTermId fId)+ arith <- newArith s (posLit tv)+ circuit <- BB.newCircuit (newVar s) (void . addClause s) (posLit tv)+ pending <- newIORef []+ arrays <-+ Arrays (storeCounts store)+ <$> newIORef Set.empty+ <*> newIORef IntMap.empty+ <*> newIORef Set.empty+ <*> newIORef 0+ <*> newIORef IntSet.empty+ env <-+ Env s store+ <$> newIORef store+ <*> newIORef IntMap.empty+ <*> newIORef Map.empty+ <*> newIORef []+ <*> pure euf+ <*> pure arith+ <*> pure (posLit tv)+ <*> newIORef IntMap.empty+ <*> newIORef IntSet.empty+ <*> newIORef Map.empty+ <*> pure circuit+ <*> newIORef IntMap.empty+ <*> pure pending+ <*> pure arrays+ <*> pure bound+ <*> (posLit <$> newVar s)+ <*> newIORef IntMap.empty+ <*> (posLit <$> newVar s)+ <*> newIORef Map.empty+ <*> newIORef IntMap.empty+ -- The constants true and false are linked to the SAT constant.+ addAtom euf tv (ABool (unTermId tId) True)+ addAtom euf tv (ABool (unTermId fId) False)+ setEqAtomMaker euf (mkEqLit env)+ setValueOracle euf (litValueNow s)+ Encoding env <$> newIORef (False, False) <*> newIORef IntSet.empty+++-- | Every model is checked against the original assertions; a failure is an+-- internal error of the solver.+checkModel :: Interpretation -> [Expr] -> IO ()+checkModel interp assertions =+ forM_ assertions $ \a ->+ case evalExpr interp a of+ Right (VBool True) -> pure ()+ other ->+ error ("hsmt: internal error, model does not satisfy " <> show a <> ": " <> show other)++-------------------------------------------------------------------------------+-- Boolean structure++sortOfT :: Env -> Int -> Sort+sortOfT env t = nodeSort (nodeOf env t)++-- | The node of a term. The store only grows and nodes never change, so+-- reading it outside 'IO' is safe: the result for an existing term is the+-- same whenever the read happens.+nodeOf :: Env -> Int -> TermNode+nodeOf env t+ | t < storeSize (envStore0 env) = lookupNode (envStore0 env) (TermId t)+ | otherwise = laterNode env t++laterNode :: Env -> Int -> TermNode+laterNode env t = unsafePerformIO (flip lookupNode (TermId t) <$> readIORef (envStore env))+{-# NOINLINE laterNode #-}++-- | Intern a term built by the engine.+mkTerm :: Env -> Op -> [Int] -> IO Int+mkTerm env op args = do+ st <- readIORef (envStore env)+ case internNode op (map TermId args) st of+ Left err -> error ("hsmt: ill-sorted internal term: " <> T.unpack (seMessage err))+ Right (TermId t, st') -> t <$ writeIORef (envStore env) st'++-- | Run an encoding step whose failure would be an internal error (terms+-- created by theory axioms have supported sorts).+runEnc :: Enc a -> IO a+runEnc m =+ runExceptT m >>= \case+ Left why -> error ("hsmt: internal error: " <> T.unpack why)+ Right x -> pure x++-- | Tseitin literal of a Boolean term.+encode :: Env -> TermId -> Enc Lit+encode env (TermId t) = do+ cache <- liftIO (readIORef (envCache env))+ case IntMap.lookup t cache of+ Just l -> pure l+ Nothing -> do+ l <- encodeNode env t (nodeOf env t)+ liftIO (modifyIORef' (envCache env) (IntMap.insert t l))+ pure l++encodeNode :: Env -> Int -> TermNode -> Enc Lit+encodeNode env self (TermNode op args sort) = case op of+ BoolConst b -> pure (if b then envTrue env else litNeg (envTrue env))+ Uninterpreted sym+ | null args -> do+ v <- liftIO (newVar s)+ liftIO (modifyIORef' (envBoolSyms env) ((sym, v) :))+ pure (posLit v)+ | otherwise -> boolApp+ Select -> boolApp+ RecordGet _ -> boolApp+ _+ | op `elem` [StrContains, StrPrefixOf, StrSuffixOf, StrLt, StrLe, StrInRe] || regexArgs+ , Just (VBool b) <- groundValue env self ->+ pure (if b then envTrue env else litNeg (envTrue env))+ _ | regexArgs -> throwError "equality of regular languages that are not ground"+ StrContains | [a, b] <- argIds -> stringContains env a b+ StrInRe | [a, r] <- argIds -> stringInRe env a r+ StrPrefixOf | [a, b] <- argIds -> do+ -- a is a prefix of b iff len a <= len b and a = substr(b, 0, len a)+ la <- io (mkTerm env StrLen [a])+ lb <- io (mkTerm env StrLen [b])+ zero <- io (mkTerm env (IntConst 0) [])+ rewrite [(Le, [la, lb])] =<< io (mkTerm env StrSubstr [b, zero, la])+ StrSuffixOf | [a, b] <- argIds -> do+ -- a is a suffix of b iff len a <= len b and a = substr(b, len b - len a, len a)+ la <- io (mkTerm env StrLen [a])+ lb <- io (mkTerm env StrLen [b])+ start <- io (mkTerm env Sub [lb, la])+ rewrite [(Le, [la, lb])] =<< io (mkTerm env StrSubstr [b, start, la])+ StrLt | [a, b] <- argIds -> stringLess env a b+ StrLe | [a, b] <- argIds -> do+ lt <- stringLess env a b+ eq <- registerTerm env (TermId a) >> registerTerm env (TermId b) >> eqAtom env a b+ liftIO (litNeg <$> andGate [litNeg lt, litNeg eq])+ Not -> litNeg <$> arg1+ And -> mapM sub args >>= liftIO . andGate+ Or -> mapM sub args >>= fmap litNeg . liftIO . andGate . map litNeg+ Implies -> do+ ls <- mapM sub args+ case reverse ls of+ (c : hyps) -> liftIO (litNeg <$> andGate (litNeg c : hyps))+ [] -> malformed+ Xor -> do+ ls <- mapM sub args+ case ls of+ (a : rest) -> liftIO (foldlM' xorGate a rest)+ [] -> malformed+ Ite+ | sort == BoolSort -> mapM sub args >>= \case+ [c, a, b] -> liftIO (iteGate c a b)+ _ -> malformed+ Eq+ | bvArgs -> do+ bs <- mapM (blast env) argIds+ liftIO (andGate =<< sequence [BB.bvEq circ a b | (a, b) <- pairs bs])+ | boolArgs -> do+ ls <- mapM sub args+ liftIO (andGate =<< sequence [litNeg <$> xorGate a b | (a, b) <- pairs ls])+ | otherwise -> do+ mapM_ (registerTerm env . TermId) argIds+ eqs <- mapM (uncurry (eqAtom env)) (pairs argIds)+ liftIO (andGate eqs)+ Distinct+ | bvArgs -> do+ bs <- mapM (blast env) argIds+ eqs <- liftIO (sequence [BB.bvEq circ a b | (i, a) <- zip [0 :: Int ..] bs, b <- drop (i + 1) bs])+ liftIO (andGate (map litNeg eqs))+ | boolArgs -> do+ ls <- mapM sub args+ case ls of+ [a, b] -> liftIO (xorGate a b)+ _ -> pure (litNeg (envTrue env)) -- three distinct Booleans cannot exist+ | otherwise -> do+ mapM_ (registerTerm env . TermId) argIds+ eqs <- mapM (uncurry (eqAtom env)) [(a, b) | (i, a) <- zip [0 :: Int ..] argIds, b <- drop (i + 1) argIds]+ liftIO (andGate (map litNeg eqs))+ _+ | Just p <- fpPredicate op -> do+ bs <- mapM (blast env) argIds+ case map (sortOfT env) argIds of+ (FPSort eb sb : _) -> liftIO (p (eb, sb) bs)+ _ -> malformed+ _+ | Just cmp <- bvComparison op -> case args of+ [a, b] -> do+ ba <- blast env (unTermId a)+ bb <- blast env (unTermId b)+ liftIO (cmp circ ba bb)+ _ -> malformed+ _+ | Just mk <- comparison op -> do+ lins <- mapM (linearize env . unTermId) args+ atoms <- liftIO (mapM (leAtom (envArith env) . uncurry mk) (pairs lins))+ liftIO (andGate atoms)+ _ -> unsupported op+ where+ s = envSolver env+ circ = envCircuit env+ argIds = map unTermId args+ io = liftIO++ -- Prefix and suffix tests: the comparisons hold and the first argument+ -- equals the given substring.+ rewrite cmps sub' = case argIds of+ (a : _) -> do+ cs <- mapM (\(o, as) -> io (mkTerm env o as) >>= encode env . TermId) cmps+ registerTerm env (TermId a)+ registerTerm env (TermId sub')+ e <- eqAtom env a sub'+ io (andGate (e : cs))+ [] -> malformed++ -- A Boolean application is an atom linked to its EUF term.+ boolApp = do+ v <- liftIO (newVar s)+ registerApp env self op args+ liftIO (addAtom (envEUF env) v (ABool self True))+ pure (posLit v)+ bvArgs = case map (sortOfT env) argIds of+ (srt : _) -> isBitSort srt+ _ -> False++ -- Floating-point predicates over the bits of their arguments; the+ -- comparisons are chainable.+ fpPredicate = \case+ FPLeq -> Just (chain FB.fpLeq)+ FPLt -> Just (chain FB.fpLt)+ FPGeq -> Just (chain (\cc f a b -> FB.fpLeq cc f b a))+ FPGt -> Just (chain (\cc f a b -> FB.fpLt cc f b a))+ FPEq -> Just (chain FB.fpEq)+ FPIsNormal -> Just (unaryP FB.fpIsNormal)+ FPIsSubnormal -> Just (unaryP FB.fpIsSubnormal)+ FPIsZero -> Just (unaryP FB.fpIsZero)+ FPIsInfinite -> Just (unaryP FB.fpIsInf)+ FPIsNaN -> Just (unaryP FB.fpIsNaN)+ FPIsNegative -> Just (unaryP FB.fpIsNegative)+ FPIsPositive -> Just (unaryP FB.fpIsPositive)+ _ -> Nothing+ where+ chain rel fmt bs = andGate =<< sequence [rel circ fmt a b | (a, b) <- zip bs (drop 1 bs)]+ unaryP p fmt = \case+ [a] -> p circ fmt a+ _ -> malformed++ bvComparison = \case+ BVULt -> Just BB.bvULt+ BVULe -> Just BB.bvULe+ BVUGt -> Just (\cc a b -> BB.bvULt cc b a)+ BVUGe -> Just (\cc a b -> BB.bvULe cc b a)+ BVSLt -> Just BB.bvSLt+ BVSLe -> Just BB.bvSLe+ BVSGt -> Just (\cc a b -> BB.bvSLt cc b a)+ BVSGe -> Just (\cc a b -> BB.bvSLe cc b a)+ _ -> Nothing++ -- Each comparison as "e <= 0", using integrality for strict ones.+ comparison = \case+ Le -> Just (\a b -> linSub a b)+ Lt -> Just (\a b -> linAdd (linSub a b) (linConst 1))+ Ge -> Just (\a b -> linSub b a)+ Gt -> Just (\a b -> linAdd (linSub b a) (linConst 1))+ _ -> Nothing+ boolArgs = all ((== BoolSort) . sortOfT env) argIds+ -- Equalities between regular languages (always ground terms).+ regexArgs = op `elem` [Eq, Distinct] && any ((== RegLanSort) . sortOfT env) argIds+ sub = encode env+ arg1 = case args of+ [a] -> sub a+ _ -> malformed+ malformed = error ("hsmt: malformed term " <> T.unpack (opName op))+ pairs xs = zip xs (drop 1 xs)++ andGate [] = pure (envTrue env)+ andGate [l] = pure l+ andGate ls = do+ x <- posLit <$> newVar s+ forM_ ls $ \l -> addClause s [litNeg x, l]+ void (addClause s (x : map litNeg ls))+ pure x++ xorGate a b = do+ x <- posLit <$> newVar s+ void (addClause s [litNeg x, a, b])+ void (addClause s [litNeg x, litNeg a, litNeg b])+ void (addClause s [x, litNeg a, b])+ void (addClause s [x, a, litNeg b])+ pure x++ iteGate c a b = do+ x <- posLit <$> newVar s+ void (addClause s [litNeg x, litNeg c, a])+ void (addClause s [litNeg x, c, b])+ void (addClause s [x, litNeg c, litNeg a])+ void (addClause s [x, c, litNeg b])+ pure x++ foldlM' f z = \case+ [] -> pure z+ (y : ys) -> f z y >>= \z' -> foldlM' f z' ys++unsupported :: Op -> Enc a+unsupported op = throwError ("unsupported operator: " <> opName op <> " (theory not implemented yet)")++-------------------------------------------------------------------------------+-- EUF terms++-- | Equality atom between two registered terms.+eqAtom :: Env -> Int -> Int -> Enc Lit+eqAtom env a b = liftIO (mkEqLit env a b)++mkEqLit :: Env -> Int -> Int -> IO Lit+mkEqLit env a b+ | a == b = pure (envTrue env)+ | otherwise = do+ let key = (min a b, max a b)+ eqs <- readIORef (envEqs env)+ case Map.lookup key eqs of+ Just l -> pure l+ Nothing -> do+ v <- newVar (envSolver env)+ addAtom (envEUF env) v (uncurry AEq key)+ modifyIORef' (envEqs env) (Map.insert key (posLit v))+ case sortOfT env a of+ IntSort -> arithEquality env (posLit v) a b+ srt | isBitSort srt -> bitEquality env (posLit v) a b+ ArraySort idx _ -> extensionality env (posLit v) idx a b+ StringSort -> stringEquality env (posLit v) a b+ _ -> pure ()+ pure (posLit v)++-- | Axioms relating a bit-vector equality atom to the bits of its sides.+bitEquality :: Env -> Lit -> Int -> Int -> IO ()+bitEquality env eq a b = do+ bits <- readIORef (envBits env)+ case (IntMap.lookup a bits, IntMap.lookup b bits) of+ (Just ba, Just bb) -> do+ let c = envCircuit env+ same <- BB.bvEq c ba bb+ BB.emitClause c [litNeg eq, same]+ BB.emitClause c [eq, litNeg same]+ _ -> error "hsmt: bit-vector equality between terms without bits"++-- | Axioms relating an integer equality atom to arithmetic:+-- @eq -> a - b <= 0@, @eq -> b - a <= 0@ and @a - b <= 0 /\ b - a <= 0 -> eq@.+arithEquality :: Env -> Lit -> Int -> Int -> IO ()+arithEquality env eq a b = do+ lins <- readIORef (envLin env)+ case (IntMap.lookup a lins, IntMap.lookup b lins) of+ (Just la, Just lb) -> do+ let ar = envArith env+ p <- leAtom ar (linSub la lb)+ q <- leAtom ar (linSub lb la)+ queueClause ar [litNeg eq, p]+ queueClause ar [litNeg eq, q]+ queueClause ar [eq, litNeg p, litNeg q]+ _ -> error "hsmt: integer equality between terms without linear forms"++-- | Sorts of terms congruence closure can handle. Arrays are indexed by+-- sorts whose elements can be enumerated or that are infinite (see+-- @arrayTerm@).+eufSort :: Sort -> Bool+eufSort = \case+ BoolSort -> True+ IntSort -> True+ StringSort -> True+ BVSort _ -> True+ FPSort _ _ -> True+ RoundingModeSort -> True+ RegLanSort -> False+ UninterpretedSort _ -> True+ RecordSort fs -> all (eufSort . snd) fs+ ArraySort i e ->+ eufSort i && eufSort e && (enumerable i || finiteCardinality i == Nothing)++-- | Sorts whose elements are written with literals: Booleans, bit-vectors+-- and records of those.+enumerable :: Sort -> Bool+enumerable = \case+ BoolSort -> True+ BVSort _ -> True+ FPSort _ _ -> True+ RoundingModeSort -> True+ RecordSort fs -> all (enumerable . snd) fs+ _ -> False++-- | Make a term known to congruence closure.+registerTerm :: Env -> TermId -> Enc ()+registerTerm env (TermId t) = do+ done <- liftIO (isRegistered euf t)+ unless done $ do+ let TermNode op args sort = nodeOf env t+ unless (eufSort sort) $+ throwError ("unsupported sort in equality: " <> prettySort sort <> " (theory not implemented yet)")+ if sort == BoolSort+ then do+ -- Boolean terms are opaque for congruence; their value comes from+ -- their literal.+ l <- encode env (TermId t)+ registered <- liftIO (isRegistered euf t)+ unless registered $ liftIO $ do+ addNode euf t Leaf False+ -- Congruence closure learns the value of the term when the+ -- atom's variable is assigned. A variable assigned already (a+ -- constant, or a fact of an earlier check) may have been handed+ -- to the theories before the atom existed, so the atom gets a+ -- fresh variable equivalent to the literal.+ litValueNow (envSolver env) l >>= \case+ LUndef -> addAtom euf (litVar l) (ABool t (not (litSign l)))+ _ -> do+ v <- newVar (envSolver env)+ addAtom euf v (ABool t True)+ emit env [litNeg (posLit v), l]+ emit env [posLit v, litNeg l]+ else registerNonBool op args+ where+ euf = envEUF env++ registerNonBool op args = do+ registerNode op args+ case sortOfT env t of+ IntSort -> do+ lin <- linearize env t+ liftIO (modifyIORef' (envLin env) (IntMap.insert t lin))+ srt | isBitSort srt -> void (blast env t)+ ArraySort idx el -> arrayTerm env t idx el+ RecordSort fs -> liftIO (recordTerm env t (map fst fs))+ StringSort -> void (stringEnc env t)+ _ -> pure ()++ registerNode op args = case op of+ IntConst _ -> liftIO (addNode euf t Leaf True)+ FPConst {} -> liftIO (addNode euf t Leaf True)+ RMConst _ -> liftIO (addNode euf t Leaf True)+ StrConst _ -> liftIO (addNode euf t Leaf True)+ BVConst _ _ -> liftIO (addNode euf t Leaf True)+ Uninterpreted _ -> registerApp env t op args+ Select -> registerApp env t op args+ Store -> registerApp env t op args+ ConstArray _ -> registerApp env t op args+ RecordMk _ -> registerApp env t op args+ RecordGet _ -> registerApp env t op args+ RecordSet _ -> registerApp env t op args+ _+ | op `elem` stringOps ->+ -- String operators are opaque to congruence closure; their+ -- encoding determines their values.+ liftIO (addNode euf t Leaf False)+ | op `elem` [IntDiv, IntMod]+ , [_, d] <- args+ , nodeOp (nodeOf env (unTermId d)) == IntConst 0 ->+ -- Division by zero is an uninterpreted function of the dividend.+ registerApp env t op args+ | unspecifiedOp op ->+ -- Floating-point operations with unspecified results are+ -- functions of their arguments where unspecified.+ registerApp env t op args+ | op `elem` [Add, Sub, Neg, Mul, IntDiv, IntMod, Abs] || isBitSort (sortOfT env t) ->+ -- Arithmetic and bit-vector operators are opaque to congruence+ -- closure.+ liftIO (addNode euf t Leaf False)+ Ite -> case args of+ [c, a, b] -> do+ lc <- encode env c+ registerTerm env c+ registerTerm env a+ registerTerm env b+ liftIO (addNode euf t (AppNode Ite (map unTermId args)) False)+ -- The equality atoms below need the linear form or the bits of+ -- the ite.+ case sortOfT env t of+ IntSort -> void (linearize env t)+ srt | isBitSort srt -> void (blast env t)+ _ -> pure ()+ -- c => ite = a, not c => ite = b+ ea <- eqAtom env t (unTermId a)+ eb <- eqAtom env t (unTermId b)+ void (liftIO (addClause (envSolver env) [litNeg lc, ea]))+ void (liftIO (addClause (envSolver env) [lc, eb]))+ _ -> error "hsmt: malformed ite"+ _ -> unsupported op++registerApp :: Env -> Int -> Op -> [TermId] -> Enc ()+registerApp env t op args = do+ mapM_ (registerTerm env) args+ liftIO (addNode (envEUF env) t (AppNode op (map unTermId args)) False)+ -- Integer and bit-vector results and arguments of applications are shared+ -- with LIA and with the bit-blaster.+ let shared = filter (isSharedSort . sortOfT env) (t : map unTermId args)+ isSharedSort srt = srt == IntSort || srt == StringSort || isBitSort srt+ liftIO (modifyIORef' (envShared env) (\sh -> foldr IntSet.insert sh shared))+ -- Arrays given to uninterpreted functions or used as indices.+ let arrayArgs = case (op, map unTermId args) of+ (Uninterpreted sym, as) | not (isInternal sym) -> as+ (RecordMk _, as) -> as+ (Select, [_, i]) -> [i]+ (Store, [_, i, _]) -> [i]+ _ -> []+ isArraySort = \case+ ArraySort _ _ -> True+ _ -> False+ liftIO $+ modifyIORef' (axShared (envArrays env)) $ \sh ->+ foldr IntSet.insert sh (filter (isArraySort . sortOfT env) arrayArgs)++-- | Symbols introduced by the engine (array defaults and skolem indices).+isInternal :: Symbol -> Bool+isInternal sym = "hsmt!" `T.isPrefixOf` symName sym++-- | Sorts whose terms are bit-blasted: bit-vectors, floating point (the+-- IEEE pattern) and rounding modes (3 bits).+isBitSort :: Sort -> Bool+isBitSort = \case+ BVSort _ -> True+ FPSort _ _ -> True+ RoundingModeSort -> True+ _ -> False++bitWidth :: Sort -> Int+bitWidth = \case+ BVSort w -> w+ FPSort eb sb -> eb + sb+ RoundingModeSort -> 3+ s -> error ("hsmt: no bits for sort " <> T.unpack (prettySort s))++-- | Floating-point operators whose result SMT-LIB leaves unspecified for+-- some arguments.+unspecifiedOp :: Op -> Bool+unspecifiedOp = \case+ FPMin -> True+ FPMax -> True+ FPToUBV _ -> True+ FPToSBV _ -> True+ _ -> False++-- | Fresh bits for a term of the sort, constrained to valid patterns.+freshFor :: Env -> Sort -> IO Bits+freshFor env srt = do+ let c = envCircuit env+ bs <- BB.freshBits c (bitWidth srt)+ case srt of+ FPSort eb sb -> FB.fpInvariant c (eb, sb) bs+ RoundingModeSort -> FB.rmInvariant c bs+ _ -> pure ()+ pure bs++-------------------------------------------------------------------------------+-- Bit-vectors++-- | Bits of a bit-vector term. Uninterpreted constants get fresh bits;+-- applications of uninterpreted functions also get fresh bits and are+-- registered with congruence closure.+blast :: Env -> Int -> Enc Bits+blast env t = do+ cache <- liftIO (readIORef (envBits env))+ case IntMap.lookup t cache of+ Just bs -> pure bs+ Nothing -> do+ bs <- compute+ liftIO (modifyIORef' (envBits env) (IntMap.insert t bs))+ pure bs+ where+ c = envCircuit env+ TermNode op args sort = nodeOf env t+ width = bitWidth sort+ fmt = case sort of+ FPSort eb sb -> (eb, sb)+ _ -> (0, 0)+ fmtOf a = case sortOfT env (unTermId a) of+ FPSort eb sb -> (eb, sb)+ _ -> error "hsmt: not a floating-point term"+ -- An operation with a rounding mode and floating-point arguments.+ withRM f = case args of+ (r : xs) -> do+ br <- sub r+ bxs <- mapM sub xs+ io (f br bxs)+ [] -> error "hsmt: malformed floating-point term"+ -- A result that may be unspecified: a function of the arguments (see+ -- 'unspecifiedOp'), equal to the computed bits where specified.+ unspecifiedApp :: IO (Bits, Lit, Bits -> Lit -> IO ()) -> Enc Bits+ unspecifiedApp build = do+ registerTerm env (TermId t)+ io (IntMap.lookup t <$> readIORef (envBits env)) >>= \case+ Just bs -> pure bs+ Nothing -> io $ do+ (spec, specified, otherwise') <- build+ r <- BB.freshBits c width+ same <- BB.bvEq c r spec+ BB.emitClause c [litNeg specified, same]+ otherwise' r specified+ pure r+ sub = blast env . unTermId+ io = liftIO+ binary f = case args of+ (a : rest) -> do+ ba <- sub a+ brest <- mapM sub rest+ io (foldlM' f ba brest)+ [] -> error "hsmt: malformed bit-vector term"+ unary f = case args of+ [a] -> sub a >>= io . f+ _ -> error "hsmt: malformed bit-vector term"+ foldlM' f z = \case+ [] -> pure z+ (y : ys) -> f z y >>= \z' -> foldlM' f z' ys+ compute = case op of+ BVConst w v -> pure (BB.constBits c w v)+ Uninterpreted _+ | null args -> io (freshFor env sort)+ | otherwise -> application+ Select -> application+ RecordGet _ -> application+ Ite -> case args of+ [cond, a, b] -> do+ lc <- encode env cond+ ba <- sub a+ bb <- sub b+ io (BB.bvIte c lc ba bb)+ _ -> error "hsmt: malformed ite"+ BVNot -> unary (pure . BB.bvNot)+ BVNeg -> unary (BB.bvNeg c)+ BVAnd -> binary (BB.bvAnd c)+ BVOr -> binary (BB.bvOr c)+ BVXor -> binary (BB.bvXor c)+ BVAdd -> binary (BB.bvAdd c)+ BVSub -> binary (BB.bvSub c)+ BVMul -> binary (BB.bvMul c)+ BVUDiv -> binary (BB.bvUDiv c)+ BVURem -> binary (BB.bvURem c)+ BVSDiv -> binary (BB.bvSDiv c)+ BVSRem -> binary (BB.bvSRem c)+ BVSMod -> binary (BB.bvSMod c)+ BVShl -> binary (BB.bvShl c)+ BVLShr -> binary (BB.bvLShr c)+ BVAShr -> binary (BB.bvAShr c)+ -- (concat a b) has a in the high bits; bits are stored low first.+ BVConcat -> concat . reverse <$> mapM sub args+ BVExtract hi lo -> unary (\bs -> pure (take (hi - lo + 1) (drop lo bs)))+ BVZeroExtend k -> unary (\bs -> pure (bs <> replicate k (BB.cFalse c)))+ BVSignExtend k -> unary (\bs -> pure (bs <> replicate k (last bs)))+ -- Floating point+ FPConst _ _ x -> pure (BB.constBits c width x)+ RMConst rm -> pure (BB.constBits c 3 (toInteger (fromEnum rm)))+ FPFromFields -> mapM sub args >>= \case+ [bs, be, bf] -> io (FB.fpFromFields c fmt bs be bf)+ _ -> error "hsmt: malformed fp"+ FPAbs -> unary (FB.fpAbs c fmt)+ FPNeg -> unary (FB.fpNeg c fmt)+ FPAdd -> withRM (\r -> \case [a, b] -> FB.fpAdd c fmt r a b; _ -> bad)+ FPSub -> withRM (\r -> \case [a, b] -> FB.fpSub c fmt r a b; _ -> bad)+ FPMul -> withRM (\r -> \case [a, b] -> FB.fpMul c fmt r a b; _ -> bad)+ FPDiv -> withRM (\r -> \case [a, b] -> FB.fpDiv c fmt r a b; _ -> bad)+ FPFma -> withRM (\r -> \case [a, b, z] -> FB.fpFma c fmt r a b z; _ -> bad)+ FPSqrt -> withRM (\r -> \case [a] -> FB.fpSqrt c fmt r a; _ -> bad)+ FPRoundToIntegral -> withRM (\r -> \case [a] -> FB.fpRoundToIntegral c fmt r a; _ -> bad)+ FPRem -> binary (FB.fpRem c fmt)+ FPMin -> minMax FB.fpMin+ FPMax -> minMax FB.fpMax+ ToFP _ _ -> case (args, map (sortOfT env . unTermId) args) of+ ([_], [BVSort _]) -> unary (FB.fpFromBits c fmt)+ ([_, x], [_, FPSort _ _]) -> withRM (\r -> \case [a] -> FB.fpConvert c (fmtOf x) fmt r a; _ -> bad)+ (_, [_, BVSort _]) -> withRM (\r -> \case [a] -> FB.fpFromInt c fmt True r a; _ -> bad)+ _ -> error "hsmt: malformed to_fp"+ ToFPUnsigned _ _ -> withRM (\r -> \case [a] -> FB.fpFromInt c fmt False r a; _ -> bad)+ FPToUBV w -> toInt False w+ FPToSBV w -> toInt True w+ _ -> unsupported op+ bad :: IO a+ bad = error "hsmt: malformed floating-point term"+ minMax f = case args of+ [a, b] -> unspecifiedApp $ do+ ba <- runEnc (sub a)+ bb <- runEnc (sub b)+ (spec, unspec) <- f c fmt ba bb+ -- Where unspecified, the result is one of the two zeros.+ let zeroRest r u = mapM_ (\bit -> BB.emitClause c [litNeg u, litNeg bit]) (init r)+ pure (spec, litNeg unspec, \r specified -> zeroRest r (litNeg specified))+ _ -> error "hsmt: malformed fp.min"+ toInt signed w = case args of+ [r, a] -> unspecifiedApp $ do+ br <- runEnc (sub r)+ ba <- runEnc (sub a)+ (spec, specified) <- FB.fpToInt c (fmtOf a) signed w br ba+ pure (spec, specified, \_ _ -> pure ())+ _ -> error "hsmt: malformed fp.to_ubv"+ -- Registration blasts the application itself (see 'registerTerm'), so+ -- the bits may exist afterwards.+ application = do+ registerTerm env (TermId t)+ io (IntMap.lookup t <$> readIORef (envBits env)) >>= \case+ Just bs -> pure bs+ Nothing -> io (freshFor env sort)++-------------------------------------------------------------------------------+-- Arrays++-- | Whether arrays over an index sort are expanded (see @arrayTerm@):+-- enumerable sorts (Booleans, bit-vectors and records of those) with at most+-- 16 values or with no more values than there are stores in the problem.+expands :: Env -> Sort -> Bool+expands env = expandsWith (axStoreCounts (envArrays env))++-- | @expands@ for the given numbers of @store@ terms per index sort.+expandsWith :: Map Sort Int -> Sort -> Bool+expandsWith counts idx = enumerable idx && case finiteCardinality idx of+ Just n -> n <= max 16 (toInteger (Map.findWithDefault 0 idx counts))+ Nothing -> False++-- | The literal index terms of an expanded index sort (records of literals+-- for record sorts).+indexConstants :: Env -> Sort -> IO (Maybe [Int])+indexConstants env idx+ | expands env idx = Just <$> literals idx+ | otherwise = pure Nothing+ where+ literals = \case+ BoolSort -> mapM (\b -> mkTerm env (BoolConst b) []) [False, True]+ BVSort w -> mapM (\v -> mkTerm env (BVConst w v) []) [0 .. bvMask w]+ FPSort eb sb ->+ mapM+ (\v -> mkTerm env (FPConst eb sb v) [])+ [v | v <- [0 .. bvMask (eb + sb)], not (F.isNaNBits eb sb v) || v == F.canonicalNaN eb sb]+ RoundingModeSort -> mapM (\r -> mkTerm env (RMConst r) []) F.allRoundingModes+ RecordSort fs -> do+ fields <- mapM (literals . snd) fs+ mapM (mkTerm env (RecordMk (map fst fs))) (sequence fields)+ _ -> pure []++-- | Axioms of a new array term.+--+-- Arrays over expanded index sorts are read at every index, so their value+-- is determined by their reads; the axioms of stores and constant arrays are+-- instantiated at every index.+--+-- Other arrays get a default-value term @default(a)@: the value of @a@ at an+-- index written by no store. Such an index exists because the remaining+-- index sorts are infinite or have more values than there are stores.+-- Stores keep the default of their base and constant arrays have their+-- element as default; together with the reads, the default determines the+-- value of an array in the model. Read-over-write axioms of these arrays are+-- instantiated on demand (@arrayCheck@).+arrayTerm :: Env -> Int -> Sort -> Sort -> Enc ()+arrayTerm env t idx el = do+ expansion <- liftIO (indexConstants env idx)+ let TermNode op args _ = nodeOf env t+ case (expansion, op, map unTermId args) of+ (Just ks, _, argIds) -> do+ forM_ ks $ \k -> liftIO (mkTerm env Select [t, k]) >>= registerTerm env . TermId+ liftIO $ case (op, argIds) of+ (Store, [_, i, v]) -> storedValue i v >> mapM_ (instantiateRow env t) ks+ (ConstArray _, [_]) -> mapM_ (instantiateConst env t) ks+ _ -> pure ()+ (Nothing, Store, [a, i, v]) -> liftIO $ do+ storedValue i v+ d <- defaultTerm env t idx el+ da <- defaultTerm env a idx el+ termEq env d da >>= emit env . pure+ (Nothing, ConstArray _, [v]) -> liftIO $ do+ d <- defaultTerm env t idx el+ termEq env d v >>= emit env . pure+ (Nothing, _, _) -> void (liftIO (defaultTerm env t idx el))+ where+ -- select(store(a, i, v), i) = v+ storedValue i v = do+ sel <- mkTerm env Select [t, i]+ termEq env sel v >>= emit env . pure++-- | The default-value term of an array over a non-expanded index sort.+defaultTerm :: Env -> Int -> Sort -> Sort -> IO Int+defaultTerm env t idx el =+ IntMap.lookup t <$> readIORef (axDefault ax) >>= \case+ Just d -> pure d+ Nothing -> do+ let sym = Symbol "hsmt!default" [ArraySort idx el] el+ modifyIORef' (axInternal ax) (Set.insert sym)+ d <- mkTerm env (Uninterpreted sym) [t]+ modifyIORef' (axDefault ax) (IntMap.insert t d)+ runEnc (registerTerm env (TermId d))+ pure d+ where+ ax = envArrays env++-- | Equality literal of two terms, registering them first.+termEq :: Env -> Int -> Int -> IO Lit+termEq env a b = do+ runEnc (registerTerm env (TermId a) >> registerTerm env (TermId b))+ mkEqLit env a b++-- | Add a valid clause: directly while encoding, as a lemma during search.+emit :: Env -> [Lit] -> IO ()+emit env = BB.emitClause (envCircuit env)++-- | Run an instantiation once per (array term, index term) pair. Returns+-- whether it ran.+once :: Env -> (Int, Int) -> IO () -> IO Bool+once env key act = do+ done <- Set.member key <$> readIORef (axDone (envArrays env))+ if done+ then pure False+ else True <$ (modifyIORef' (axDone (envArrays env)) (Set.insert key) >> act)++-- | Read over write at index @j@ for @b = store(a, i, v)@:+-- @i = j \/ select(b, j) = select(a, j)@.+instantiateRow :: Env -> Int -> Int -> IO Bool+instantiateRow env b j = once env (b, j) $ case nodeOf env b of+ TermNode Store [TermId a, TermId i, _] _ -> do+ sb <- mkTerm env Select [b, j]+ sa <- mkTerm env Select [a, j]+ same <- termEq env i j+ sameRead <- termEq env sb sa+ emit env [same, sameRead]+ _ -> error "hsmt: read-over-write on a term that is not a store"++-- | Constant array at index @j@: @select(const(v), j) = v@.+instantiateConst :: Env -> Int -> Int -> IO Bool+instantiateConst env c j = once env (c, j) $ case nodeOf env c of+ TermNode (ConstArray _) [TermId v] _ -> do+ sel <- mkTerm env Select [c, j]+ termEq env sel v >>= emit env . pure+ _ -> error "hsmt: constant-array axiom on a term that is not a constant array"++-- | Extensionality for an equality atom between arrays: when the arrays+-- differ, they differ at some index. The index is a fresh constant, or each+-- index of an expanded sort.+extensionality :: Env -> Lit -> Sort -> Int -> Int -> IO ()+extensionality env eq idx a b = do+ ks <- indexConstants env idx >>= maybe (pure <$> skolem) pure+ same <- forM ks $ \k -> do+ sa <- mkTerm env Select [a, k]+ sb <- mkTerm env Select [b, k]+ termEq env sa sb+ emit env (eq : map litNeg same)+ where+ ax = envArrays env+ skolem = do+ n <- readIORef (axFresh ax)+ writeIORef (axFresh ax) (n + 1)+ let sym = Symbol ("hsmt!k" <> T.pack (show n)) [] idx+ modifyIORef' (axInternal ax) (Set.insert sym)+ k <- mkTerm env (Uninterpreted sym) []+ runEnc (registerTerm env (TermId k))+ pure k++-- | Instantiate the read-over-write and constant-array axioms made relevant+-- by the current congruence classes: for every read @select(x, j)@ of a+-- non-expanded array, every store whose result or base is in the class of+-- @x@, and every constant array in that class.+arrayCheck :: Env -> IO TheoryResult+arrayCheck env = do+ nodes <- registeredNodes (envEUF env)+ classes <- currentClasses (envEUF env)+ let classOf t = ciRepr (classes IntMap.! t)+ lazy t = case sortOfT env t of+ ArraySort idx _ -> not (expands env idx)+ _ -> False+ stores = [(b, a) | (b, AppNode Store [a, _, _]) <- IntMap.toList nodes, lazy b]+ storesOf =+ IntMap.fromListWith (<>) ([(classOf b, [b]) | (b, _) <- stores] <> [(classOf a, [b]) | (b, a) <- stores])+ constsOf =+ IntMap.fromListWith (<>) [(classOf c, [c]) | (c, AppNode (ConstArray _) _) <- IntMap.toList nodes, lazy c]+ selects = [(classOf x, j) | (_, AppNode Select [x, j]) <- IntMap.toList nodes, lazy x]+ progress <-+ forM selects $ \(cx, j) -> do+ r <- mapM (\b -> instantiateRow env b j) (IntMap.findWithDefault [] cx storesOf)+ c <- mapM (\k -> instantiateConst env k j) (IntMap.findWithDefault [] cx constsOf)+ pure (or r || or c)+ if or progress+ then do+ lemmas <- drainLemmas env+ pure (if null lemmas then TheoryOk else TheoryLemmas lemmas)+ else pure TheoryOk++-- | Clauses produced during search by the engine and by arithmetic.+drainLemmas :: Env -> IO [Lemma]+drainLemmas env = do+ axioms <- pendingLemmas (envArith env)+ bitAxioms <- reverse <$> readIORef (envPending env)+ writeIORef (envPending env) []+ pure (axioms <> bitAxioms)++-------------------------------------------------------------------------------+-- Records++-- | Axioms of a new record term. Records are a datatype with one+-- constructor: a constructor application gets the selection axioms+-- @get_f(mk(.., v_f, ..)) = v_f@; any other record term @r@ gets+-- @r = mk(get_f1(r), .., get_fn(r))@, so congruence closure derives both+-- that equal records have equal fields and that records with equal fields+-- are equal. An update @set_f(r, v)@ also gets @get_f(set_f(r, v)) = v@ and+-- @get_g(set_f(r, v)) = get_g(r)@ for the other fields.+--+-- The constructor applications created here have field reads of smaller+-- sorts as arguments, so the axioms only create finitely many terms.+recordTerm :: Env -> Int -> [Text] -> IO ()+recordTerm env t names = case (op, map unTermId args) of+ (RecordMk _, vs) -> forM_ (zip names vs) $ \(f, v) -> do+ g <- field f+ unit =<< termEq env g v+ _ -> do+ gs <- mapM field names+ case (op, map unTermId args) of+ (RecordSet f, [r, v]) -> forM_ (zip names gs) $ \(g, gt) ->+ if g == f+ then unit =<< termEq env gt v+ else mkTerm env (RecordGet g) [r] >>= termEq env gt >>= unit+ _ -> pure ()+ m <- mkTerm env (RecordMk names) gs+ unit =<< termEq env t m+ where+ TermNode op args _ = nodeOf env t+ field f = mkTerm env (RecordGet f) [t]+ unit l = emit env [l]++-------------------------------------------------------------------------------+-- Strings++-- | Bounded encoding of a string term.+--+-- A string has a length, an integer term of the arithmetic solver, and+-- characters at positions @0 .. L-1@ (@L@ is 'envStrBound'), 18-bit vectors+-- holding code points up to @0x2FFFF@. Positions at or past the length hold+-- the code point 0.+--+-- Every constraint is valid for strings of any length when the characters+-- are read as the first @L@ characters of the string: definitions that need+-- the whole string are guarded by the literals @len s <= L@ of the strings+-- involved. The encoding is therefore a relaxation of the theory, exact when+-- every string fits in @L@ characters. That condition is a single assumption+-- ('envBound'); a refutation that does not use it is a proof of+-- unsatisfiability for strings of any length.+data SE = SE+ { seLen :: LinExpr+ , seLe :: [Lit]+ -- ^ @len <= k@ for @k = 0 .. L@.+ , seChars :: [Bits]+ }++charWidth :: Int+charWidth = 18++maxCodePoint :: Integer+maxCodePoint = 0x2FFFF++-- | @len s <= L@.+seFits :: SE -> Lit+seFits = last . seLe++-- | Operators of the string theory.+stringOps :: [Op]+stringOps =+ [StrConcat, StrLen, StrAt, StrSubstr, StrIndexOf, StrReplace, StrToInt, StrFromInt]++-- | Build an encoding from a length and characters, tying it to the bound+-- assumption.+newSE :: Env -> LinExpr -> [Bits] -> IO SE+newSE env len chars = do+ les <- forM [0 .. envStrBound env] $ \k -> leAtom (envArith env) (linSub len (linConst (toInteger k)))+ let se = SE len les chars+ emit env [litNeg (envBound env), seFits se]+ pure se++-- | A string term with unconstrained characters, whose length is the+-- arithmetic variable of the term.+freshSE :: Env -> Int -> IO SE+freshSE env t = do+ let c = envCircuit env+ ar = envArith env+ len <- linVar <$> termVar ar t+ nonNeg <- leAtom ar (linScale (-1) len)+ emit env [nonNeg]+ chars <- replicateM (envStrBound env) $ do+ bs <- BB.freshBits c charWidth+ inRange <- BB.bvULe c bs (BB.constBits c charWidth maxCodePoint)+ emit env [inRange]+ pure bs+ se <- newSE env len chars+ -- Padding: no character at or past the length.+ forM_ (zip (seLe se) chars) $ \(past, bs) -> forM_ bs $ \b -> emit env [litNeg past, litNeg b]+ pure se++-- | The encoding of a string term.+stringEnc :: Env -> Int -> Enc SE+stringEnc env t = do+ cache <- io (readIORef (envStrings env))+ case IntMap.lookup t cache of+ Just se -> pure se+ Nothing -> do+ se <- compute+ -- Registration may have computed the encoding meanwhile.+ known <- io (IntMap.lookup t <$> readIORef (envStrings env))+ case known of+ Just se' -> pure se'+ Nothing -> se <$ io (modifyIORef' (envStrings env) (IntMap.insert t se))+ where+ io = liftIO+ c = envCircuit env+ bound = envStrBound env+ TermNode op args _ = nodeOf env t+ argIds = map unTermId args+ alias o as = io (mkTerm env o as) >>= stringEnc env+ int n = io (mkTerm env (IntConst n) [])+ compute = case (op, argIds) of+ _+ | not (isStrConst op)+ , Just (VString w) <- groundValue env t ->+ io (mkTerm env (StrConst w) []) >>= stringEnc env+ (StrConst w, []) -> io $ do+ let codes = map (toInteger . fromEnum) (T.unpack w)+ chars = take bound (map (BB.constBits c charWidth) (codes <> repeat 0))+ newSE env (linConst (toInteger (T.length w))) chars+ (StrConcat, a : rest) -> do+ sa <- stringEnc env a+ srest <- mapM (stringEnc env) rest+ io (foldlM' (concatSE env) sa srest)+ (StrAt, [a, i]) -> do+ one <- int 1+ alias StrSubstr [a, i, one]+ (StrSubstr, [a, i, n]) -> stringSubstr env t a i n+ (StrReplace, [a, p, u]) -> do+ -- The first occurrence of p in a is replaced by u; an empty pattern+ -- is replaced at the start.+ empty <- io (mkTerm env (StrConst "") [])+ isEmpty <- io (mkTerm env Eq [p, empty])+ prepended <- io (mkTerm env StrConcat [u, a])+ zero <- int 0+ minus1 <- int (-1)+ at <- io (mkTerm env StrIndexOf [a, p, zero])+ missing <- io (mkTerm env Eq [at, minus1])+ before <- io (mkTerm env StrSubstr [a, zero, at])+ lenA <- io (mkTerm env StrLen [a])+ lenP <- io (mkTerm env StrLen [p])+ from <- io (mkTerm env Add [at, lenP])+ rest <- io (mkTerm env Sub [lenA, from])+ after <- io (mkTerm env StrSubstr [a, from, rest])+ replaced <- io (mkTerm env StrConcat [before, u, after])+ inner <- io (mkTerm env Ite [missing, a, replaced])+ alias Ite [isEmpty, prepended, inner]+ (StrFromInt, [n]) -> stringFromInt env t n+ (Uninterpreted _, []) -> io (freshSE env t)+ _ -> registerTerm env (TermId t) >> io (freshSE env t)+ foldlM' f z = \case+ [] -> pure z+ (y : ys) -> f z y >>= \z' -> foldlM' f z' ys++-- | Value of a term built from literals and operators of the string and+-- arithmetic theories, computed by the reference evaluator.+groundValue :: Env -> Int -> Maybe Value+groundValue env t = do+ e <- toGround t+ either (const Nothing) Just (evalExpr emptyInterpretation e)+ where+ toGround u =+ let TermNode op args _ = nodeOf env u+ in if groundOp op then App op <$> mapM (toGround . unTermId) args else Nothing+ groundOp = \case+ StrConst _ -> True+ IntConst _ -> True+ BoolConst _ -> True+ ReLoop _ _ -> True+ RePower _ -> True+ op -> op `elem` (stringOps <> regexOps <> [StrContains, StrPrefixOf, StrSuffixOf, StrLt, StrLe, Add, Sub, Neg, Mul, Abs, Ite, Eq, Distinct, Not, And, Or])+ regexOps =+ [StrToRe, StrInRe, ReNone, ReAll, ReAllChar, ReConcat, ReUnion, ReInter, ReStar, RePlus, ReOpt, ReRange, ReComp, ReDiff]++isStrConst :: Op -> Bool+isStrConst = \case+ StrConst _ -> True+ _ -> False++-- | Concatenation: position @i@ holds @x[i]@ when @i < len x@ and+-- @y[i - len x]@ otherwise.+concatSE :: Env -> SE -> SE -> IO SE+concatSE env x y = do+ let c = envCircuit env+ xs = seChars x+ ys = seChars y+ le = seLe x+ chars <- forM (zip [0 ..] xs) $ \(i, xi) -> do+ -- The first k with len x <= k is len x itself.+ tailPart <- foldlM' (\acc k -> BB.bvIte c (le !! k) (ys !! (i - k)) acc) (ys !! 0) [i - 1, i - 2 .. 0]+ BB.bvIte c (le !! i) tailPart xi+ newSE env (linAdd (seLen x) (seLen y)) chars+ where+ foldlM' f z = \case+ [] -> pure z+ (a : as) -> f z a >>= \z' -> foldlM' f z' as++-- | @len = k@ for @k = 0 .. L@.+lenIs :: Env -> SE -> IO [Lit]+lenIs env se =+ forM (zip [0 :: Int ..] (seLe se)) $ \case+ (0, le0) -> pure le0+ (k, lek) -> BB.andG (envCircuit env) lek (litNeg (seLe se !! (k - 1)))++-- | Literal @e = k@ of an integer expression.+intIs :: Env -> LinExpr -> Integer -> IO Lit+intIs env e k = do+ let ar = envArith env+ le <- leAtom ar (linSub e (linConst k))+ below <- leAtom ar (linSub e (linConst (k - 1)))+ BB.andG (envCircuit env) le (litNeg below)++-- | Clauses for @e = e'@ under the given condition (the literals of the+-- condition are negated in the clauses).+equalUnder :: Env -> [Lit] -> LinExpr -> LinExpr -> IO ()+equalUnder env conds e e' = do+ let ar = envArith env+ p <- leAtom ar (linSub e e')+ q <- leAtom ar (linSub e' e)+ emit env (p : map litNeg conds)+ emit env (q : map litNeg conds)++-- | Equality atom between strings: equal lengths and characters.+stringEquality :: Env -> Lit -> Int -> Int -> IO ()+stringEquality env eq a b = do+ sa <- runEnc (stringEnc env a)+ sb <- runEnc (stringEnc env b)+ let ar = envArith env+ c = envCircuit env+ p <- leAtom ar (linSub (seLen sa) (seLen sb))+ q <- leAtom ar (linSub (seLen sb) (seLen sa))+ same <- zipWithM (BB.bvEq c) (seChars sa) (seChars sb)+ mapM_ (\l -> emit env [litNeg eq, l]) (p : q : same)+ emit env (eq : seFitsNeg sa : map litNeg (p : q : same))+ where+ seFitsNeg = litNeg . seFits++-- | @substr(s, i, n)@: when @0 <= i < len s@ and @n > 0@, the characters of+-- @s@ from @i@, at most @n@ of them; otherwise the empty string.+stringSubstr :: Env -> Int -> Int -> Int -> Int -> Enc SE+stringSubstr env t a i n = do+ sa <- stringEnc env a+ li <- linearize env i+ ln <- linearize env n+ io $ do+ let ar = envArith env+ c = envCircuit env+ bound = envStrBound env+ ls = seLen sa+ r <- freshSE env t+ let lr = seLen r+ a1 <- leAtom ar (linScale (-1) li)+ a2 <- leAtom ar (linAdd (linSub li ls) (linConst 1))+ a3 <- leAtom ar (linSub (linConst 1) ln)+ cond <- BB.andN c [a1, a2, a3]+ emptyR <- leAtom ar lr+ emit env [cond, emptyR]+ whole <- leAtom ar (linSub ln (linSub ls li))+ equalUnder env [cond, whole] lr ln+ equalUnder env [cond, litNeg whole] lr (linSub ls li)+ forM_ [0 .. bound - 1] $ \k -> do+ atK <- intIs env li (toInteger k)+ forM_ [0 .. bound - 1 - k] $ \j -> do+ same <- BB.bvEq c (seChars r !! j) (seChars sa !! (k + j))+ -- Visible positions of s hold its real characters: no guard.+ emit env [litNeg cond, litNeg atK, seLe r !! j, same]+ pure r+ where+ io = liftIO++-- | Literal: @p@ occurs in @s@ at position @k@.+occursAt :: Env -> SE -> SE -> Int -> IO Lit+occursAt env s p k = do+ let c = envCircuit env+ bound = envStrBound env+ fits <- leAtom (envArith env) (linSub (linAdd (seLen p) (linConst (toInteger k))) (seLen s))+ chars <- forM [0 .. bound - 1] $ \j ->+ if k + j < bound+ then BB.bvEq c (seChars s !! (k + j)) (seChars p !! j) >>= BB.orG c (seLe p !! j)+ else pure (seLe p !! j)+ BB.andN c (fits : chars)++-- | @contains(s, p)@.+stringContains :: Env -> Int -> Int -> Enc Lit+stringContains env a b = do+ ss <- stringEnc env a+ sp <- stringEnc env b+ liftIO $ do+ l <- posLit <$> newVar (envSolver env)+ occ <- mapM (occursAt env ss sp) [0 .. envStrBound env]+ mapM_ (\o -> emit env [l, litNeg o]) occ+ -- Every occurrence in a string that fits in the bound is visible.+ emit env (litNeg l : litNeg (seFits ss) : occ)+ shorter <- leAtom (envArith env) (linSub (seLen sp) (seLen ss))+ emit env [litNeg l, shorter]+ -- The empty string occurs everywhere.+ emit env [l, litNeg (seLe sp !! 0)]+ pure l++-- | @str.in_re(s, r)@ for a ground expression @r@: the automaton of @r@+-- ('R.toDfa') runs over the characters of @s@, one state literal per state+-- and position. When @s@ fits in the bound, the atom holds iff the state at+-- position @len s@ is accepting. Longer strings are only known to reach,+-- after the first @L@ characters, a state from which an accepting one can+-- be reached; and every member is at least as long as the shortest string+-- of the language (and at most as long as the longest, when the language+-- is finite).+stringInRe :: Env -> Int -> Int -> Enc Lit+stringInRe env a r = do+ regex <- case groundValue env r of+ Just (VRegLan x) -> pure x+ _ -> throwError "regular expressions must be ground (str.to_re of string literals)"+ dfa <- maybe (throwError "regular expression with too many states") pure (R.toDfa regex)+ ss <- stringEnc env a+ liftIO $ do+ let c = envCircuit env+ ar = envArith env+ n = R.dfaStates dfa+ incoming =+ IntMap.fromListWith (<>) [(j, [(q, cs)]) | (q, edges) <- IntMap.toList (R.dfaDelta dfa), (cs, j) <- edges]+ initial = IntMap.fromList [(q, if q == 0 then BB.cTrue c else BB.cFalse c) | q <- [0 .. n - 1]]+ inSet chars cs+ | cs == R.fullSet = pure (BB.cTrue c)+ | otherwise = do+ ranges <- forM cs $ \(lo, hi) -> do+ ge <- BB.bvULe c (BB.constBits c charWidth (toInteger lo)) chars+ le <- BB.bvULe c chars (BB.constBits c charWidth (toInteger hi))+ BB.andG c ge le+ BB.orN c ranges+ step st chars =+ fmap IntMap.fromList . forM [0 .. n - 1] $ \q' -> do+ ins <- forM (IntMap.findWithDefault [] q' incoming) $ \(q, cs) ->+ inSet chars cs >>= BB.andG c (st IntMap.! q)+ (,) q' <$> BB.orN c ins+ anyOf st qs = BB.orN c [st IntMap.! q | q <- IntSet.toList qs]+ states <- scanM step initial (seChars ss)+ lens <- lenIs env ss+ accepted <- forM (zip lens states) (\(isLen, st) -> anyOf st (R.dfaAccepting dfa) >>= BB.andG c isLen) >>= BB.orN c+ live <- anyOf (last states) (R.liveStates dfa)+ l <- posLit <$> newVar (envSolver env)+ emit env [litNeg l, litNeg (seFits ss), accepted]+ emit env [l, litNeg accepted]+ emit env [litNeg l, seFits ss, live]+ case R.minLength dfa of+ Nothing -> emit env [litNeg l]+ Just m -> when (m > 0) $ do+ shorter <- leAtom ar (linSub (seLen ss) (linConst (toInteger m - 1)))+ emit env [litNeg l, litNeg shorter]+ forM_ (R.maxLength dfa) $ \m -> do+ notLonger <- leAtom ar (linSub (seLen ss) (linConst (toInteger m)))+ emit env [litNeg l, notLonger]+ relateRegexAtoms env a regex l+ pure l+ where+ -- The states before each character and after the last one.+ scanM f z = \case+ [] -> pure [z]+ (x : xs) -> f z x >>= \z' -> (z :) <$> scanM f z' xs++-- | Clauses between the new atom @str.in_re(s, r)@ and the earlier atoms+-- on the same string term, from the relations between their languages:+-- disjoint languages exclude each other, an included language implies the+-- other, and two languages whose union is every string cannot both fail.+-- They hold for strings of any length, so they refute some problems the+-- bounded encoding alone cannot.+relateRegexAtoms :: Env -> Int -> R.Regex -> Lit -> IO ()+relateRegexAtoms env s r l = do+ earlier <- IntMap.findWithDefault [] s <$> readIORef (envRegexAtoms env)+ modifyIORef' (envRegexAtoms env) (IntMap.insertWith (<>) s [(r, l)])+ -- A few earlier atoms are enough in practice and keep this quadratic+ -- step cheap.+ forM_ (take 16 earlier) $ \(r', l') -> do+ let empty x = R.isEmpty x == Just True+ when (empty (R.inter [r, r'])) $ emit env [litNeg l, litNeg l']+ when (empty (R.difference r r')) $ emit env [litNeg l, l']+ when (empty (R.difference r' r)) $ emit env [litNeg l', l]+ when (empty (R.inter [R.complement r, R.complement r'])) $ emit env [l, l']++-- | @indexof(s, p, i)@: the first position at or after @i@ where @p@+-- occurs, when @0 <= i <= len s@; otherwise -1.+stringIndexOf :: Env -> Int -> Int -> Int -> Int -> Enc LinExpr+stringIndexOf env t a b i = do+ ss <- stringEnc env a+ sp <- stringEnc env b+ li <- linearize env i+ liftIO $ do+ let ar = envArith env+ c = envCircuit env+ bound = envStrBound env+ r <- linVar <$> termVar ar t+ atLeastM1 <- leAtom ar (linSub (linConst (-1)) r)+ notFound <- leAtom ar (linAdd r (linConst 1))+ atMostLen <- leAtom ar (linSub r (seLen ss))+ emit env [atLeastM1]+ emit env [atMostLen]+ v1 <- leAtom ar (linScale (-1) li)+ v2 <- leAtom ar (linSub li (seLen ss))+ valid <- BB.andG c v1 v2+ emit env [valid, notFound]+ afterI <- leAtom ar (linSub li r)+ emit env [litNeg valid, notFound, afterI]+ -- Facts for strings of any length: an occurrence fits in s, a search+ -- that finds something was valid, and the empty pattern is found at i.+ fitsS <- leAtom ar (linSub (linAdd r (seLen sp)) (seLen ss))+ emit env [notFound, fitsS]+ emit env [notFound, valid]+ equalUnder env [valid, seLe sp !! 0] r li+ occ <- mapM (occursAt env ss sp) [0 .. bound]+ from <- mapM (\k -> leAtom ar (linSub li (linConst (toInteger k)))) [0 .. bound]+ is <- mapM (intIs env r . toInteger) [0 .. bound]+ -- A visible occurrence (see 'occursAt') is a real one, so only the+ -- existence of the occurrence found needs it to be visible: its end+ -- within the bound.+ emit env ([litNeg (seFits ss), litNeg valid, notFound] <> is)+ forM_ (zip3 [0 :: Int ..] occ from) $ \(k, o, f) -> do+ visible <- leAtom ar (linSub (linAdd (seLen sp) (linConst (toInteger k))) (linConst (toInteger bound)))+ emit env [litNeg (is !! k), litNeg visible, o]+ -- No earlier occurrence at or after i.+ forM_ (take k (zip occ from)) $ \(o', f') ->+ emit env [litNeg (is !! k), litNeg f', litNeg o']+ emit env [litNeg valid, litNeg notFound, litNeg f, litNeg o]+ pure r++-- | @x = to_int(s)@: the decimal value of a non-empty string of digits, or+-- -1.+stringToInt :: Env -> SE -> LinExpr -> Enc ()+stringToInt env se x = liftIO $ do+ let ar = envArith env+ c = envCircuit env+ chars = seChars se+ fits = seFits se+ code = BB.constBits c charWidth . toInteger . fromEnum+ atLeastM1 <- leAtom ar (linSub (linConst (-1)) x)+ minus1 <- leAtom ar (linAdd x (linConst 1))+ emit env [atLeastM1]+ digits <- forM chars $ \ch -> do+ lo <- BB.bvULe c (code '0') ch+ hi <- BB.bvULe c ch (code '9')+ BB.andG c lo hi+ allDigits <- BB.andN c =<< zipWithM (BB.orG c) (seLe se) digits+ emit env [litNeg (seLe se !! 0), minus1]+ emit env [litNeg fits, allDigits, minus1]+ -- The value of each digit.+ values <- forM chars $ \ch -> do+ d <- linVar <$> freshVar ar+ lo <- leAtom ar (linScale (-1) d)+ hi <- leAtom ar (linSub d (linConst 9))+ emit env [lo]+ emit env [hi]+ forM_ [0 .. 9 :: Integer] $ \v -> do+ isV <- BB.bvEq c ch (BB.constBits c charWidth (48 + v))+ equalUnder env [isV] d (linConst v)+ pure d+ lens <- lenIs env se+ forM_ (zip [1 ..] (drop 1 lens)) $ \(k, isK) -> do+ let value = foldr linAdd (linConst 0) [linScale (10 ^ (k - 1 - j)) d | (j, d) <- zip [0 :: Int ..] (take k values)]+ equalUnder env [fits, isK, allDigits] x value++-- | @from_int(n)@: the decimal digits of @n@ without leading zeros, or the+-- empty string when @n@ is negative.+stringFromInt :: Env -> Int -> Int -> Enc SE+stringFromInt env t n = do+ ln <- linearize env n+ r <- liftIO (freshSE env t)+ x <- liftIO (linVar <$> freshVar (envArith env))+ stringToInt env r x+ liftIO $ do+ let ar = envArith env+ c = envCircuit env+ negative <- leAtom ar (linAdd ln (linConst 1))+ emptyR <- leAtom ar (seLen r)+ emit env [litNeg negative, emptyR]+ equalUnder env [litNeg negative] x ln+ zero <- BB.bvEq c (seChars r !! 0) (BB.constBits c charWidth 48)+ emit env [negative, seLe r !! 1, litNeg zero]+ pure r++-- | Lexicographic order @a < b@ on code points.+stringLess :: Env -> Int -> Int -> Enc Lit+stringLess env a b = do+ sa <- stringEnc env a+ sb <- stringEnc env b+ liftIO $ do+ let c = envCircuit env+ positions = zip3 (seChars sa) (seChars sb) (zip (seLe sa) (seLe sb))+ -- less from position i on, given equal characters before i+ step (ca, cb, (aEnds, bEnds)) later = do+ ended <- BB.andG c aEnds (litNeg bEnds)+ lt <- BB.bvULt c ca cb+ eq <- BB.bvEq c ca cb+ tieBreak <- BB.andG c eq later+ byChar <- BB.orG c lt tieBreak+ both <- BB.andN c [litNeg aEnds, litNeg bEnds, byChar]+ BB.orG c ended both+ lt0 <- foldrM' step (BB.cFalse c) positions+ -- The comparison of the visible characters decides the order unless+ -- both strings are longer than the bound and agree on their visible+ -- characters; then neither order is visible.+ known <- readIORef (envLess env)+ case Map.lookup (a, b) known of+ Just l -> pure l+ Nothing -> do+ l <- posLit <$> newVar (envSolver env)+ emit env [litNeg lt0, l]+ emit env [litNeg (seFits sa), litNeg l, lt0]+ emit env [litNeg (seFits sb), litNeg l, lt0]+ -- Asymmetry.+ forM_ (Map.lookup (b, a) known) $ \l' -> emit env [litNeg l, litNeg l']+ modifyIORef' (envLess env) (Map.insert (a, b) l)+ pure l+ where+ foldrM' f z = \case+ [] -> pure z+ (x : xs) -> foldrM' f z xs >>= f x++isSurrogate :: Int -> Bool+isSurrogate c = c >= 0xD800 && c <= 0xDFFF++-- | Code points of a string term in an assignment.+stringCodes :: Env -> (Lit -> IO Bool) -> SE -> IO [Int]+stringCodes env val se = do+ len <- floor <$> linValue (envArith env) (seLen se)+ codes <- mapM (BB.bitsValue val) (take (min len (envStrBound env)) (seChars se))+ pure (map fromInteger codes)++-------------------------------------------------------------------------------+-- Linear arithmetic++-- | Linear form of an integer term. Non-arithmetic subterms become simplex+-- variables; non-linear terms are not supported.+linearize :: Env -> Int -> Enc LinExpr+linearize env t = do+ cache <- liftIO (readIORef (envLin env))+ case IntMap.lookup t cache of+ Just l -> pure l+ Nothing -> do+ l <- compute+ liftIO (modifyIORef' (envLin env) (IntMap.insert t l))+ pure l+ where+ ar = envArith env+ TermNode op args _ = nodeOf env t+ sub = linearize env . unTermId+ isConst (LinExpr cs _) = IntMap.null cs+ compute = case (op, args) of+ (IntConst n, []) -> pure (linConst n)+ (Add, _) -> foldr1 linAdd <$> mapM sub args+ (Sub, a : rest) -> do+ la <- sub a+ lrest <- mapM sub rest+ pure (foldl linSub la lrest)+ (Neg, [a]) -> linScale (-1) <$> sub a+ (Mul, _) -> do+ ls <- mapM sub args+ case filter (not . isConst) ls of+ [] -> pure (linConst (product (map linConstant ls)))+ [l] -> pure (linScale (product [linConstant c | c <- ls, isConst c]) l)+ _ -> throwError "non-linear multiplication is not supported"+ (IntDiv, [a, d]) -> divMod' a d fst+ (IntMod, [a, d]) -> divMod' a d snd+ _+ | op `elem` stringOps+ , Just (VInt n) <- groundValue env t ->+ pure (linConst n)+ (StrLen, [a]) -> seLen <$> stringEnc env (unTermId a)+ (StrIndexOf, [a, b, i]) -> stringIndexOf env t (unTermId a) (unTermId b) (unTermId i)+ (StrToInt, [a]) -> do+ se <- stringEnc env (unTermId a)+ x <- liftIO (linVar <$> termVar ar t)+ stringToInt env se x+ pure x+ (Abs, [a]) -> do+ la <- sub a+ x <- liftIO (linVar <$> termVar ar t)+ liftIO $ do+ nonNeg <- leAtom ar (linScale (-1) la)+ p1 <- leAtom ar (linSub x la)+ p2 <- leAtom ar (linSub la x)+ n1 <- leAtom ar (linAdd x la)+ n2 <- leAtom ar (linScale (-1) (linAdd x la))+ mapM_ (queueClause ar) [[litNeg nonNeg, p1], [litNeg nonNeg, p2], [nonNeg, n1], [nonNeg, n2]]+ pure x+ _ -> atomic++ -- Uninterpreted constants and applications, ite, division by zero:+ -- a simplex variable, linked to congruence closure when needed.+ atomic = do+ case (op, args) of+ (Uninterpreted _, []) -> pure ()+ _ -> registerTerm env (TermId t)+ liftIO (linVar <$> termVar ar t)++ -- q = div a k and r = mod a k satisfy a = k q + r and 0 <= r <= |k| - 1.+ divMod' a d pick = do+ ld <- sub d+ if not (isConst ld)+ then throwError "division by a non-constant term is not supported"+ else case linConstant ld of+ 0 -> atomic+ k -> do+ la <- sub a+ known <- liftIO (Map.lookup (unTermId a, k) <$> readIORef (envDivMod env))+ case known of+ Just qr -> pure (pick qr)+ Nothing -> do+ q <- liftIO (linVar <$> freshVar ar)+ r <- liftIO (linVar <$> freshVar ar)+ let def = linSub la (linAdd (linScale k q) r)+ liftIO $ do+ facts <-+ sequence+ [ leAtom ar def+ , leAtom ar (linScale (-1) def)+ , leAtom ar (linScale (-1) r)+ , leAtom ar (linSub r (linConst (abs k - 1)))+ ]+ mapM_ (\l -> queueClause ar [l]) facts+ modifyIORef' (envDivMod env) (Map.insert (unTermId a, k) (q, r))+ pure (pick (q, r))++-------------------------------------------------------------------------------+-- Theory combination++-- | EUF and LIA hooks, plus model-based combination at final check. Each+-- theory is installed only when the problem uses it.+combinedHooks :: Env -> Bool -> Bool -> TheoryHooks+combinedHooks env useEUF useArith =+ TheoryHooks+ { thNewLevel = mapM_ thNewLevel hooks+ , thBacktrack = \l -> mapM_ (`thBacktrack` l) hooks+ , thAssert = \l -> mapM_ (`thAssert` l) hooks+ , thPropagate = firstNonOk (deliver : map thPropagate hooks)+ , thFinalCheck =+ firstNonOk (deliver : map thFinalCheck hooks <> [arrayCheck env | useEUF] <> [combine env | useEUF])+ }+ where+ -- Clauses created during search (bit-vector equality axioms and gates).+ deliver = do+ ls <- readIORef (envPending env)+ writeIORef (envPending env) []+ pure (if null ls then TheoryOk else TheoryLemmas (reverse ls))+ hooks = [eufHooks (envEUF env) | useEUF] <> [arithHooks (envArith env) | useArith]+ firstNonOk = \case+ [] -> pure TheoryOk+ (c : cs) ->+ c >>= \case+ TheoryOk -> firstNonOk cs+ r -> pure r++-- | Make congruence closure agree with arithmetic and bit-vectors on the+-- shared terms. Terms in one class with different values get their equality+-- propagated; terms with the same value in different classes get an+-- equality atom, which the SAT solver decides (trying true first).+combine :: Env -> IO TheoryResult+combine env = do+ shared <- IntSet.toList <$> readIORef (envShared env)+ values <- theoryValues env (litTrueNow (envSolver env))+ info <- forM shared $ \t -> do+ c <- currentClass (envEUF env) t+ pure (t, values IntMap.! t, c)+ -- Same class, different values.+ let byClass = Map.fromListWith (flip (<>)) [(c, [(t, v)]) | (t, v, c) <- info]+ splits =+ [ (t0, t)+ | ((t0, v0) : rest) <- Map.elems byClass+ , (t, v) <- rest+ , v /= v0+ ]+ -- Same value, different classes: one representative term per class.+ byValue = Map.fromListWith (flip (<>)) [(v, [(c, t)]) | (t, v, c) <- info]+ merges =+ [ (t0, t)+ | group <- Map.elems byValue+ , ((_, t0) : others) <- [Map.toList (Map.fromListWith (\_ old -> old) group)]+ , (_, t) <- others+ ]+ propagated <- forM splits $ \(a, b) -> do+ eq <- mkEqLit env a b+ expl <- explainEqual (envEUF env) a b+ pure (permanent (eq : map litNeg expl))+ -- Arrays are compared once the other values are stable.+ arrayMerges <- if null splits && null merges then arrayCollisions env values else pure []+ forM_ (merges <> arrayMerges) $ \(a, b) -> do+ eq <- mkEqLit env a b+ setPhase (envSolver env) (litVar eq) (not (litSign eq))+ axioms <- drainLemmas env+ pure $ case axioms <> propagated of+ [] -> TheoryOk+ lemmas -> TheoryLemmas lemmas++-- | Classes of shared arrays whose values in the current candidate model+-- coincide: one pair per class besides the first of each value. Their+-- equality is decided like the merges of shared terms (an array equality+-- atom carries the extensionality axiom, so deciding it false makes the+-- values differ). Other arrays may share values freely: only their reads+-- matter.+arrayCollisions :: Env -> IntMap Value -> IO [(Int, Int)]+arrayCollisions env values = do+ shared <- IntSet.toList <$> readIORef (axShared (envArrays env))+ if null shared+ then pure []+ else do+ nodes <- registeredNodes (envEUF env)+ classes <- currentClasses (envEUF env)+ defaults <- readIORef (axDefault (envArrays env))+ pure $ case classValues env values nodes defaults classes of+ Left _ -> []+ Right vals ->+ let reps = IntSet.toList (IntSet.fromList [ciRepr (classes IntMap.! t) | t <- shared])+ groups = Map.fromListWith (flip (<>)) [((sortOfT env r, vals IntMap.! r), [r]) | r <- reps]+ in [(r0, r) | (r0 : rest) <- Map.elems groups, r <- rest]++-- | Value of a literal in the current (complete) assignment.+litTrueNow :: Solver -> Lit -> IO Bool+litTrueNow s l = (== LTrue) <$> litValueNow s l++-- | Values of the integer and bit-vector terms: from the arithmetic model+-- and from the assignment of the bits.+theoryValues :: Env -> (Lit -> IO Bool) -> IO (IntMap Value)+theoryValues env val = do+ lins <- readIORef (envLin env)+ ints <- traverse (fmap (VInt . floorR) . linValue (envArith env)) lins+ bits <- readIORef (envBits env)+ bvs <- IntMap.traverseWithKey (\t bs -> bitsToValue (sortOfT env t) <$> BB.bitsValue val bs) bits+ strings <- readIORef (envStrings env)+ strs <- traverse (fmap (VString . T.pack . map toEnum) . stringCodes env val) strings+ pure (IntMap.unions [ints, bvs, strs])+ where+ floorR r = numerator r `div` denominator r++-- | The value of the bits of a term of a bit sort.+bitsToValue :: Sort -> Integer -> Value+bitsToValue srt x = case srt of+ FPSort eb sb -> VFP eb sb (F.canonicalize eb sb x)+ RoundingModeSort -> VRM (toEnum (fromInteger (min 4 x)))+ _ -> VBV (bitWidth srt) x++-------------------------------------------------------------------------------+-- Models++buildModel :: Env -> Bool -> IO (Either Text Interpretation)+buildModel env useEUF = do+ boolSyms <- readIORef (envBoolSyms env)+ boolVals <- forM boolSyms $ \(sym, v) -> (,) sym . VBool <$> modelValue (envSolver env) v+ values <- theoryValues env modelLit+ codes <- traverse (stringCodes env modelLit) =<< readIORef (envStrings env)+ internal <- readIORef (axInternal (envArrays env))+ defaults <- readIORef (axDefault (envArrays env))+ let visible sym _ = Set.notMember sym internal+ theoryConsts =+ Map.filterWithKey visible . Map.fromList $+ [ (sym, constInterp v)+ | (t, v) <- IntMap.toList values+ , TermNode (Uninterpreted sym) [] _ <- [nodeOf env t]+ ]+ base = Map.union (Map.fromList [(sym, constInterp val) | (sym, val) <- boolVals]) theoryConsts+ if any (any isSurrogate) codes+ then pure (Left "the model needs a surrogate code point, which has no Text representation")+ else if not useEUF+ then pure (Right emptyInterpretation {interpSymbols = base})+ else+ finalClasses (envEUF env) >>= \case+ Nothing -> pure (Left "internal error: no final EUF state")+ Just classes -> do+ nodes <- registeredNodes (envEUF env)+ pure $ do+ classVal <- classValues env values nodes defaults classes+ let valueOf t = classVal IntMap.! ciRepr (classes IntMap.! t)+ apps =+ [ (sym, map valueOf args, valueOf t)+ | (t, AppNode (Uninterpreted sym) args) <- IntMap.toList nodes+ ]+ tables =+ Map.fromListWith+ Map.union+ [(sym, Map.singleton argVals v) | (sym, argVals, v) <- apps]+ funs =+ Map.mapWithKey+ (\sym table -> FunInterp table (defaultValue (symResult sym)))+ (Map.filterWithKey visible tables)+ byZero o =+ FunInterp+ (Map.fromList [([valueOf a], valueOf t) | (t, AppNode o' [a, _]) <- IntMap.toList nodes, o' == o])+ (VInt 0)+ pure+ emptyInterpretation+ { interpSymbols = Map.union funs base+ , interpDivByZero = byZero IntDiv+ , interpModByZero = byZero IntMod+ , interpUnspecified =+ Map.fromList+ [ ((o, map valueOf as), valueOf t)+ | (t, AppNode o as) <- IntMap.toList nodes+ , unspecifiedOp o+ ]+ }+ where+ modelLit l = (/= litSign l) <$> modelValue (envSolver env) (litVar l)++-- | Pick a value for every congruence class: the literal it contains, or a+-- fresh value distinct from every other class. Arrays take the values of+-- their reads over their default (see @arrayTerm@).+classValues ::+ Env -> IntMap Value -> IntMap NodeKind -> IntMap Int -> IntMap ClassInfo -> Either Text (IntMap Value)+classValues env theoryVals nodes defaults classes = do+ scalars <- scalarValues env theoryVals (IntMap.filter (not . isCompound . sortOfT env . ciRepr) classes)+ let repOf t = ciRepr (classes IntMap.! t)+ readsOf =+ IntMap.fromListWith (<>) [(repOf x, [(j, sel)]) | (sel, AppNode Select [x, j]) <- IntMap.toList nodes]+ defaultOf = IntMap.fromList [(repOf a, repOf d) | (a, d) <- IntMap.toList defaults]+ arrays =+ LazyMap.fromList+ [ (r, arrayValue r idx el)+ | ci <- IntMap.elems classes+ , let r = ciRepr ci+ , ArraySort idx el <- [sortOfT env r]+ ]+ -- Every record class has a constructor application (see+ -- @recordTerm@), whose arguments give the fields.+ constructors =+ IntMap.fromList [(repOf m, as) | (m, AppNode (RecordMk _) as) <- IntMap.toList nodes]+ records =+ LazyMap.fromList+ [ (r, recordValue r (map fst fs))+ | ci <- IntMap.elems classes+ , let r = ciRepr ci+ , RecordSort fs <- [sortOfT env r]+ ]+ recordValue r names = case IntMap.lookup r constructors of+ Just as -> VRecord (zip names [allVals IntMap.! repOf a | a <- as])+ Nothing -> error "hsmt: record class without a constructor application"+ -- Lazy: arrays and records may contain other arrays and records, of+ -- smaller sorts.+ allVals = LazyMap.unions [scalars, arrays, records]+ arrayValue r idx el =+ mkArray+ idx+ (Map.fromList [(allVals IntMap.! repOf j, allVals IntMap.! repOf sel) | (j, sel) <- IntMap.findWithDefault [] r readsOf])+ (maybe (defaultValue el) (allVals IntMap.!) (IntMap.lookup r defaultOf))+ pure allVals+ where+ isCompound = \case+ ArraySort _ _ -> True+ RecordSort _ -> True+ _ -> False++scalarValues :: Env -> IntMap Value -> IntMap ClassInfo -> Either Text (IntMap Value)+scalarValues env theoryVals classes = do+ let reps = IntMap.fromList [(ciRepr ci, ci) | ci <- IntMap.elems classes]+ constVal c = literalValue (nodeOp (nodeOf env c))+ used = Set.fromList [constVal c | ci <- IntMap.elems reps, Just c <- [ciConst ci]]+ step (acc, usedSoFar, counter) (r, ci) = do+ (v, used', counter') <- case (ciConst ci, IntMap.lookup r theoryVals) of+ -- Integer and bit-vector classes take their value from their+ -- theory.+ (_, Just tv) -> Right (tv, usedSoFar, counter)+ (Just c, _) -> Right (constVal c, usedSoFar, counter)+ (Nothing, _) -> freshValue (sortOfT env r) usedSoFar counter+ pure (IntMap.insert r v acc, used', counter')+ (vals, _, _) <- foldlM step (IntMap.empty, used, 0 :: Int) (IntMap.toList reps)+ pure vals+ where+ foldlM f z xs = foldl' (\m x -> m >>= \a -> f a x) (Right z) xs++literalValue :: Op -> Value+literalValue = \case+ BoolConst b -> VBool b+ IntConst n -> VInt n+ StrConst str -> VString str+ BVConst w x -> VBV w x+ FPConst eb sb x -> VFP eb sb x+ RMConst r -> VRM r+ op -> error ("hsmt: not a literal: " <> show op)++-- | A value of the sort not used so far.+freshValue :: Sort -> Set.Set Value -> Int -> Either Text (Value, Set.Set Value, Int)+freshValue sort used counter = case candidates of+ (v : _) -> Right (v, Set.insert v used, counter + 1)+ [] -> Left ("not enough values in sort " <> prettySort sort <> " for the model")+ where+ candidates = filter (`Set.notMember` used) $ case sort of+ IntSort -> map VInt ([0 ..] >>= \n -> if n == 0 then [0] else [n, negate n])+ StringSort -> map (VString . T.pack . ("s" <>) . show) [counter ..]+ BVSort w -> [VBV w x | x <- [0 .. bvMask w]]+ FPSort eb sb ->+ [VFP eb sb x | x <- [0 .. bvMask (eb + sb)], not (F.isNaNBits eb sb x) || x == F.canonicalNaN eb sb]+ RoundingModeSort -> map VRM F.allRoundingModes+ UninterpretedSort _ -> [VUninterp sort k | k <- [counter ..]]+ BoolSort -> [VBool False, VBool True]+ _ -> []
+ src/HSMT/SMTLib/Parser.hs view
@@ -0,0 +1,565 @@+{-# LANGUAGE ViewPatterns #-}++-- | A parser for the subset of SMT-LIB 2.6 scripts that hsmt supports.+--+-- Scripts are read as S-expressions and then elaborated into 'Command's+-- whose terms are sort-checked core expressions. Macros introduced by+-- @define-fun@ and @define-const@, local bindings of @let@ and sort+-- abbreviations of @define-sort@ are expanded at their use sites.+-- Single-constructor datatypes are read as records. Declarations are+-- scoped: @pop@ removes the declarations made since the matching @push@.+--+-- Regular expressions are supported as ground terms: symbols of sort+-- @RegLan@ cannot be declared.+--+-- Not supported: quantifiers, real arithmetic, parametric sorts and+-- multi-constructor datatypes.+module HSMT.SMTLib.Parser+ ( -- * Scripts+ parseScript+ -- * Command by command+ , ParseState+ , initialParseState+ , parseCommand+ , parseTerm+ , parseSort+ , declareConstants+ -- * S-expressions+ , SExpr (..)+ , parseSExprs+ , parseSExprsPartial+ , showS+ ) where++import Control.Monad (foldM, unless, when)+import Data.Char (chr, isDigit, isHexDigit, isSpace)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as T+import Numeric (readHex)++import HSMT.Core.Expr+import HSMT.Core.Float (RoundingMode (..))+import qualified HSMT.Core.Float as F+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Typing+import HSMT.SMTLib.Syntax++-------------------------------------------------------------------------------+-- S-expressions++-- | A raw S-expression, before elaboration into commands.+data SExpr+ = SSym Text+ -- ^ Simple or quoted symbol (quotes removed).+ | SKey Text+ -- ^ Keyword, without the leading colon.+ | SNum Integer+ -- ^ Decimal numeral.+ | SBin Text+ -- ^ Binary literal digits (after @#b@).+ | SHex Text+ -- ^ Hexadecimal literal digits (after @#x@).+ | SStr Text+ -- ^ String literal, already unescaped.+ | SList [SExpr]+ -- ^ Parenthesized list.+ deriving (Eq, Show)++-- | Read a sequence of S-expressions.+parseSExprs :: Text -> Either Text [SExpr]+parseSExprs t = case parseSExprsPartial t of+ (es, Nothing) -> Right es+ (_, Just err) -> Left err++-- | Read S-expressions up to the first syntax error, returning the+-- expressions before it and the error, if any.+parseSExprsPartial :: Text -> ([SExpr], Maybe Text)+parseSExprsPartial = go []+ where+ go acc t = case skip t of+ t' | T.null t' -> (reverse acc, Nothing)+ t' -> case sexpr t' of+ Left err -> (reverse acc, Just err)+ Right (e, rest) -> go (e : acc) rest++ -- Whitespace and comments.+ skip t =+ let t' = T.dropWhile isSpace t+ in case T.uncons t' of+ Just (';', r) -> skip (T.dropWhile (/= '\n') r)+ _ -> t'++ sexpr t = case T.uncons t of+ Just ('(', r) -> list [] (skip r)+ Just (')', _) -> Left "unexpected ')'"+ Just ('|', r) ->+ let (s, r') = T.break (== '|') r+ in if T.null r' then Left "unterminated quoted symbol" else Right (SSym s, T.drop 1 r')+ Just ('"', r) -> stringLit [] r+ Just (':', r) -> let (k, r') = token r in Right (SKey k, r')+ Just ('#', r) -> case T.uncons r of+ Just ('b', r') -> let (d, r'') = token r' in Right (SBin d, r'')+ Just ('x', r') -> let (d, r'') = token r' in Right (SHex d, r'')+ _ -> Left "invalid # literal"+ Just _ ->+ let (tok, r) = token t+ in if T.all isDigit tok+ then Right (SNum (read (T.unpack tok)), r)+ else Right (SSym tok, r)+ Nothing -> Left "unexpected end of input"++ list acc t = case T.uncons t of+ Just (')', r) -> Right (SList (reverse acc), r)+ Nothing -> Left "unbalanced parentheses"+ _ -> do+ (e, r) <- sexpr t+ list (e : acc) (skip r)++ token = T.break (\c -> isSpace c || c `elem` ("()|\";" :: String))++ stringLit acc t =+ let (chunk, r) = T.break (== '"') t+ in case T.uncons r of+ Nothing -> Left "unterminated string literal"+ Just (_, r') -> case T.uncons r' of+ Just ('"', r'') -> stringLit (acc <> [chunk, "\""]) r''+ _ -> do+ s <- unescape (T.concat (acc <> [chunk]))+ Right (SStr s, r')++-- | Resolve the @\\u{d...}@ and @\\udddd@ escapes of SMT-LIB 2.6.+unescape :: Text -> Either Text Text+unescape t = case T.breakOn "\\u" t of+ (pre, rest)+ | T.null rest -> Right pre+ | otherwise -> do+ let body = T.drop 2 rest+ (c, rest') <- case T.uncons body of+ Just ('{', r) ->+ let (digits, r') = T.break (== '}') r+ in if T.null r' || T.null digits || T.length digits > 5 || not (T.all isHexDigit digits)+ then Right ('\\', T.drop 1 rest)+ else Right (hexChar digits, T.drop 1 r')+ _ ->+ let digits = T.take 4 body+ in if T.length digits == 4 && T.all isHexDigit digits+ then Right (hexChar digits, T.drop 4 body)+ else Right ('\\', T.drop 1 rest)+ ((pre <> T.singleton c) <>) <$> unescape rest'+ where+ hexChar ds = case readHex (T.unpack ds) of+ [(n, "")] -> chr n+ _ -> '\\'++-------------------------------------------------------------------------------+-- Elaboration++data Env = Env+ { envSorts :: Map Text Sort+ , envFuns :: Map Text Symbol+ , envMacros :: Map Text ([Symbol], Expr)+ , envCtors :: Map Text [Text]+ -- ^ Record constructors and their field names.+ , envSelectors :: Map Text Text+ -- ^ Record selectors and their field names.+ , envLocals :: Map Text (Expr, Sort)+ -- ^ Variables bound by @let@.+ }++emptyEnv :: Env+emptyEnv = Env Map.empty Map.empty Map.empty Map.empty Map.empty Map.empty++-- | The declarations in scope, and those of the enclosing assertion levels+-- (innermost first), restored by @pop@.+data ParseState = ParseState Env [Env]++-- | The state at the start of a script: no declarations, no open+-- assertion levels.+initialParseState :: ParseState+initialParseState = ParseState emptyEnv []++type P a = Either Text a++-- | Parse and elaborate a script. The first error aborts the parse.+parseScript :: Text -> Either Text [Command]+parseScript txt = do+ ses <- parseSExprs txt+ (_, cmds) <- foldM step (initialParseState, []) ses+ pure (reverse cmds)+ where+ step (st, acc) se = do+ (st', cs) <- parseCommand st se+ pure (st', reverse cs <> acc)++-- | Elaborate one command. An error leaves the state unchanged (the caller+-- keeps the old one), as SMT-LIB asks of solvers that continue after an+-- error.+parseCommand :: ParseState -> SExpr -> Either Text (ParseState, [Command])+parseCommand st@(ParseState env saved) se =+ either (Left . (<> (" in " <> showS se))) Right $ case se of+ SList [SSym "push"] -> push 1+ SList [SSym "push", SNum k] -> push k+ SList [SSym "pop"] -> pop 1+ SList [SSym "pop", SNum k] -> pop k+ SList [SSym "reset"] -> Right (initialParseState, [Reset])+ SList [SSym "reset-assertions"] -> Right (initialParseState, [ResetAssertions])+ _ -> do+ (env', cs) <- command env se+ Right (ParseState env' saved, cs)+ where+ push k = Right (ParseState env (replicate (fromInteger k) env <> saved), [Push (fromInteger k)])+ pop k+ | k == 0 = Right (st, [Pop 0])+ | fromInteger k <= length saved =+ Right (ParseState (saved !! (fromInteger k - 1)) (drop (fromInteger k) saved), [Pop (fromInteger k)])+ | otherwise = Left "pop: not enough assertion levels"++-- | Elaborate a term in the declarations of the state, returning it with+-- its sort.+parseTerm :: ParseState -> SExpr -> Either Text (Expr, Sort)+parseTerm (ParseState env _) = term env++-- | Elaborate a sort in the declarations of the state.+parseSort :: ParseState -> SExpr -> Either Text Sort+parseSort (ParseState env _) = sortOfS env++-- | Make nullary symbols known to later elaborations, shadowing earlier+-- symbols of the same names.+declareConstants :: [Symbol] -> ParseState -> ParseState+declareConstants syms (ParseState env saved) =+ ParseState+ env+ { envFuns = Map.union (Map.fromList [(symName s, s) | s <- syms]) (envFuns env)+ , envMacros = foldr (Map.delete . symName) (envMacros env) syms+ }+ saved++command :: Env -> SExpr -> P (Env, [Command])+command env = \case+ SList [SSym "set-logic", SSym l] -> ok [SetLogic l]+ SList [SSym "set-option", SKey o, v] -> ok [SetOption o (showS v)]+ SList [SSym "set-info", SKey o, v] -> ok [SetInfo o (showS v)]+ SList [SSym "set-info", SKey o] -> ok [SetInfo o ""]+ SList [SSym "declare-sort", SSym n] -> declareSort n+ SList [SSym "declare-sort", SSym n, SNum 0] -> declareSort n+ SList [SSym "declare-const", SSym n, s] -> declareFun n [] s+ SList [SSym "declare-fun", SSym n, SList as, s] -> declareFun n as s+ SList [SSym "define-fun", SSym n, SList ps, s, body] -> do+ fresh n+ result <- sortOfS env s+ params <- traverse param ps+ let scope = Map.fromList [(symName p, p) | p <- params]+ (e, s') <- term env {envFuns = Map.union scope (envFuns env)} body+ unless (s' == result) $ Left "body sort does not match the declared sort"+ let sym = Symbol n (map symResult params) result+ pure (env {envMacros = Map.insert n (params, e) (envMacros env)}, [DefineFun sym params e])+ SList [SSym "declare-datatypes", SList [SList [SSym n, SNum 0]], SList [SList [SList (SSym c : fields)]]] ->+ declareRecord n c fields+ SList [SSym "declare-datatype", SSym n, SList [SList (SSym c : fields)]] ->+ declareRecord n c fields+ SList [SSym "assert", SList [SSym "!", t, SKey "named", SSym n]] -> do+ fresh n+ (e, s) <- term env t+ unless (s == BoolSort) $ Left "assertion is not Boolean"+ -- The name also stands for the term, like a nullary macro.+ pure (env {envMacros = Map.insert n ([], e) (envMacros env)}, [AssertNamed n e])+ SList [SSym "assert", t] -> do+ (e, s) <- term env t+ unless (s == BoolSort) $ Left "assertion is not Boolean"+ ok [Assert e]+ SList [SSym "define-const", SSym n, s, body] -> do+ fresh n+ result <- sortOfS env s+ (e, s') <- term env body+ unless (s' == result) $ Left "body sort does not match the declared sort"+ pure (env {envMacros = Map.insert n ([], e) (envMacros env)}, [DefineFun (Symbol n [] result) [] e])+ SList [SSym "define-sort", SSym n, SList [], s] -> do+ when (Map.member n (envSorts env)) $ Left ("sort already declared: " <> n)+ s' <- sortOfS env s+ pure (env {envSorts = Map.insert n s' (envSorts env)}, [])+ SList [SSym "define-sort", SSym _, SList _, _] -> Left "parametric sorts are not supported"+ SList [SSym "check-sat"] -> ok [CheckSat]+ SList [SSym "check-sat-assuming", SList ts] -> do+ es <- traverse (term env) ts+ unless (all ((== BoolSort) . snd) es) $ Left "assumption is not Boolean"+ ok [CheckSatAssuming (map fst es)]+ SList [SSym "get-model"] -> ok [GetModel]+ SList [SSym "get-value", SList ts@(_ : _)] -> do+ es <- traverse (term env) ts+ ok [GetValue (map fst es)]+ SList [SSym "get-assertions"] -> ok [GetAssertions]+ SList [SSym "get-info", SKey k] -> ok [GetInfo k]+ SList [SSym "get-option", SKey k] -> ok [GetOption k]+ SList [SSym "get-unsat-core"] -> ok [GetUnsatCore]+ SList [SSym "echo", SStr s] -> ok [Echo s]+ SList [SSym "exit"] -> ok [Exit]+ SList (SSym c : _) -> Left ("unsupported command: " <> c)+ _ -> Left "malformed command"+ where+ ok cs = Right (env, cs)++ fresh n =+ when (Map.member n (envFuns env) || Map.member n (envMacros env)) $+ Left ("symbol already declared: " <> n)++ declareSort n = do+ when (Map.member n (envSorts env)) $ Left ("sort already declared: " <> n)+ pure (env {envSorts = Map.insert n (UninterpretedSort n) (envSorts env)}, [DeclareSort n])++ declareFun n as s = do+ fresh n+ args <- traverse (sortOfS env) as+ result <- sortOfS env s+ when (RegLanSort `elem` (result : args)) $ Left "symbols of sort RegLan are not supported"+ let sym = Symbol n args result+ pure (env {envFuns = Map.insert n sym (envFuns env)}, [DeclareFun sym])++ param = \case+ SList [SSym p, s] -> Symbol p [] <$> sortOfS env s+ _ -> Left "malformed parameter"++ -- Selectors named "<datatype>.<field>" (as produced by the printer) give+ -- the field name; other selectors are used as field names verbatim.+ declareRecord n c fields = do+ when (Map.member n (envSorts env)) $ Left ("sort already declared: " <> n)+ sels <- traverse field fields+ let fieldName sel = maybe sel id (T.stripPrefix (n <> ".") sel)+ fs = [(fieldName sel, s) | (sel, s) <- sels]+ sort = RecordSort fs+ pure+ ( env+ { envSorts = Map.insert n sort (envSorts env)+ , envCtors = Map.insert c (map fst fs) (envCtors env)+ , envSelectors =+ Map.union (Map.fromList [(sel, fieldName sel) | (sel, _) <- sels]) (envSelectors env)+ }+ , [DeclareRecord fs]+ )++ field = \case+ SList [SSym sel, s] -> (,) sel <$> sortOfS env s+ _ -> Left "malformed datatype field"++sortOfS :: Env -> SExpr -> P Sort+sortOfS env = \case+ SSym "Bool" -> pure BoolSort+ SSym "Int" -> pure IntSort+ SSym "String" -> pure StringSort+ SSym n | Just s <- Map.lookup n (envSorts env) -> pure s+ SList [SSym "_", SSym "BitVec", SNum w] | w > 0 -> pure (BVSort (fromInteger w))+ SList [SSym "Array", i, e] -> ArraySort <$> sortOfS env i <*> sortOfS env e+ SList [SSym "_", SSym "FloatingPoint", SNum eb, SNum sb]+ | eb >= 2 && sb >= 2 -> pure (FPSort (fromInteger eb) (fromInteger sb))+ SSym "Float16" -> pure (FPSort 5 11)+ SSym "Float32" -> pure (FPSort 8 24)+ SSym "Float64" -> pure (FPSort 11 53)+ SSym "Float128" -> pure (FPSort 15 113)+ SSym "RoundingMode" -> pure RoundingModeSort+ SSym "RegLan" -> pure RegLanSort+ s -> Left ("unknown sort: " <> showS s)++sortOfE :: Expr -> P Sort+sortOfE e = either (Left . seMessage) Right (sortOf e)++-- | Elaborate a term, returning it with its sort.+term :: Env -> SExpr -> P (Expr, Sort)+term env = \case+ SNum n -> typed (IntConst n) []+ SBin ds+ | not (T.null ds) && T.all (`elem` ['0', '1']) ds ->+ typed (BVConst (T.length ds) (T.foldl' (\a c -> 2 * a + (if c == '1' then 1 else 0)) 0 ds)) []+ SHex ds+ | [(v, "")] <- readHex (T.unpack ds), not (T.null ds) ->+ typed (BVConst (4 * T.length ds) v) []+ SStr s -> typed (StrConst s) []+ SSym "true" -> typed (BoolConst True) []+ SSym "false" -> typed (BoolConst False) []+ SSym n | Just rm <- lookup n roundingModes -> typed (RMConst rm) []+ SSym n -> applyName n []+ SList [SSym "_", SSym bv, SNum w]+ | Just digits <- T.stripPrefix "bv" bv+ , not (T.null digits) && T.all isDigit digits ->+ typed (BVConst (fromInteger w) (read (T.unpack digits))) []+ -- Floating-point special values.+ SList [SSym "_", SSym special, SNum eb, SNum sb]+ | Just v <- lookup special fpSpecials+ , eb >= 2 && sb >= 2 ->+ let (e, s) = (fromInteger eb, fromInteger sb)+ in typed (FPConst e s (F.encode e s v)) []+ -- A floating-point literal from binary fields.+ SList [SSym "fp", bitsOf -> Just sg, bitsOf -> Just ex, bitsOf -> Just sig]+ | T.length sg == 1 && T.length ex >= 2 && T.length sig >= 1 ->+ let (e, s) = (T.length ex, T.length sig + 1)+ in typed (FPConst e s (F.fpFromFields e s (binValue sg) (binValue ex) (binValue sig))) []+ SList (SList [SSym "_", SSym ix, SNum a, SNum b] : args@(_ : _))+ | ix == "to_fp" -> traverse (term env) args >>= typed (ToFP (fromInteger a) (fromInteger b))+ | ix == "to_fp_unsigned" -> traverse (term env) args >>= typed (ToFPUnsigned (fromInteger a) (fromInteger b))+ SList (SList [SSym "_", SSym "re.loop", SNum i, SNum j] : args@(_ : _)) ->+ traverse (term env) args >>= typed (ReLoop (fromInteger i) (fromInteger j))+ SList (SList [SSym "_", SSym ix, SNum w] : args@(_ : _))+ | ix == "re.^" -> traverse (term env) args >>= typed (RePower (fromInteger w))+ | ix == "fp.to_ubv" -> traverse (term env) args >>= typed (FPToUBV (fromInteger w))+ | ix == "fp.to_sbv" -> traverse (term env) args >>= typed (FPToSBV (fromInteger w))+ -- A negative numeral.+ SList [SSym "-", SNum n] -> typed (IntConst (negate n)) []+ SList [SList [SSym "as", SSym "const", s], v] ->+ sortOfS env s >>= \case+ ArraySort i e -> do+ x <- term env v+ unless (snd x == e) $ Left "const array element of the wrong sort"+ typed (ConstArray i) [x]+ _ -> Left "const expects an array sort"+ SList [SList [SSym "_", SSym ix, SNum a, SNum b], t]+ | ix == "extract" -> indexed (BVExtract (fromInteger a) (fromInteger b)) t+ SList [SList [SSym "_", SSym ix, SNum a], t]+ | ix == "zero_extend" -> indexed (BVZeroExtend (fromInteger a)) t+ | ix == "sign_extend" -> indexed (BVSignExtend (fromInteger a)) t+ SList [SSym "let", SList binds@(_ : _), body] -> do+ bound <- traverse binding binds+ term env {envLocals = Map.union (Map.fromList bound) (envLocals env)} body+ SList (SSym q : _) | q `elem` ["forall", "exists"] -> Left "quantifiers are not supported"+ SList [SList [SSym "_", SSym ix, SNum k], t]+ | ix `elem` ["rotate_left", "rotate_right", "repeat"] -> do+ x@(e, s) <- term env t+ case s of+ BVSort w+ | ix == "repeat" ->+ if k < 1 then Left "repeat: the count must be positive" else foldM (\acc _ -> typed BVConcat [acc, x]) x [2 .. k]+ | otherwise ->+ -- Rotating left by i is rotating right by w - i.+ let i = fromInteger (if ix == "rotate_left" then k `mod` toInteger w else (toInteger w - k `mod` toInteger w) `mod` toInteger w)+ in if i == 0+ then pure x+ else do+ hi <- typed (BVExtract (w - 1 - i) 0) [(e, s)]+ lo <- typed (BVExtract (w - 1) (w - i)) [(e, s)]+ typed BVConcat [hi, lo]+ _ -> Left (ix <> " expects a bit-vector")+ -- Annotations other than the names of assertions are ignored.+ SList (SSym "!" : t : _) -> term env t+ SList (SSym f : args) | not (null args) -> traverse (term env) args >>= applyName f+ s -> Left ("malformed term: " <> showS s)+ where+ indexed op t = term env t >>= \x -> typed op [x]++ binding = \case+ SList [SSym x, t] -> (,) x <$> term env t+ _ -> Left "malformed let binding"++ applyName n args+ | null args, Just x <- Map.lookup n (envLocals env) = pure x+ | Just sym <- Map.lookup n (envFuns env) = typed (Uninterpreted sym) args+ | Just (params, body) <- Map.lookup n (envMacros env) = do+ unless (map snd args == map symResult params) $+ Left ("wrong number or sorts of arguments to " <> n)+ let e = substitute (Map.fromList (zip params (map fst args))) body+ (,) e <$> sortOfE e+ | Just names <- Map.lookup n (envCtors env) = typed (RecordMk names) args+ | Just f <- Map.lookup n (envSelectors env) = typed (RecordGet f) args+ | n == "-" && length args == 1 = typed Neg args+ | Just op <- lookup n negated = typed op args >>= \x -> typed BVNot [x]+ | n == "bvcomp" = do+ c <- typed Eq args+ one <- typed (BVConst 1 1) []+ zero <- typed (BVConst 1 0) []+ typed Ite [c, one, zero]+ | Just op <- Map.lookup n builtins = typed op args+ | otherwise = Left ("unknown symbol: " <> n)++typed :: Op -> [(Expr, Sort)] -> P (Expr, Sort)+typed op args = case inferSort op (map snd args) of+ Right s -> Right (App op (map fst args), s)+ Left err -> Left (opName op <> ": " <> seMessage err)++-- | Replace parameters (nullary uninterpreted symbols) by expressions.+substitute :: Map Symbol Expr -> Expr -> Expr+substitute sub = go+ where+ go (App op@(Uninterpreted sym) [])+ | Just e <- Map.lookup sym sub = e+ | otherwise = App op []+ go (App op args) = App op (map go args)++builtins :: Map Text Op+builtins =+ Map.fromList+ [ (opName op, op)+ | op <-+ [ Not, And, Or, Xor, Implies, Ite, Eq, Distinct+ , Add, Sub, Mul, IntDiv, IntMod, Abs, Le, Lt, Ge, Gt+ , BVNot, BVAnd, BVOr, BVXor, BVNeg, BVAdd, BVSub, BVMul+ , BVUDiv, BVURem, BVSDiv, BVSRem, BVSMod, BVShl, BVLShr, BVAShr, BVConcat+ , BVULt, BVULe, BVUGt, BVUGe, BVSLt, BVSLe, BVSGt, BVSGe+ , Select, Store+ , StrConcat, StrLen, StrAt, StrSubstr, StrContains, StrPrefixOf, StrSuffixOf+ , StrIndexOf, StrReplace, StrToInt, StrFromInt, StrLt, StrLe+ , StrToRe, StrInRe, ReNone, ReAll, ReAllChar, ReConcat, ReUnion, ReInter+ , ReStar, RePlus, ReOpt, ReRange, ReComp, ReDiff+ , FPFromFields, FPAbs, FPNeg, FPAdd, FPSub, FPMul, FPDiv, FPFma, FPSqrt, FPRem+ , FPRoundToIntegral, FPMin, FPMax, FPLeq, FPLt, FPGeq, FPGt, FPEq+ , FPIsNormal, FPIsSubnormal, FPIsZero, FPIsInfinite, FPIsNaN, FPIsNegative, FPIsPositive+ ]+ ]+ <> Map.fromList+ [ ("str.to.int", StrToInt)+ , ("int.to.str", StrFromInt)+ , ("str.to.re", StrToRe)+ , ("str.in.re", StrInRe)+ ]++-- | Bit-vector operators defined as the complement of another.+negated :: [(Text, Op)]+negated = [("bvnand", BVAnd), ("bvnor", BVOr), ("bvxnor", BVXor)]++roundingModes :: [(Text, RoundingMode)]+roundingModes =+ [ ("RNE", RNE)+ , ("RNA", RNA)+ , ("RTP", RTP)+ , ("RTN", RTN)+ , ("RTZ", RTZ)+ , ("roundNearestTiesToEven", RNE)+ , ("roundNearestTiesToAway", RNA)+ , ("roundTowardPositive", RTP)+ , ("roundTowardNegative", RTN)+ , ("roundTowardZero", RTZ)+ ]++fpSpecials :: [(Text, F.FP)]+fpSpecials =+ [ ("+zero", F.Zero False)+ , ("-zero", F.Zero True)+ , ("+oo", F.Inf False)+ , ("-oo", F.Inf True)+ , ("NaN", F.NaN)+ ]++-- | The binary digits of a bit-vector literal (hexadecimal digits stand for+-- four bits each, as Z3 prints floating-point fields).+bitsOf :: SExpr -> Maybe Text+bitsOf = \case+ SBin d -> Just d+ SHex d+ | not (T.null d) && T.all isHexDigit d -> Just (T.concatMap hexBits d)+ _ -> Nothing+ where+ hexBits c = case readHex [c] of+ [(n, "")] -> T.pack [if odd (n `div` (2 ^ k) :: Int) then '1' else '0' | k <- [3, 2, 1, 0 :: Int]]+ _ -> "0000"++binValue :: Text -> Integer+binValue = T.foldl' (\a c -> 2 * a + (if c == '1' then 1 else 0)) 0++-- | Render an S-expression back to text, for error messages and options.+showS :: SExpr -> Text+showS = \case+ SSym s -> s+ SKey k -> ":" <> k+ SNum n -> T.pack (show n)+ SBin d -> "#b" <> d+ SHex d -> "#x" <> d+ SStr s -> T.pack (show s)+ SList xs -> "(" <> T.unwords (map showS xs) <> ")"
+ src/HSMT/SMTLib/Printer.hs view
@@ -0,0 +1,394 @@+-- | Rendering of core expressions, sorts, values and scripts in SMT-LIB 2.6+-- syntax.+--+-- Records have no native SMT-LIB counterpart; they are rendered as+-- single-constructor datatypes whose names are derived from the field list+-- (see 'recordName'), so structurally equal record sorts map to the same+-- datatype. Record updates are expanded into a constructor application.+--+-- The output is accepted by Z3 and by 'HSMT.SMTLib.Parser'.+module HSMT.SMTLib.Printer+ ( -- * Scripts+ renderScript+ , renderCommand+ , problemScript+ , declarationsFor+ , modelCommands+ , modelResponse+ -- * Terms+ , renderExpr+ , renderSort+ , renderSymbol+ , renderString+ -- * Records+ , recordName+ , recordConstructor+ , recordSelector+ -- * Values+ , valueExpr+ , valueSort+ ) where++import Data.Char (isAlphaNum, isDigit, ord)+import Data.List (sortOn)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import Numeric (showHex)++import HSMT.Core.Eval+import HSMT.Core.Expr+import HSMT.Core.Op+import qualified HSMT.Core.Regex as R+import HSMT.Core.Sort+import HSMT.Core.Typing+import HSMT.Core.Value+import HSMT.SMTLib.Syntax++-------------------------------------------------------------------------------+-- Scripts++-- | Render a list of commands, one per line.+renderScript :: [Command] -> Text+renderScript = T.unlines . map renderCommand++-- | Render a single command.+renderCommand :: Command -> Text+renderCommand = \case+ SetLogic l -> parens ["set-logic", l]+ SetOption o v -> parens ["set-option", ":" <> o, v]+ SetInfo o v -> parens ["set-info", ":" <> o, v]+ DeclareSort n -> parens ["declare-sort", renderSymbol n, "0"]+ DeclareRecord fs ->+ let name = renderSymbol (recordName fs)+ fields = [parens [renderSymbol (recordSelector fs f), renderSort s] | (f, s) <- fs]+ ctor = parens (renderSymbol (recordConstructor fs) : fields)+ in parens ["declare-datatypes", parens [parens [name, "0"]], parens [parens [ctor]]]+ DeclareFun sym ->+ parens+ [ "declare-fun"+ , renderSymbol (symName sym)+ , parens (map renderSort (symArgs sym))+ , renderSort (symResult sym)+ ]+ DefineFun sym params body ->+ parens+ [ "define-fun"+ , renderSymbol (symName sym)+ , parens [parens [renderSymbol (symName p), renderSort (symResult p)] | p <- params]+ , renderSort (symResult sym)+ , renderExpr body+ ]+ Assert e -> parens ["assert", renderExpr e]+ AssertNamed n e -> parens ["assert", parens ["!", renderExpr e, ":named", renderSymbol n]]+ Push n -> parens ["push", tshow n]+ Pop n -> parens ["pop", tshow n]+ CheckSat -> "(check-sat)"+ CheckSatAssuming es -> parens ["check-sat-assuming", parens (map renderExpr es)]+ GetModel -> "(get-model)"+ GetValue es -> parens ["get-value", parens (map renderExpr es)]+ GetAssertions -> "(get-assertions)"+ GetUnsatCore -> "(get-unsat-core)"+ GetInfo k -> parens ["get-info", ":" <> k]+ GetOption k -> parens ["get-option", ":" <> k]+ Echo t -> parens ["echo", renderString t]+ Reset -> "(reset)"+ ResetAssertions -> "(reset-assertions)"+ Exit -> "(exit)"++-- | A complete script checking the conjunction of the assertions.+problemScript :: [Expr] -> [Command]+problemScript as =+ [SetLogic "ALL"] <> declarationsFor as <> map Assert as <> [CheckSat]++-- | Declarations for every sort and symbol used by the expressions:+-- uninterpreted sorts, record datatypes (dependencies first) and symbols.+declarationsFor :: [Expr] -> [Command]+declarationsFor as =+ sortDeclarations (concatMap symbolSorts syms <> Set.toList (foldMap subtermSorts as))+ <> map DeclareFun syms+ where+ syms = Set.toList (foldMap symbols as)++-- | Sorts of all subterms of a well-sorted expression.+subtermSorts :: Expr -> Set Sort+subtermSorts = snd . go+ where+ go (App op args) =+ let (ss, sets) = unzip (map go args)+ s = either (const BoolSort) id (inferSort op ss)+ in (s, Set.insert s (Set.unions sets))++symbolSorts :: Symbol -> [Sort]+symbolSorts sym = symResult sym : symArgs sym++-- | Declarations of the uninterpreted and record sorts occurring in the+-- given sorts, in dependency order and without repetitions.+sortDeclarations :: [Sort] -> [Command]+sortDeclarations = reverse . snd . foldl visit (Set.empty, [])+ where+ visit (seen, acc) s+ | Set.member s seen = (seen, acc)+ | otherwise =+ let (seen', acc') = foldl visit (Set.insert s seen, acc) (children s)+ in case s of+ UninterpretedSort n -> (seen', DeclareSort n : acc')+ RecordSort fs -> (seen', DeclareRecord fs : acc')+ _ -> (seen', acc')+ children = \case+ ArraySort i e -> [i, e]+ RecordSort fs -> map snd fs+ _ -> []++-------------------------------------------------------------------------------+-- Models++-- | Commands declaring the sorts of the given expressions and defining+-- every symbol they use according to the interpretation, for checking a+-- model with another solver.+--+-- Elements of uninterpreted sorts become fresh constants that are asserted+-- pairwise distinct. Symbols the interpretation does not mention take the+-- default value of their sort. The interpretation of integer division by+-- zero cannot be expressed in SMT-LIB and is left to the other solver.+modelCommands :: Interpretation -> [Expr] -> [Command]+modelCommands interp as =+ sortDeclarations (concatMap symbolSorts syms <> Set.toList (foldMap subtermSorts as) <> elemSorts)+ <> map DeclareFun elemSyms+ <> [Assert (App Distinct es) | es <- elemGroups, length es >= 2]+ <> map (definition interp) syms+ where+ syms = Set.toList (foldMap symbols as)+ elems = modelElements interp syms+ elemSyms = map elemSymbol elems+ elemSorts = [s | VUninterp s _ <- elems]+ elemGroups =+ Map.elems $+ Map.fromListWith (flip (<>)) [(s, [constant (Uninterpreted (elemSymbol v))]) | v@(VUninterp s _) <- elems]++-- | The answer to @get-model@ for the given symbols: a declaration for each+-- element of an uninterpreted sort that the model uses (as Z3 does), then+-- a definition of each symbol.+modelResponse :: Interpretation -> [Symbol] -> [Command]+modelResponse interp syms =+ map (DeclareFun . elemSymbol) (modelElements interp syms) <> map (definition interp) syms++-- | The interpretation of a symbol; symbols the interpretation does not+-- mention take the default value of their sort.+funOf :: Interpretation -> Symbol -> FunInterp+funOf interp sym =+ Map.findWithDefault (constInterp (defaultValue (symResult sym))) sym (interpSymbols interp)++-- | Elements of uninterpreted sorts in the interpretations of the symbols.+modelElements :: Interpretation -> [Symbol] -> [Value]+modelElements interp syms =+ Set.toList . foldMap uninterpElems $+ concat+ [ fiDefault fi : concat [r : args | (args, r) <- Map.toList (fiTable fi)]+ | sym <- syms+ , let fi = funOf interp sym+ ]++-- | A @define-fun@ giving the interpretation of a symbol, as a chain of+-- @ite@ over its table.+definition :: Interpretation -> Symbol -> Command+definition interp sym =+ let fi = funOf interp sym+ params = [Symbol ("x!" <> tshow i) [] s | (i, s) <- zip [0 :: Int ..] (symArgs sym)]+ paramExprs = map (constant . Uninterpreted) params+ entry (args, r) rest =+ App Ite [conj (zipWith (\p v -> App Eq [p, valueExpr v]) paramExprs args), valueExpr r, rest]+ body+ | null params = valueExpr (Map.findWithDefault (fiDefault fi) [] (fiTable fi))+ | otherwise = foldr entry (valueExpr (fiDefault fi)) (Map.toList (fiTable fi))+ in DefineFun sym params body+ where+ conj [c] = c+ conj cs = App And cs++-- | Every abstract element occurring in a value.+uninterpElems :: Value -> Set Value+uninterpElems = \case+ v@(VUninterp _ _) -> Set.singleton v+ VArray _ entries def ->+ foldMap uninterpElems (def : Map.keys entries <> Map.elems entries)+ VRecord fs -> foldMap (uninterpElems . snd) fs+ _ -> Set.empty++elemSymbol :: Value -> Symbol+elemSymbol = \case+ VUninterp s n -> Symbol (sortTag s <> "!elem!" <> tshow n) [] s+ v -> error ("elemSymbol: not an abstract element: " <> show v)+ where+ sortTag = \case+ UninterpretedSort n -> n+ s -> renderSort s++-- | A term denoting a value. Abstract elements of uninterpreted sorts are+-- denoted by the constants introduced by 'modelCommands'.+valueExpr :: Value -> Expr+valueExpr = \case+ VBool b -> constant (BoolConst b)+ VInt n -> constant (IntConst n)+ VString s -> constant (StrConst s)+ VBV w x -> constant (BVConst w x)+ VArray idx entries def ->+ foldl+ (\acc (k, e) -> App Store [acc, valueExpr k, valueExpr e])+ (App (ConstArray idx) [valueExpr def])+ (sortOn fst (Map.toList entries))+ VRecord fs -> App (RecordMk (map fst fs)) (map (valueExpr . snd) fs)+ v@(VUninterp _ _) -> constant (Uninterpreted (elemSymbol v))+ VFP eb sb x -> constant (FPConst eb sb x)+ VRM rm -> constant (RMConst rm)+ VRegLan r -> regexExpr r++-- | A term denoting a regular expression.+regexExpr :: R.Regex -> Expr+regexExpr = \case+ R.RSet [] -> constant ReNone+ R.RSet cs+ | cs == R.fullSet -> constant ReAllChar+ | otherwise -> case map rangeExpr cs of+ [e] -> e+ es -> App ReUnion es+ R.REps -> App StrToRe [constant (StrConst "")]+ R.RCat a b -> App ReConcat [regexExpr a, regexExpr b]+ R.RAlt xs -> App ReUnion (map regexExpr (Set.toList xs))+ R.RAnd xs -> App ReInter (map regexExpr (Set.toList xs))+ R.RStar r -> App ReStar [regexExpr r]+ R.RNot (R.RSet []) -> constant ReAll+ R.RNot r -> App ReComp [regexExpr r]+ where+ char c = constant (StrConst (T.singleton (toEnum c)))+ rangeExpr (lo, hi)+ | lo == hi = App StrToRe [char lo]+ | otherwise = App ReRange [char lo, char hi]++-- | Sort of a value.+valueSort :: Value -> Sort+valueSort = \case+ VBool _ -> BoolSort+ VInt _ -> IntSort+ VString _ -> StringSort+ VBV w _ -> BVSort w+ VArray idx _ def -> ArraySort idx (valueSort def)+ VRecord fs -> RecordSort [(f, valueSort v) | (f, v) <- fs]+ VUninterp s _ -> s+ VFP eb sb _ -> FPSort eb sb+ VRM _ -> RoundingModeSort+ VRegLan _ -> RegLanSort++-------------------------------------------------------------------------------+-- Terms++-- | Render a well-sorted expression as an SMT-LIB term.+renderExpr :: Expr -> Text+renderExpr (App op args) = case (op, args) of+ (IntConst n, [])+ | n < 0 -> parens ["-", tshow (negate n)]+ | otherwise -> tshow n+ (BVConst w v, []) -> parens ["_", "bv" <> tshow v, tshow w]+ (StrConst s, []) -> renderString s+ (FPConst eb sb x, []) -> prettyValue (VFP eb sb x)+ (Uninterpreted sym, _) -> apply (renderSymbol (symName sym))+ -- Degenerate Boolean connectives.+ (And, []) -> "true"+ (And, [a]) -> renderExpr a+ (Or, []) -> "false"+ (Or, [a]) -> renderExpr a+ (ConstArray idx, [e]) ->+ parens+ [ parens ["as", "const", renderSort (ArraySort idx (exprSort e))]+ , renderExpr e+ ]+ (RecordMk names, _) -> apply (renderSymbol (recordConstructor (fieldsOf names args)))+ (RecordGet f, [r]) -> case exprSort r of+ RecordSort fs -> parens [renderSymbol (recordSelector fs f), renderExpr r]+ s -> illSorted s+ (RecordSet f, [r, v]) -> case exprSort r of+ RecordSort fs ->+ renderExpr $+ App+ (RecordMk (map fst fs))+ [if g == f then v else App (RecordGet g) [r] | (g, _) <- fs]+ s -> illSorted s+ _ -> apply (opName op)+ where+ apply f+ | null args = f+ | otherwise = parens (f : map renderExpr args)+ fieldsOf names es = zip names (map exprSort es)+ illSorted s = "|ill-sorted:" <> renderSort s <> "|"++-- | Sort of a well-sorted expression. Rendering ill-sorted expressions is a+-- bug in the caller.+exprSort :: Expr -> Sort+exprSort e = case sortOf e of+ Right s -> s+ Left err -> error ("hsmt: rendering an ill-sorted expression: " <> show err)++-- | Render a sort; record sorts are rendered as the name of their datatype.+renderSort :: Sort -> Text+renderSort = \case+ BoolSort -> "Bool"+ IntSort -> "Int"+ StringSort -> "String"+ BVSort n -> parens ["_", "BitVec", tshow n]+ ArraySort i e -> parens ["Array", renderSort i, renderSort e]+ RecordSort fs -> renderSymbol (recordName fs)+ UninterpretedSort n -> renderSymbol n+ FPSort eb sb -> parens ["_", "FloatingPoint", tshow eb, tshow sb]+ RoundingModeSort -> "RoundingMode"+ RegLanSort -> "RegLan"++-- | Name of the datatype standing for a record sort. It is a function of the+-- field list, so equal record sorts get equal names.+recordName :: [(Text, Sort)] -> Text+recordName fs = "Record{" <> T.intercalate "," [f <> ":" <> plain s | (f, s) <- fs] <> "}"+ where+ plain = \case+ RecordSort gs -> recordName gs+ UninterpretedSort n -> n+ s -> renderSort s++-- | Name of the constructor of the datatype standing for a record sort.+recordConstructor :: [(Text, Sort)] -> Text+recordConstructor fs = "mk-" <> recordName fs++-- | Name of the selector of the given field of a record sort.+recordSelector :: [(Text, Sort)] -> Text -> Text+recordSelector fs f = recordName fs <> "." <> f++-- | Render a symbol, quoting it when it is not a simple symbol.+renderSymbol :: Text -> Text+renderSymbol s+ | isSimple = s+ | otherwise = "|" <> s <> "|"+ where+ isSimple =+ not (T.null s)+ && T.all (\c -> isAsciiAlphaNum c || c `elem` ("~!@$%^&*_-+=<>.?/" :: String)) s+ && not (isDigit (T.head s))+ && s `notElem` reserved+ isAsciiAlphaNum c = isAlphaNum c && ord c < 128+ reserved =+ ["par", "NUMERAL", "DECIMAL", "STRING", "_", "!", "as", "let", "exists", "forall", "match"]++-- | Render a string literal. Quotes are doubled; backslashes and characters+-- outside printable ASCII use the @\\u{...}@ escape of SMT-LIB 2.6.+renderString :: Text -> Text+renderString s = "\"" <> T.concatMap escape s <> "\""+ where+ escape c+ | c == '"' = "\"\""+ | c == '\\' || ord c < 32 || ord c > 126 = "\\u{" <> T.pack (showHex (ord c) "") <> "}"+ | otherwise = T.singleton c++parens :: [Text] -> Text+parens ts = "(" <> T.unwords ts <> ")"++tshow :: Show a => a -> Text+tshow = T.pack . show
+ src/HSMT/SMTLib/Run.hs view
@@ -0,0 +1,281 @@+-- | Execution of SMT-LIB scripts with the hsmt engine or an external+-- solver ("HSMT.Backend").+--+-- All checks of a script run in one incremental session+-- (t'HSMT.SMT.Engine.Session', or one external solver process). Models+-- of external solvers are read back, so @get-model@ and @get-value@ are+-- answered by hsmt in both cases. Scripts are elaborated and executed command+-- by command: a command with an error answers @(error ...)@ and the script+-- goes on, as the @:error-behavior@ @continued-execution@ of SMT-LIB 2.6+-- describes.+--+-- Besides the standard options (@:print-success@, @:produce-models@ and the+-- like, which are accepted), the options @:timeout@ (milliseconds per check)+-- and @:smt.core.minimize@ (as in Z3) are honored. With an external+-- solver, @get-unsat-core@ gives a small core only under+-- @:produce-unsat-cores true@ (as SMT-LIB requires); otherwise it names+-- every assertion.+module HSMT.SMTLib.Run+ ( -- * Responses+ Response (..)+ , renderResponse+ -- * Running scripts+ , runScriptWith+ , runScriptWithBackend+ , runScriptResponses+ , runScriptResponsesWith+ , runScriptText+ -- * Running elaborated commands+ , runResponses+ , runCommands+ ) where++import Control.Exception (bracket)+import Data.IORef+import Data.Maybe (mapMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Version (showVersion)+import Text.Read (readMaybe)++import HSMT.Backend+import HSMT.Core.Eval+import HSMT.Core.Expr+import HSMT.Core.Op (Symbol)+import HSMT.SMT.Engine+import HSMT.SMTLib.Parser+import HSMT.SMTLib.Printer+import HSMT.SMTLib.Syntax+import qualified Paths_hsmt as Paths++-- | The output of a command.+data Response+ = CheckResult EngineResult+ -- ^ Answer of @check-sat@ or @check-sat-assuming@.+ | UnsatCore [Text]+ -- ^ Answer of @get-unsat-core@: the names of the named assertions and+ -- the assumptions (rendered) of the last core.+ | Model Interpretation [Symbol]+ -- ^ Answer of @get-model@: the model and the symbols in scope.+ | Values [(Expr, Expr)]+ -- ^ Answer of @get-value@: each term with its value, as a term.+ | Assertions [Text]+ -- ^ Answer of @get-assertions@, rendered.+ | Info Text Text+ -- ^ Answer of @get-info@ or @get-option@: the keyword and its value.+ | Success+ -- ^ The answer of a command without output under @:print-success@.+ | Unsupported+ -- ^ An unknown keyword of @get-info@ or @get-option@.+ | Echoed Text+ | CommandError Text+ -- ^ A command that cannot be executed, such as @get-unsat-core@ after+ -- a satisfiable check or an ill-sorted term. The script goes on.+ deriving (Show)++-- | The text a solver prints for a response, without the final newline.+renderResponse :: Response -> Text+renderResponse = \case+ CheckResult (ESat _) -> "sat"+ CheckResult (EUnsat _) -> "unsat"+ CheckResult (EUnknown _) -> "unknown"+ UnsatCore names -> "(" <> T.unwords names <> ")"+ Model interp syms -> case modelResponse interp syms of+ [] -> "(\n)"+ cs -> "(\n" <> T.unlines (map ((" " <>) . renderCommand) cs) <> ")"+ Values vs -> "(" <> T.intercalate "\n " ["(" <> renderExpr t <> " " <> renderExpr v <> ")" | (t, v) <- vs] <> ")"+ Assertions as -> "(" <> T.intercalate "\n " as <> ")"+ Info k v -> "(:" <> k <> " " <> v <> ")"+ Success -> "success"+ Unsupported -> "unsupported"+ Echoed t -> renderString t+ CommandError why -> "(error " <> renderString why <> ")"++-- | An entry of an assertion level.+data Entry+ = EAssert (Maybe Text) Expr+ | EDeclare Symbol++data RunState = RunState+ { rsBackend :: Backend+ , rsSession :: BackendSession+ , rsLevels :: [[Entry]]+ -- ^ Assertion levels, innermost first; each in reverse order.+ , rsOptions :: CheckOptions+ , rsInitialOptions :: CheckOptions+ -- ^ The options @reset@ restores.+ , rsPrintSuccess :: Bool+ , rsLast :: Maybe (EngineResult, [Maybe Text])+ -- ^ The last check result and the labels of its formulas, while no+ -- assertion level changed since.+ , rsReason :: Maybe Text+ -- ^ Why the last check answered unknown.+ }++newState :: Backend -> CheckOptions -> IO RunState+newState backend opts = do+ sess <- newBackendSession backend+ -- Scripts that want cores say so with :produce-unsat-cores.+ let opts' = opts {coNeedCore = False}+ pure (RunState backend sess [[]] opts' opts' False Nothing Nothing)++-- | Execute one command, giving its responses and whether the script goes+-- on.+execute :: RunState -> Command -> IO (RunState, [Response], Bool)+execute st = \case+ Assert e -> quiet (change (addEntry (EAssert Nothing e) st))+ AssertNamed n e -> quiet (change (addEntry (EAssert (Just n) e) st))+ DeclareFun sym -> quiet (addEntry (EDeclare sym) st)+ Push n -> quiet (change st {rsLevels = replicate n [] <> rsLevels st})+ Pop n+ | n < length (rsLevels st) -> quiet (change st {rsLevels = drop n (rsLevels st)})+ | otherwise -> out st [CommandError "pop: not enough assertion levels"]+ CheckSat -> check []+ CheckSatAssuming es -> check es+ GetModel -> withModel $ \interp -> [Model interp (declared st)]+ GetValue es -> withModel $ \interp ->+ case traverse (evalExpr interp) es of+ Right vs -> [Values (zip es (map valueExpr vs))]+ Left err -> [CommandError ("cannot evaluate: " <> eeMessage err)]+ GetAssertions -> out st [Assertions [render n e | EAssert n e <- reverse (concat (rsLevels st))]]+ GetUnsatCore -> out st $ case rsLast st of+ Just (EUnsat idx, labels) -> [UnsatCore (mapMaybe (labels !!) idx)]+ _ -> [CommandError "no unsatisfiable core available"]+ GetInfo k -> out st [info k]+ GetOption k -> out st [option k]+ SetOption o v -> quiet (setOption o v st)+ Echo t -> out st [Echoed t]+ Reset -> do+ closeBackendSession (rsSession st)+ newState (rsBackend st) (rsInitialOptions st) >>= quiet+ ResetAssertions -> do+ closeBackendSession (rsSession st)+ sess <- newBackendSession (rsBackend st)+ quiet st {rsSession = sess, rsLevels = [[]], rsLast = Nothing}+ Exit -> pure (st, [Success | rsPrintSuccess st], False)+ _ -> quiet st+ where+ out st' rs = pure (st', rs, True)+ quiet st' = out st' [Success | rsPrintSuccess st']+ change st' = st' {rsLast = Nothing}++ addEntry e st' = case rsLevels st' of+ (l : rest) -> st' {rsLevels = (e : l) : rest}+ [] -> st' {rsLevels = [[e]]}++ render n e = maybe (renderExpr e) (\name -> "(! " <> renderExpr e <> " :named " <> renderSymbol name <> ")") n++ check assumed = do+ let levels = [[(n, e) | EAssert n e <- reverse l] | l <- reverse (rsLevels st)]+ labels = map fst (concat levels) <> map (Just . renderExpr) assumed+ r <- checkBackend (rsSession st) (rsOptions st) (map (map snd) levels) assumed+ let reason = case r of+ EUnknown why -> Just why+ _ -> Nothing+ out st {rsLast = Just (r, labels), rsReason = reason} [CheckResult r]++ withModel k = out st $ case rsLast st of+ Just (ESat interp, _) -> k interp+ _ -> [CommandError "no model available"]++ declared st' = reverse [sym | EDeclare sym <- concat (rsLevels st')]++ info = \case+ "name" -> Info "name" "\"hsmt\""+ "version" -> Info "version" (renderString (T.pack (showVersion Paths.version)))+ "authors" -> Info "authors" "\"rodrigogribeiro\""+ "error-behavior" -> Info "error-behavior" "continued-execution"+ "assertion-stack-levels" -> Info "assertion-stack-levels" (T.pack (show (length (rsLevels st) - 1)))+ "all-statistics" -> Info "all-statistics" "()"+ "reason-unknown" -> case rsReason st of+ Just "timeout" -> Info "reason-unknown" "timeout"+ Just why -> Info "reason-unknown" (renderString why)+ Nothing -> CommandError "the last check did not answer unknown"+ _ -> Unsupported++ option = \case+ "print-success" -> Info "print-success" (bool (rsPrintSuccess st))+ "produce-models" -> Info "produce-models" "true"+ "produce-unsat-cores" -> Info "produce-unsat-cores" (bool (coNeedCore (rsOptions st)))+ "smt.core.minimize" -> Info "smt.core.minimize" (bool (coMinimizeCore (rsOptions st)))+ "timeout" -> Info "timeout" (maybe "0" (\t -> T.pack (show (round (t * 1000) :: Integer))) (coTimeout (rsOptions st)))+ _ -> Unsupported++ bool b = if b then "true" else "false"++ setOption o v st' = case o of+ "print-success" -> st' {rsPrintSuccess = v == "true"}+ "timeout" | Just ms <- readMaybe (T.unpack v) ->+ let t = if ms <= 0 then Nothing else Just (fromInteger ms / 1000)+ in st' {rsOptions = (rsOptions st') {coTimeout = t}}+ "smt.core.minimize" -> st' {rsOptions = (rsOptions st') {coMinimizeCore = v == "true"}}+ "produce-unsat-cores" -> st' {rsOptions = (rsOptions st') {coNeedCore = v == "true"}}+ _ -> st'++-------------------------------------------------------------------------------+-- Drivers++-- | Elaborate and execute a script command by command, passing each+-- response to the callback as soon as it is known. Errors (including a+-- syntax error, which ends the script) are responses.+runScriptWith :: CheckOptions -> (Response -> IO ()) -> Text -> IO ()+runScriptWith = runScriptWithBackend Native++-- | 'runScriptWith' with the given backend.+runScriptWithBackend :: Backend -> CheckOptions -> (Response -> IO ()) -> Text -> IO ()+runScriptWithBackend backend opts emit txt = do+ -- The session in use, stopped at the end even after an exception.+ current <- newIORef Nothing+ let (ses, syntaxError) = parseSExprsPartial txt+ go _ _ [] = mapM_ (emit . CommandError) syntaxError+ go ps st (se : rest) = case parseCommand ps se of+ Left err -> emit (CommandError err) >> go ps st rest+ Right (ps', cmds) -> steps ps' st cmds rest+ steps ps st [] rest = go ps st rest+ steps ps st (c : cs) rest = do+ (st', rs, continue) <- execute st c+ writeIORef current (Just (rsSession st'))+ mapM_ emit rs+ if continue then steps ps st' cs rest else pure ()+ bracket+ (newState backend opts)+ (\_ -> readIORef current >>= mapM_ closeBackendSession)+ (\st0 -> writeIORef current (Just (rsSession st0)) >> go initialParseState st0 ses)++-- | Elaborate and execute a script, returning every response in order.+-- When @validate@ holds, models are checked against the assertions.+runScriptResponses :: Bool -> Text -> IO [Response]+runScriptResponses = runScriptResponsesWith Native++-- | 'runScriptResponses' with the given backend.+runScriptResponsesWith :: Backend -> Bool -> Text -> IO [Response]+runScriptResponsesWith backend validate txt = do+ ref <- newIORef []+ runScriptWithBackend backend defaultCheckOptions {coValidate = validate} (\r -> modifyIORef' ref (r :)) txt+ reverse <$> readIORef ref++-- | Parse and run a script, returning the check results. Unlike+-- 'runScriptResponses', the first error in the script is returned as+-- 'Left' and nothing runs.+runScriptText :: Bool -> Text -> IO (Either Text [EngineResult])+runScriptText validate txt = case parseScript txt of+ Left err -> pure (Left err)+ Right cmds -> runCommands validate cmds++-- | Run elaborated commands and return the output of each, in order.+runResponses :: Bool -> [Command] -> IO [Response]+runResponses validate cmds0 = newState Native defaultCheckOptions {coValidate = validate} >>= go cmds0+ where+ go [] _ = pure []+ go (c : cs) st = do+ (st', rs, continue) <- execute st c+ (rs <>) <$> if continue then go cs st' else pure []++-- | Run elaborated commands and return the result of every @check-sat@+-- and @check-sat-assuming@, in order. An error is returned as 'Left'.+runCommands :: Bool -> [Command] -> IO (Either Text [EngineResult])+runCommands validate cmds = do+ rs <- runResponses validate cmds+ pure $ case [e | CommandError e <- rs] of+ e : _ -> Left e+ [] -> Right [r | CheckResult r <- rs]
+ src/HSMT/SMTLib/Syntax.hs view
@@ -0,0 +1,81 @@+-- | Abstract syntax of the SMT-LIB 2 commands understood by hsmt.+--+-- Terms are represented directly as core expressions ('HSMT.Core.Expr'):+-- the parser elaborates and sort-checks them, and the printer renders them+-- back. Parameters of @define-fun@ are represented as nullary uninterpreted+-- symbols.+module HSMT.SMTLib.Syntax+ ( Command (..)+ , Answer (..)+ , renderAnswer+ ) where++import Data.Text (Text)++import HSMT.Core.Expr+import HSMT.Core.Op+import HSMT.Core.Sort++-- | An SMT-LIB command.+data Command+ = SetLogic Text+ -- ^ @set-logic@ with the logic name.+ | SetOption Text Text+ -- ^ Option name (without the leading colon) and its value, verbatim.+ | SetInfo Text Text+ -- ^ @set-info@: keyword (without the leading colon) and its value,+ -- verbatim.+ | DeclareSort Text+ -- ^ An uninterpreted sort of arity 0.+ | DeclareRecord [(Text, Sort)]+ -- ^ A record sort, rendered as a single-constructor datatype.+ | DeclareFun Symbol+ -- ^ @declare-fun@ (or @declare-const@) of an uninterpreted symbol.+ | DefineFun Symbol [Symbol] Expr+ -- ^ A macro: the defined symbol, its parameters and its body.+ | Assert Expr+ -- ^ @assert@ of a Boolean expression.+ | AssertNamed Text Expr+ -- ^ @(assert (! e :named n))@: the name identifies the assertion in+ -- unsatisfiable cores.+ | Push Int+ -- ^ @push@ the given number of assertion levels.+ | Pop Int+ -- ^ @pop@ the given number of assertion levels.+ | CheckSat+ -- ^ @check-sat@.+ | CheckSatAssuming [Expr]+ -- ^ @check-sat-assuming@ with Boolean assumptions.+ | GetModel+ -- ^ @get-model@.+ | GetValue [Expr]+ -- ^ @get-value@ of the given terms.+ | GetAssertions+ -- ^ @get-assertions@.+ | GetUnsatCore+ -- ^ @get-unsat-core@.+ | GetInfo Text+ -- ^ The keyword, without the leading colon.+ | GetOption Text+ -- ^ The option name, without the leading colon.+ | Echo Text+ -- ^ @echo@ of a string literal (its contents, without the quotes).+ | Reset+ -- ^ @reset@: back to the initial state.+ | ResetAssertions+ -- ^ @reset-assertions@: drop all assertions and declarations, keeping+ -- options.+ | Exit+ -- ^ @exit@.+ deriving (Eq, Show)++-- | Answer to a @check-sat@ command.+data Answer = AnsSat | AnsUnsat | AnsUnknown+ deriving (Eq, Ord, Show)++-- | The SMT-LIB spelling of an answer (@sat@, @unsat@ or @unknown@).+renderAnswer :: Answer -> Text+renderAnswer = \case+ AnsSat -> "sat"+ AnsUnsat -> "unsat"+ AnsUnknown -> "unknown"
+ src/HSMT/Theory/Arith.hs view
@@ -0,0 +1,341 @@+-- | Linear integer arithmetic (LIA) for DPLL(T).+--+-- Every arithmetic atom is normalized to the form @x <= c@, where @x@ is a+-- simplex variable (an integer term, or a slack variable standing for a+-- linear combination with coprime integer coefficients) and @c@ is an+-- integer. Over the integers the negation of @x <= c@ is @x >= c + 1@, so+-- both polarities of an atom are bounds.+--+-- Satisfiability over the rationals is decided by the general simplex+-- ('HSMT.Theory.Arith.Simplex'); integrality is enforced by+-- branch-and-bound, which creates new atoms @x <= floor v@ for variables+-- with fractional values and lets the SAT solver decide them.+module HSMT.Theory.Arith+ ( Arith+ , LinExpr (..)+ , linConst+ , linVar+ , linAdd+ , linScale+ , linSub+ , newArith+ , termVar+ , freshVar+ , leAtom+ , pendingLemmas+ , queueClause+ , arithHooks+ , linValue+ , varValue+ , isUnbranchable+ , resetBranching+ , hasArithVars+ ) where++import Control.Monad (forM, forM_, unless)+import Data.IORef+import Data.List (sortOn)+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IntMap+import qualified Data.IntSet as IntSet+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Ratio (denominator, numerator)++import HSMT.SAT.Solver (Solver)+import qualified HSMT.SAT.Solver as SAT+import HSMT.SAT.Types+import HSMT.Theory.Arith.Simplex (SVar)+import qualified HSMT.Theory.Arith.Simplex as Sx++-- | A linear combination of simplex variables plus a constant.+data LinExpr = LinExpr+ { linCoeffs :: !(IntMap Integer)+ , linConstant :: !Integer+ }+ deriving (Eq, Ord, Show)++-- | A constant expression.+linConst :: Integer -> LinExpr+linConst = LinExpr IntMap.empty++-- | A single variable with coefficient 1.+linVar :: SVar -> LinExpr+linVar x = LinExpr (IntMap.singleton x 1) 0++-- | Sum of two expressions; zero coefficients are dropped.+linAdd :: LinExpr -> LinExpr -> LinExpr+linAdd (LinExpr a c) (LinExpr b d) = LinExpr (IntMap.filter (/= 0) (IntMap.unionWith (+) a b)) (c + d)++-- | Multiply an expression by a constant.+linScale :: Integer -> LinExpr -> LinExpr+linScale 0 _ = linConst 0+linScale k (LinExpr a c) = LinExpr (IntMap.map (* k) a) (k * c)++-- | Difference of two expressions.+linSub :: LinExpr -> LinExpr -> LinExpr+linSub a b = linAdd a (linScale (-1) b)++-- | The LIA theory solver: a simplex, the atoms over its variables and the+-- branch-and-bound state.+data Arith = Arith+ { arSolver :: !Solver+ , arTrue :: !Lit+ , arSimplex :: !Sx.Simplex+ , arTermVars :: !(IORef (IntMap SVar))+ -- ^ Simplex variable of each integer term.+ , arBranchVars :: !(IORef IntSet.IntSet)+ -- ^ Variables that must take integer values (all but slack variables).+ , arForms :: !(IORef (Map [(SVar, Integer)] SVar))+ -- ^ Slack variable of each normalized combination.+ , arAtoms :: !(IORef (IntMap (SVar, Integer)))+ -- ^ SAT variable to the atom @x <= c@ it stands for.+ , arVarAtoms :: !(IORef (IntMap (Map Integer Lit)))+ -- ^ Atoms of each simplex variable, by constant.+ , arPending :: !(IORef [Lemma])+ -- ^ Clauses waiting to be handed to the SAT solver.+ , arConflict :: !(IORef (Maybe [Lit]))+ , arBranches :: !(IORef Int)+ , arBranchCount :: !(IORef (IntMap Int))+ -- ^ How often each variable was branched on.+ , arBranchLimit :: !Int+ , arGaveUp :: !(IORef Bool)+ }++-- | An empty solver attached to a SAT solver, given the literal that is+-- always true (used for constant atoms).+newArith :: Solver -> Lit -> IO Arith+newArith s t =+ Arith s t+ <$> Sx.newSimplex+ <*> newIORef IntMap.empty+ <*> newIORef IntSet.empty+ <*> newIORef Map.empty+ <*> newIORef IntMap.empty+ <*> newIORef IntMap.empty+ <*> newIORef []+ <*> newIORef Nothing+ <*> newIORef 0+ <*> newIORef IntMap.empty+ <*> pure 100000+ <*> newIORef False++-- | The simplex variable of an integer term (by term id).+termVar :: Arith -> Int -> IO SVar+termVar ar t =+ IntMap.lookup t <$> readIORef (arTermVars ar) >>= \case+ Just x -> pure x+ Nothing -> do+ x <- freshVar ar+ modifyIORef' (arTermVars ar) (IntMap.insert t x)+ pure x++-- | A fresh integer variable not associated with a term.+freshVar :: Arith -> IO SVar+freshVar ar = do+ x <- Sx.newVar (arSimplex ar)+ modifyIORef' (arBranchVars ar) (IntSet.insert x)+ pure x++-- | The literal of @e <= 0@.+leAtom :: Arith -> LinExpr -> IO Lit+leAtom ar (LinExpr coeffs k)+ | IntMap.null coeffs = pure (if k <= 0 then arTrue ar else litNeg (arTrue ar))+ | otherwise = do+ -- sum a_i x_i <= -k, divided by the gcd g: sum (a_i/g) x_i <= floor(-k/g)+ let g = foldr1 gcd (map abs (IntMap.elems coeffs))+ c = floorDiv (negate k) g+ normalized = IntMap.toList (IntMap.map (`div` g) coeffs)+ case normalized of+ ((_, lead) : _)+ | lead > 0 -> atomFor normalized c+ | otherwise ->+ -- sum b_i x_i >= -c with b = -a/g, i.e. not (sum b_i x_i <= -c - 1)+ litNeg <$> atomFor [(x, negate a) | (x, a) <- normalized] (negate c - 1)+ [] -> error "leAtom: empty combination"+ where+ floorDiv a b = floor (fromInteger a / fromInteger b :: Rational)++ atomFor form c = do+ x <- formVar form+ atomLit x c++ formVar = \case+ [(x, 1)] -> pure x+ form ->+ Map.lookup form <$> readIORef (arForms ar) >>= \case+ Just s -> pure s+ Nothing -> do+ s <- Sx.addRow (arSimplex ar) [(fromInteger a, x) | (x, a) <- form]+ modifyIORef' (arForms ar) (Map.insert form s)+ pure s++ -- The atom x <= c, related by implications to its nearest neighbours+ -- on the same variable (x <= c' implies x <= c for c' < c).+ atomLit x c = do+ byVar <- IntMap.findWithDefault Map.empty x <$> readIORef (arVarAtoms ar)+ case Map.lookup c byVar of+ Just l -> pure l+ Nothing -> do+ v <- SAT.newVar (arSolver ar)+ let l = posLit v+ modifyIORef' (arAtoms ar) (IntMap.insert v (x, c))+ modifyIORef' (arVarAtoms ar) (IntMap.insert x (Map.insert c l byVar))+ let below = Map.lookupLT c byVar+ above = Map.lookupGT c byVar+ forM_ below $ \(_, lb) -> queue ar [litNeg lb, l]+ forM_ above $ \(_, la) -> queue ar [litNeg l, la]+ pure l++queue :: Arith -> [Lit] -> IO ()+queue ar c = modifyIORef' (arPending ar) (permanent c :)++-- | Queue a permanent clause; it reaches the SAT solver at the next check.+queueClause :: Arith -> [Lit] -> IO ()+queueClause = queue++-- | Take the clauses produced while creating atoms.+pendingLemmas :: Arith -> IO [Lemma]+pendingLemmas ar = do+ ls <- readIORef (arPending ar)+ writeIORef (arPending ar) []+ pure (reverse ls)++-- | The current (rational) value of a simplex variable.+varValue :: Arith -> SVar -> IO Rational+varValue ar = Sx.value (arSimplex ar)++-- | The value of an expression under the current simplex assignment.+linValue :: Arith -> LinExpr -> IO Rational+linValue ar (LinExpr coeffs k) = do+ vs <- forM (IntMap.toList coeffs) $ \(x, a) -> (* fromInteger a) <$> varValue ar x+ pure (fromInteger k + sum vs)++-- | True when some simplex variable exists.+hasArithVars :: Arith -> IO Bool+hasArithVars ar = not . IntSet.null <$> readIORef (arBranchVars ar)++-- | True when branch-and-bound gave up (the result must be unknown).+isUnbranchable :: Arith -> IO Bool+isUnbranchable = readIORef . arGaveUp++-- | Restore the branch-and-bound budget, for a new satisfiability check of+-- an incremental session.+resetBranching :: Arith -> IO ()+resetBranching ar = do+ writeIORef (arBranches ar) 0+ writeIORef (arGaveUp ar) False++-------------------------------------------------------------------------------+-- DPLL(T) interface++-- | Hooks connecting the arithmetic solver to the SAT engine: bounds are+-- asserted as atoms are assigned, feasibility is checked on propagation and+-- integrality (branch-and-bound and Gomory cuts) at the final check.+arithHooks :: Arith -> TheoryHooks+arithHooks ar =+ TheoryHooks+ { thNewLevel = Sx.push sx+ , thBacktrack = \lvl -> do+ Sx.pop sx lvl+ writeIORef (arConflict ar) Nothing+ , thAssert = assertLit+ , thPropagate = checkNow False+ , thFinalCheck = checkNow True+ }+ where+ sx = arSimplex ar++ assertLit l = do+ conflict <- readIORef (arConflict ar)+ atom <- IntMap.lookup (litVar l) <$> readIORef (arAtoms ar)+ case (conflict, atom) of+ (Nothing, Just (x, c)) -> do+ r <-+ if litSign l+ then Sx.assertLower sx x (fromInteger c + 1) [l]+ else Sx.assertUpper sx x (fromInteger c) [l]+ forM_ r (writeIORef (arConflict ar) . Just)+ _ -> pure ()++ checkNow final = do+ pending <- pendingLemmas ar+ conflict <- readIORef (arConflict ar)+ case (pending, conflict) of+ (_ : _, _) -> pure (TheoryLemmas pending)+ (_, Just c) -> pure (TheoryConflict c)+ _ ->+ Sx.check sx >>= \case+ Just c -> do+ writeIORef (arConflict ar) (Just c)+ pure (TheoryConflict c)+ Nothing+ | final -> branch+ | otherwise -> pure TheoryOk++ -- Integrality: alternate Gomory cuts and branching on the first+ -- variable with a fractional value. Branching creates the atom+ -- x <= floor v, whose two polarities are the two branches. Cuts alone+ -- and branching alone may both diverge on unbounded problems; together+ -- they usually converge quickly.+ branch = do+ vars <- IntSet.toList <$> readIORef (arBranchVars ar)+ fractional <- filterM' (\x -> (/= 1) . denominator <$> Sx.value sx x) vars+ counts <- readIORef (arBranchCount ar)+ scored <- forM fractional $ \x -> do+ lo <- Sx.lowerBound sx x+ up <- Sx.upperBound sx x+ let unbounded = length (filter null [() <$ lo, () <$ up])+ pure ((IntMap.findWithDefault 0 x counts, unbounded), x)+ -- Fairness: always branching on the same unbounded variables may+ -- diverge while a bounded fractional variable is never split.+ case map snd (sortOn fst scored) of+ [] -> pure TheoryOk+ (x : _) -> do+ modifyIORef' (arBranchCount ar) (IntMap.insertWith (+) x 1)+ n <- readIORef (arBranches ar)+ writeIORef (arBranches ar) (n + 1)+ if n >= arBranchLimit ar+ then do+ writeIORef (arGaveUp ar) True+ pure TheoryOk+ else do+ cut <- if odd n then tryCut fractional else pure Nothing+ maybe (splitOn x) pure cut++ splitOn x = do+ v <- Sx.value sx x+ let fl = numerator v `div` denominator v+ l <- leAtomVar x fl+ pending <- pendingLemmas ar+ -- The new atom is unassigned; the SAT solver decides it next. The+ -- branch towards zero is tried first: rounding to the nearest integer+ -- lets values drift away on unbounded problems, while small solutions+ -- are the common case.+ unless (litSign l) $ SAT.setPhase (arSolver ar) (litVar l) (v > 0)+ pure (if null pending then TheoryOk else TheoryLemmas pending)++ tryCut = \case+ [] -> pure Nothing+ (x : xs) -> do+ basic <- Sx.isBasic sx x+ cut <- if basic then Sx.gomoryCut sx x else pure Nothing+ case cut of+ Nothing -> tryCut xs+ Just (coeffs, k, reasons) -> do+ -- sum c_j x_j >= k, scaled to integers: d k - sum (d c_j) x_j <= 0+ let d = foldr (lcm . denominator) (denominator k) (map fst coeffs)+ scaleR q = numerator (q * fromInteger d)+ lin = LinExpr (IntMap.filter (/= 0) (IntMap.fromListWith (+) [(y, negate (scaleR c)) | (c, y) <- coeffs])) (scaleR k)+ l <- leAtom ar lin+ pending <- pendingLemmas ar+ pure (Just (TheoryLemmas (pending <> [removable (l : map litNeg reasons)])))++ leAtomVar x c = leAtom ar (LinExpr (IntMap.singleton x 1) (negate c))++ filterM' p = \case+ [] -> pure []+ (y : ys) -> do+ keep <- p y+ rest <- filterM' p ys+ pure (if keep then y : rest else rest)
+ src/HSMT/Theory/Arith/Simplex.hs view
@@ -0,0 +1,366 @@+-- | General simplex for linear arithmetic, in the style of Dutertre and+-- de Moura ("A fast linear-arithmetic solver for DPLL(T)", CAV 2006).+--+-- The tableau keeps every basic variable as a linear combination of+-- nonbasic variables. Constraints are bounds on variables; every bound+-- carries the literals that justify it, so infeasibility is explained by a+-- set of bounds (a Farkas certificate read off a tableau row).+--+-- Bounds are backtrackable: 'push' opens a level and 'pop' restores the+-- bounds of older levels. The assignment and the tableau are kept across+-- backtracking, which is sound because loosening bounds never invalidates+-- the tableau equations.+--+-- Arithmetic is exact, over 'Rational'.+module HSMT.Theory.Arith.Simplex+ ( Simplex+ , SVar+ , Bound (..)+ , newSimplex+ , newVar+ , addRow+ , assertUpper+ , assertLower+ , check+ , push+ , pop+ , level+ , value+ , lowerBound+ , upperBound+ , rowOf+ , isBasic+ , gomoryCut+ ) where++import Control.Monad (forM_, when)+import Data.IORef+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IntMap+import Data.IntSet (IntSet)+import Data.Maybe (isNothing)+import qualified Data.IntSet as IntSet++import HSMT.SAT.Types (Lit)++-- | A simplex variable (an index into the tableau).+type SVar = Int++-- | A bound and its justification. An empty justification marks a fact+-- that holds unconditionally.+data Bound = Bound+ { bValue :: !Rational+ -- ^ The value of the bound.+ , bReason :: ![Lit]+ -- ^ The literals whose assignment asserted the bound.+ }+ deriving (Show)++-- | Mutable simplex state: assignment, bounds, tableau and the trail used+-- to undo bounds on backtracking.+data Simplex = Simplex+ { sxNext :: !(IORef Int)+ , sxValue :: !(IORef (IntMap Rational))+ , sxLower :: !(IORef (IntMap Bound))+ , sxUpper :: !(IORef (IntMap Bound))+ , sxRows :: !(IORef (IntMap (IntMap Rational)))+ -- ^ Basic variable to its row over nonbasic variables.+ , sxCols :: !(IORef (IntMap IntSet))+ -- ^ Nonbasic variable to the basic variables whose rows mention it.+ , sxTrail :: !(IORef [(SVar, Bool, Maybe Bound)])+ -- ^ Previous bounds (flag: upper), most recent first.+ , sxTrailLen :: !(IORef Int)+ , sxLevels :: !(IORef [Int])+ -- ^ Trail length when each level was opened, innermost first.+ , sxDirty :: !(IORef IntSet)+ -- ^ Basic variables that may violate a bound: those whose value or+ -- bounds changed since the last 'check'. Every violated basic variable+ -- is in this set.+ }++-- | An empty simplex with no variables and no open levels.+newSimplex :: IO Simplex+newSimplex =+ Simplex+ <$> newIORef 0+ <*> newIORef IntMap.empty+ <*> newIORef IntMap.empty+ <*> newIORef IntMap.empty+ <*> newIORef IntMap.empty+ <*> newIORef IntMap.empty+ <*> newIORef []+ <*> newIORef 0+ <*> newIORef []+ <*> newIORef IntSet.empty++-- | A fresh unbounded nonbasic variable with value 0.+newVar :: Simplex -> IO SVar+newVar sx = do+ v <- readIORef (sxNext sx)+ writeIORef (sxNext sx) (v + 1)+ pure v++-- | The current value of a variable (0 for a fresh one).+value :: Simplex -> SVar -> IO Rational+value sx v = IntMap.findWithDefault 0 v <$> readIORef (sxValue sx)++-- | The current lower and upper bound of a variable, if any.+lowerBound, upperBound :: Simplex -> SVar -> IO (Maybe Bound)+lowerBound sx v = IntMap.lookup v <$> readIORef (sxLower sx)+upperBound sx v = IntMap.lookup v <$> readIORef (sxUpper sx)++-- | Whether the variable is currently basic (has a tableau row).+isBasic :: Simplex -> SVar -> IO Bool+isBasic sx v = IntMap.member v <$> readIORef (sxRows sx)++-- | The row of a basic variable.+rowOf :: Simplex -> SVar -> IO (Maybe (IntMap Rational))+rowOf sx v = IntMap.lookup v <$> readIORef (sxRows sx)++-- | A fresh basic variable equal to the given combination.+addRow :: Simplex -> [(Rational, SVar)] -> IO SVar+addRow sx combo = do+ s <- newVar sx+ rows <- readIORef (sxRows sx)+ vals <- readIORef (sxValue sx)+ -- Express the combination over nonbasic variables.+ let expand (a, x) = case IntMap.lookup x rows of+ Just r -> IntMap.map (* a) r+ Nothing -> IntMap.singleton x a+ row = IntMap.filter (/= 0) (IntMap.unionsWith (+) (map expand combo))+ val = sum [a * IntMap.findWithDefault 0 x vals | (x, a) <- IntMap.toList row]+ writeIORef (sxRows sx) (IntMap.insert s row rows)+ modifyIORef' (sxCols sx) $ \cols ->+ foldl' (\m x -> IntMap.insertWith IntSet.union x (IntSet.singleton s) m) cols (IntMap.keys row)+ modifyIORef' (sxValue sx) (IntMap.insert s val)+ modifyIORef' (sxDirty sx) (IntSet.insert s)+ pure s++-------------------------------------------------------------------------------+-- Levels++-- | Open a new backtracking level for bounds.+push :: Simplex -> IO ()+push sx = readIORef (sxTrailLen sx) >>= \n -> modifyIORef' (sxLevels sx) (n :)++-- | The number of open levels.+level :: Simplex -> IO Int+level sx = length <$> readIORef (sxLevels sx)++-- | Return to the given number of open levels.+pop :: Simplex -> Int -> IO ()+pop sx lvl = do+ levels <- readIORef (sxLevels sx)+ let excess = length levels - lvl+ when (excess > 0) $ case drop (excess - 1) levels of+ (mark : older) -> do+ writeIORef (sxLevels sx) older+ n <- readIORef (sxTrailLen sx)+ trail <- readIORef (sxTrail sx)+ let (undo, keep) = splitAt (n - mark) trail+ forM_ undo $ \(v, isUpper, old) -> do+ let ref = if isUpper then sxUpper sx else sxLower sx+ modifyIORef' ref (maybe (IntMap.delete v) (IntMap.insert v) old)+ writeIORef (sxTrail sx) keep+ writeIORef (sxTrailLen sx) mark+ [] -> pure ()++record :: Simplex -> SVar -> Bool -> Maybe Bound -> IO ()+record sx v isUpper old = do+ modifyIORef' (sxTrail sx) ((v, isUpper, old) :)+ modifyIORef' (sxTrailLen sx) (+ 1)++-------------------------------------------------------------------------------+-- Bounds++-- | Assert @v <= c@. Returns the explanation of a conflict with the lower+-- bound, if any.+assertUpper :: Simplex -> SVar -> Rational -> [Lit] -> IO (Maybe [Lit])+assertUpper sx v c reason = do+ up <- upperBound sx v+ lo <- lowerBound sx v+ case () of+ _+ | Just u <- up, bValue u <= c -> pure Nothing+ | Just l <- lo, bValue l > c -> pure (Just (reason <> bReason l))+ | otherwise -> do+ record sx v True up+ modifyIORef' (sxUpper sx) (IntMap.insert v (Bound c reason))+ basic <- isBasic sx v+ when basic $ modifyIORef' (sxDirty sx) (IntSet.insert v)+ x <- value sx v+ when (not basic && x > c) $ update sx v c+ pure Nothing++-- | Assert @v >= c@.+assertLower :: Simplex -> SVar -> Rational -> [Lit] -> IO (Maybe [Lit])+assertLower sx v c reason = do+ up <- upperBound sx v+ lo <- lowerBound sx v+ case () of+ _+ | Just l <- lo, bValue l >= c -> pure Nothing+ | Just u <- up, bValue u < c -> pure (Just (reason <> bReason u))+ | otherwise -> do+ record sx v False lo+ modifyIORef' (sxLower sx) (IntMap.insert v (Bound c reason))+ basic <- isBasic sx v+ when basic $ modifyIORef' (sxDirty sx) (IntSet.insert v)+ x <- value sx v+ when (not basic && x < c) $ update sx v c+ pure Nothing++-- | Change the value of a nonbasic variable, updating the basic ones.+update :: Simplex -> SVar -> Rational -> IO ()+update sx v new = do+ old <- value sx v+ let delta = new - old+ rows <- readIORef (sxRows sx)+ cols <- readIORef (sxCols sx)+ let affectedSet = IntMap.findWithDefault IntSet.empty v cols+ affected = IntSet.toList affectedSet+ modifyIORef' (sxDirty sx) (IntSet.union affectedSet)+ modifyIORef' (sxValue sx) $ \vals ->+ foldl'+ (\m b -> IntMap.adjust (+ (rows IntMap.! b IntMap.! v) * delta) b m)+ (IntMap.insert v new vals)+ affected++-------------------------------------------------------------------------------+-- Checking++-- | Restore feasibility. Returns an explanation (a set of bound+-- justifications) when the bounds are infeasible. Bland's rule (smallest+-- variable first) guarantees termination. Only the basic variables that may+-- have become violated (@sxDirty@) are inspected.+check :: Simplex -> IO (Maybe [Lit])+check sx = loop+ where+ loop = do+ rows <- readIORef (sxRows sx)+ dirty <- readIORef (sxDirty sx)+ vals <- readIORef (sxValue sx)+ lows <- readIORef (sxLower sx)+ ups <- readIORef (sxUpper sx)+ let valOf x = IntMap.findWithDefault 0 x vals+ violation b+ | Just l <- IntMap.lookup b lows, valOf b < bValue l = Just (b, True, l)+ | Just u <- IntMap.lookup b ups, valOf b > bValue u = Just (b, False, u)+ | otherwise = Nothing+ -- Dirty variables that are no longer basic or not violated can be+ -- dropped; the first violated one stays.+ let candidates = filter (`IntMap.member` rows) (IntSet.toAscList dirty)+ rest = dropWhile (isNothing . violation) candidates+ writeIORef (sxDirty sx) (IntSet.fromList rest)+ case firstJust violation rest of+ Nothing -> pure Nothing+ Just (b, tooLow, bnd) -> do+ let row = rows IntMap.! b+ canIncrease x = maybe True (\u -> valOf x < bValue u) (IntMap.lookup x ups)+ canDecrease x = maybe True (\l -> valOf x > bValue l) (IntMap.lookup x lows)+ -- To raise b, raise x when a > 0 or lower it when a < 0.+ suitable (x, a)+ | tooLow = if a > 0 then canIncrease x else canDecrease x+ | otherwise = if a > 0 then canDecrease x else canIncrease x+ case filter suitable (IntMap.toList row) of+ ((x, _) : _) -> do+ pivotAndUpdate sx b x (bValue bnd)+ -- The entering variable may now violate its own bounds.+ modifyIORef' (sxDirty sx) (IntSet.insert x)+ loop+ [] -> do+ let blocking (x, a)+ | tooLow == (a > 0) = maybe [] bReason (IntMap.lookup x ups)+ | otherwise = maybe [] bReason (IntMap.lookup x lows)+ pure (Just (bReason bnd <> concatMap blocking (IntMap.toList row)))++ firstJust f = \case+ [] -> Nothing+ (x : xs) -> maybe (firstJust f xs) Just (f x)++-- | Set basic @b@ to @v@ by moving nonbasic @x@, then swap their roles.+pivotAndUpdate :: Simplex -> SVar -> SVar -> Rational -> IO ()+pivotAndUpdate sx b x v = do+ rows <- readIORef (sxRows sx)+ vb <- value sx b+ let a = rows IntMap.! b IntMap.! x+ theta = (v - vb) / a+ vx <- value sx x+ update sx x (vx + theta)+ pivot sx b x++-- | Make nonbasic @x@ basic and basic @b@ nonbasic.+pivot :: Simplex -> SVar -> SVar -> IO ()+pivot sx b x = do+ rows <- readIORef (sxRows sx)+ cols <- readIORef (sxCols sx)+ let rowB = rows IntMap.! b+ a = rowB IntMap.! x+ -- x = (b - sum_{k /= x} a_k k) / a+ rowX =+ IntMap.insert b (1 / a) (IntMap.map (\c -> negate c / a) (IntMap.delete x rowB))+ others = IntSet.toList (IntSet.delete b (IntMap.findWithDefault IntSet.empty x cols))+ substitute r =+ let c = r IntMap.! x+ in IntMap.filter (/= 0) (IntMap.unionWith (+) (IntMap.delete x r) (IntMap.map (* c) rowX))+ newRows = foldl' (\m o -> IntMap.adjust substitute o m) (IntMap.insert x rowX (IntMap.delete b rows)) others+ writeIORef (sxRows sx) newRows+ -- Rebuild the column index of the affected rows.+ let touched = x : others+ removeOld m r =+ foldl' (\acc y -> IntMap.adjust (IntSet.delete r) y acc) m (IntMap.keys (rows IntMap.! r))+ addNew m r =+ foldl' (\acc y -> IntMap.insertWith IntSet.union y (IntSet.singleton r) acc) m (IntMap.keys (newRows IntMap.! r))+ cols1 = foldl' removeOld (IntMap.delete x cols) (b : others)+ cols2 = foldl' addNew cols1 touched+ writeIORef (sxCols sx) (IntMap.filter (not . IntSet.null) cols2)++-------------------------------------------------------------------------------+-- Cuts++-- | A Gomory mixed-integer cut for a basic variable with a fractional value,+-- assuming every variable must be integral. Returns @(coefficients, k,+-- justification)@ for the cut @sum c_j x_j >= k@, which the current+-- assignment violates and every integral solution of the bounds in the+-- justification satisfies. Requires every nonbasic variable of the row to+-- sit at one of its bounds.+--+-- Writing each nonbasic variable as @x_j = l_j + y_j@ (at its lower bound)+-- or @x_j = u_j - y_j@ (at its upper bound), with @y_j >= 0@, the row reads+-- @x_i + sum d_j y_j = v_i@, where @d_j@ is minus the coefficient of @y_j@,+-- and the cut is+-- @sum_{f_j <= f0} (f_j / f0) y_j + sum_{f_j > f0} ((1 - f_j) / (1 - f0)) y_j >= 1@,+-- where @f@ is the fractional part, @f0 = f(v_i)@ and @f_j = f(d_j)@.+gomoryCut :: Simplex -> SVar -> IO (Maybe ([(Rational, SVar)], Rational, [Lit]))+gomoryCut sx xi = do+ rows <- readIORef (sxRows sx)+ vals <- readIORef (sxValue sx)+ lows <- readIORef (sxLower sx)+ ups <- readIORef (sxUpper sx)+ let valOf x = IntMap.findWithDefault 0 x vals+ frac q = q - fromInteger (floor q)+ f0 = frac (valOf xi)+ atBound (x, a)+ | Just l <- IntMap.lookup x lows, bValue l == valOf x = Just (x, a, True, l)+ | Just u <- IntMap.lookup x ups, bValue u == valOf x = Just (x, negate a, False, u)+ | otherwise = Nothing+ -- c is the coefficient of y_j in x_i = v_i + sum c_j y_j.+ coefficient c+ | frac (negate c) <= f0 = frac (negate c) / f0+ | otherwise = (1 - frac (negate c)) / (1 - f0)+ pure $ case IntMap.lookup xi rows of+ Just row+ | f0 /= 0+ , Just terms <- traverse atBound (IntMap.toList row) ->+ let cut =+ [ (if atLower then e else negate e, x, if atLower then e * bValue b else negate e * bValue b, bReason b)+ | (x, c, atLower, b) <- terms+ , let e = coefficient c+ , e /= 0+ ]+ in Just+ ( [(c, x) | (c, x, _, _) <- cut]+ , 1 + sum [k | (_, _, k, _) <- cut]+ , concat [r | (_, _, _, r) <- cut]+ )+ _ -> Nothing
+ src/HSMT/Theory/BitBlast.hs view
@@ -0,0 +1,401 @@+-- | Bit-blasting: Boolean circuits for the bit-vector operators.+--+-- A bit-vector is a list of SAT literals, least significant bit first.+-- Gates are encoded with Tseitin clauses, simplified when an input is a+-- constant, and shared through a structural hash table, so building the+-- same gate twice yields the same literal.+--+-- Clauses go to a replaceable sink: while assertions are encoded they are+-- added to the SAT solver directly, and during search they are queued and+-- handed to the solver as theory lemmas.+--+-- The semantics follows SMT-LIB, including division by zero:+-- @bvudiv x 0 = ~0@ and @bvurem x 0 = x@.+module HSMT.Theory.BitBlast+ ( Circuit+ , Bits+ , newCircuit+ , setSink+ , emitClause+ -- * Gates+ , cTrue+ , cFalse+ , isConstLit+ , andG+ , orG+ , xorG+ , iteG+ , andN+ , orN+ -- * Bit-vectors+ , constBits+ , freshBits+ , bvNot+ , bvAnd+ , bvOr+ , bvXor+ , bvNeg+ , bvAdd+ , bvSub+ , bvMul+ , bvUDiv+ , bvURem+ , bvSDiv+ , bvSRem+ , bvSMod+ , bvShl+ , bvLShr+ , bvAShr+ , bvIte+ , bvEq+ , bvULt+ , bvULe+ , bvSLt+ , bvSLe+ , bitsValue+ ) where++import Control.Monad (forM, forM_, replicateM)+import Data.Bits (shiftL, testBit)+import Data.IORef+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map++import HSMT.SAT.Types++-- | A bit-vector: one literal per bit, least significant bit first.+type Bits = [Lit]++-- | A circuit builder: allocates gate outputs, emits their Tseitin clauses+-- to the current sink and shares structurally equal gates.+data Circuit = Circuit+ { cNewVar :: IO Var+ , cSink :: IORef ([Lit] -> IO ())+ , cTrueLit :: Lit+ , cGates :: IORef (Map (Int, Lit, Lit, Lit) Lit)+ -- ^ Gate kind (0: and, 1: xor, 2: ite) and inputs to output.+ , cDivRem :: IORef (Map (Bits, Bits) (Bits, Bits))+ -- ^ Quotient and remainder of each unsigned division.+ }++-- | A circuit builder from a variable allocator, an initial clause sink and+-- the literal that is always true.+newCircuit :: IO Var -> ([Lit] -> IO ()) -> Lit -> IO Circuit+newCircuit nv sink t = Circuit nv <$> newIORef sink <*> pure t <*> newIORef Map.empty <*> newIORef Map.empty++-- | Replace the clause sink; later clauses go to the new sink.+setSink :: Circuit -> ([Lit] -> IO ()) -> IO ()+setSink c = writeIORef (cSink c)++-- | Send a clause to the current sink.+emitClause :: Circuit -> [Lit] -> IO ()+emitClause = emit++emit :: Circuit -> [Lit] -> IO ()+emit c cl = readIORef (cSink c) >>= \f -> f cl++fresh :: Circuit -> IO Lit+fresh c = posLit <$> cNewVar c++-- | The constant true and false literals of the circuit.+cTrue, cFalse :: Circuit -> Lit+cTrue = cTrueLit+cFalse = litNeg . cTrueLit++-- | @Just b@ when the literal is the constant @b@.+isConstLit :: Circuit -> Lit -> Maybe Bool+isConstLit c l+ | l == cTrue c = Just True+ | l == cFalse c = Just False+ | otherwise = Nothing++-------------------------------------------------------------------------------+-- Gates++cached :: Circuit -> (Int, Lit, Lit, Lit) -> (Lit -> [[Lit]]) -> IO Lit+cached c key clauses =+ Map.lookup key <$> readIORef (cGates c) >>= \case+ Just x -> pure x+ Nothing -> do+ x <- fresh c+ mapM_ (emit c) (clauses x)+ modifyIORef' (cGates c) (Map.insert key x)+ pure x++-- | Conjunction of two literals.+andG :: Circuit -> Lit -> Lit -> IO Lit+andG c a b+ | a == cFalse c || b == cFalse c = pure (cFalse c)+ | a == cTrue c = pure b+ | b == cTrue c = pure a+ | a == b = pure a+ | a == litNeg b = pure (cFalse c)+ | otherwise =+ let (x, y) = (min a b, max a b)+ in cached c (0, x, y, x) $ \o -> [[litNeg o, x], [litNeg o, y], [o, litNeg x, litNeg y]]++-- | Disjunction of two literals.+orG :: Circuit -> Lit -> Lit -> IO Lit+orG c a b = litNeg <$> andG c (litNeg a) (litNeg b)++-- | Exclusive or of two literals.+xorG :: Circuit -> Lit -> Lit -> IO Lit+xorG c a b+ | Just va <- isConstLit c a = pure (if va then litNeg b else b)+ | Just vb <- isConstLit c b = pure (if vb then litNeg a else a)+ | a == b = pure (cFalse c)+ | a == litNeg b = pure (cTrue c)+ | otherwise = do+ -- Normalize to positive inputs; each negation flips the output.+ let flips = litSign a /= litSign b+ pa = if litSign a then litNeg a else a+ pb = if litSign b then litNeg b else b+ (x, y) = (min pa pb, max pa pb)+ o <-+ cached c (1, x, y, x) $ \o ->+ [ [litNeg o, x, y]+ , [litNeg o, litNeg x, litNeg y]+ , [o, litNeg x, y]+ , [o, x, litNeg y]+ ]+ pure (if flips then litNeg o else o)++-- | @iteG c s a b@ is @a@ when @s@ holds and @b@ otherwise.+iteG :: Circuit -> Lit -> Lit -> Lit -> IO Lit+iteG c s a b+ | Just vs <- isConstLit c s = pure (if vs then a else b)+ | a == b = pure a+ | a == cTrue c = orG c s b+ | a == cFalse c = andG c (litNeg s) b+ | b == cTrue c = orG c (litNeg s) a+ | b == cFalse c = andG c s a+ | otherwise =+ cached c (2, s, a, b) $ \o ->+ [ [litNeg o, litNeg s, a]+ , [litNeg o, s, b]+ , [o, litNeg s, litNeg a]+ , [o, s, litNeg b]+ ]++-- | Conjunction of a list of literals ('cTrue' when empty).+andN :: Circuit -> [Lit] -> IO Lit+andN c = foldlM' (andG c) (cTrue c)++-- | Disjunction of a list of literals ('cFalse' when empty).+orN :: Circuit -> [Lit] -> IO Lit+orN c = foldlM' (orG c) (cFalse c)++foldlM' :: (b -> a -> IO b) -> b -> [a] -> IO b+foldlM' f = go+ where+ go acc [] = pure acc+ go acc (x : xs) = f acc x >>= \acc' -> go acc' xs++-------------------------------------------------------------------------------+-- Bit-vectors++-- | @constBits c w v@ is the constant vector of width @w@ holding the low+-- @w@ bits of @v@ (two's complement for negative @v@).+constBits :: Circuit -> Int -> Integer -> Bits+constBits c w v = [if testBit v i then cTrue c else cFalse c | i <- [0 .. w - 1]]++-- | A vector of @w@ fresh, unconstrained bits.+freshBits :: Circuit -> Int -> IO Bits+freshBits c w = replicateM w (fresh c)++-- | Bitwise negation; needs no gates.+bvNot :: Bits -> Bits+bvNot = map litNeg++-- | Bitwise and, or and xor of two vectors of the same width.+bvAnd, bvOr, bvXor :: Circuit -> Bits -> Bits -> IO Bits+bvAnd c = zipWithM' (andG c)+bvOr c = zipWithM' (orG c)+bvXor c = zipWithM' (xorG c)++zipWithM' :: (a -> b -> IO d) -> [a] -> [b] -> IO [d]+zipWithM' f xs ys = sequence (zipWith f xs ys)++-- | Sum with a carry-in, truncated to the width of the inputs.+addWithCarry :: Circuit -> Lit -> Bits -> Bits -> IO Bits+addWithCarry c = go+ where+ go _ [] _ = pure []+ go _ _ [] = pure []+ go carry (a : as) (b : bs) = do+ ab <- xorG c a b+ s <- xorG c ab carry+ g <- andG c a b+ p <- andG c ab carry+ carry' <- orG c g p+ (s :) <$> go carry' as bs++-- | Ripple-carry sum, truncated to the width of the inputs (modulo @2^w@).+bvAdd :: Circuit -> Bits -> Bits -> IO Bits+bvAdd c = addWithCarry c (cFalse c)++-- | @a - b = a + ~b + 1@.+bvSub :: Circuit -> Bits -> Bits -> IO Bits+bvSub c a b = addWithCarry c (cTrue c) a (bvNot b)++-- | Two's complement negation, @0 - a@.+bvNeg :: Circuit -> Bits -> IO Bits+bvNeg c a = bvSub c (map (const (cFalse c)) a) a++-- | Shift-and-add multiplier, truncated to the width of the inputs.+bvMul :: Circuit -> Bits -> Bits -> IO Bits+bvMul c a b = foldlM' step (map (const (cFalse c)) a) (zip [0 ..] b)+ where+ w = length a+ step acc (i, bi) = do+ partial <- mapM (andG c bi) (take (w - i) a)+ bvAdd c acc (replicate i (cFalse c) <> partial)++-- | Unsigned quotient and remainder. They are fresh vectors constrained by+-- @a = q * b + r@ and @r < b@ when @b /= 0@, computed in double width so+-- that the product cannot overflow, and by @q = ~0@, @r = a@ when @b = 0@.+udivRem :: Circuit -> Bits -> Bits -> IO (Bits, Bits)+udivRem c a b =+ Map.lookup (a, b) <$> readIORef (cDivRem c) >>= \case+ Just qr -> pure qr+ Nothing -> do+ let w = length a+ zeros = replicate w (cFalse c)+ q <- freshBits c w+ r <- freshBits c w+ bz <- litNeg <$> orN c b+ -- b = 0+ forM_ q $ \qi -> emit c [litNeg bz, qi]+ forM_ (zip r a) $ \(ri, ai) -> do+ emit c [litNeg bz, litNeg ri, ai]+ emit c [litNeg bz, ri, litNeg ai]+ -- b /= 0+ prod <- bvMul c (q <> zeros) (b <> zeros)+ total <- bvAdd c prod (r <> zeros)+ exact <- bvEq c total (a <> zeros)+ smaller <- bvULt c r b+ emit c [bz, exact]+ emit c [bz, smaller]+ modifyIORef' (cDivRem c) (Map.insert (a, b) (q, r))+ pure (q, r)++-- | Unsigned quotient and remainder; both share one division circuit.+-- Division by zero gives @~0@ (quotient) and the dividend (remainder).+bvUDiv, bvURem :: Circuit -> Bits -> Bits -> IO Bits+bvUDiv c a b = fst <$> udivRem c a b+bvURem c a b = snd <$> udivRem c a b++msb :: Bits -> Lit+msb = last++-- | Absolute value in two's complement.+absBits :: Circuit -> Bits -> IO Bits+absBits c a = do+ n <- bvNeg c a+ bvIte c (msb a) n a++-- | Signed division, defined by SMT-LIB through unsigned division of the+-- absolute values.+bvSDiv :: Circuit -> Bits -> Bits -> IO Bits+bvSDiv c a b = do+ ua <- absBits c a+ ub <- absBits c b+ u <- bvUDiv c ua ub+ negative <- xorG c (msb a) (msb b)+ nu <- bvNeg c u+ bvIte c negative nu u++-- | Signed remainder; its sign follows the dividend.+bvSRem :: Circuit -> Bits -> Bits -> IO Bits+bvSRem c a b = do+ ua <- absBits c a+ ub <- absBits c b+ u <- bvURem c ua ub+ nu <- bvNeg c u+ bvIte c (msb a) nu u++-- | Signed modulo; its sign follows the divisor.+bvSMod :: Circuit -> Bits -> Bits -> IO Bits+bvSMod c a b = do+ ua <- absBits c a+ ub <- absBits c b+ u <- bvURem c ua ub+ nu <- bvNeg c u+ zero <- litNeg <$> orN c u+ negPlusB <- bvAdd c nu b+ uPlusB <- bvAdd c u b+ let (sa, sb) = (msb a, msb b)+ -- (sa, sb) = (0,0): u; (1,0): -u + b; (0,1): u + b; (1,1): -u+ whenNegA <- bvIte c sb nu negPlusB+ whenPosA <- bvIte c sb uPlusB u+ r <- bvIte c sa whenNegA whenPosA+ bvIte c zero u r++-- | Barrel shifter. @fill@ is the bit shifted in; shift amounts of at least+-- the width produce a vector of fill bits.+shiftBy :: Circuit -> (Int -> Bits -> Bits) -> Lit -> Bits -> Bits -> IO Bits+shiftBy c shiftConst fill a b = do+ let w = length a+ stages = [(k, bk) | (k, bk) <- zip [0 :: Int ..] b, (1 `shiftL` k) < w]+ overflowBits = [bk | (k, bk) <- zip [0 :: Int ..] b, (1 `shiftL` k) >= w]+ shifted <-+ foldlM'+ (\cur (k, bk) -> bvIte c bk (shiftConst (1 `shiftL` k) cur) cur)+ a+ stages+ overflow <- orN c overflowBits+ bvIte c overflow (replicate w fill) shifted++-- | Shift left by the unsigned amount in the second vector, filling with+-- zeros.+bvShl :: Circuit -> Bits -> Bits -> IO Bits+bvShl c a = shiftBy c (\k xs -> take (length xs) (replicate k (cFalse c) <> xs)) (cFalse c) a++-- | Logical shift right by the unsigned amount in the second vector,+-- filling with zeros.+bvLShr :: Circuit -> Bits -> Bits -> IO Bits+bvLShr c a = shiftBy c (\k xs -> drop k xs <> replicate (min k (length xs)) (cFalse c)) (cFalse c) a++-- | Arithmetic shift right by the unsigned amount in the second vector,+-- filling with copies of the sign bit.+bvAShr :: Circuit -> Bits -> Bits -> IO Bits+bvAShr c a = shiftBy c (\k xs -> drop k xs <> replicate (min k (length xs)) (msb xs)) (msb a) a++-- | @bvIte c s a b@ is @a@ when @s@ holds and @b@ otherwise, bit by bit.+bvIte :: Circuit -> Lit -> Bits -> Bits -> IO Bits+bvIte c s = zipWithM' (iteG c s)++-- | The literal of @a = b@, for vectors of the same width.+bvEq :: Circuit -> Bits -> Bits -> IO Lit+bvEq c a b = do+ diffs <- zipWithM' (xorG c) a b+ litNeg <$> orN c diffs++-- | Unsigned @a < b@, scanning from the least significant bit: the most+-- significant differing bit decides.+bvULt :: Circuit -> Bits -> Bits -> IO Lit+bvULt c a b = foldlM' step (cFalse c) (zip a b)+ where+ step lt (ai, bi) = do+ differ <- xorG c ai bi+ iteG c differ bi lt++-- | Unsigned @a <= b@.+bvULe :: Circuit -> Bits -> Bits -> IO Lit+bvULe c a b = litNeg <$> bvULt c b a++-- | Signed comparisons flip the sign bits and compare unsigned.+bvSLt :: Circuit -> Bits -> Bits -> IO Lit+bvSLt c a b = bvULt c (flipMsb a) (flipMsb b)+ where+ flipMsb xs = init xs <> [litNeg (last xs)]++-- | Signed (two's complement) @a <= b@.+bvSLe :: Circuit -> Bits -> Bits -> IO Lit+bvSLe c a b = litNeg <$> bvSLt c b a++-- | The unsigned value of a vector under an assignment.+bitsValue :: (Lit -> IO Bool) -> Bits -> IO Integer+bitsValue val bs = do+ vs <- forM bs val+ pure (sum [if v then 1 `shiftL` i else 0 | (i, v) <- zip [0 ..] vs])
+ src/HSMT/Theory/EUF.hs view
@@ -0,0 +1,570 @@+-- | Equality with uninterpreted functions (EUF).+--+-- Congruence closure with explanations: equivalence classes are maintained+-- with union-by-size, congruences are found through a signature table, and+-- every merge is recorded in a proof forest (Nieuwenhuis & Oliveras, "Fast+-- congruence closure and extensions", 2007) so that conflicts can be+-- explained by the literals that caused them.+--+-- The whole closure state is a persistent value. Backtracking restores the+-- snapshot taken when the decision level was opened, which keeps the+-- implementation simple at the cost of a logarithmic factor.+--+-- Besides detecting conflicts, the solver propagates atoms implied by the+-- closure and adds transitivity lemmas on conflicts. Finite sorts need no+-- special care: bit-vector terms are bit-blasted, and the engine keeps their+-- classes consistent with their bits through theory combination.+module HSMT.Theory.EUF+ ( -- * Building+ EUF+ , NodeKind (..)+ , Atom (..)+ , newEUF+ , addNode+ , addAtom+ , isRegistered+ , hasNodes+ , trueNode+ , falseNode+ , setEqAtomMaker+ , setValueOracle+ -- * Solving+ , eufHooks+ -- * Models+ , ClassInfo (..)+ , finalClasses+ , registeredNodes+ -- * Theory combination+ , currentClass+ , currentClasses+ , explainEqual+ ) where++import Data.IORef+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IntMap+import qualified Data.IntSet as IntSet+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set++import HSMT.Core.Op+import HSMT.SAT.Types++-- | How a term takes part in congruence closure.+data NodeKind+ = Leaf+ -- ^ No congruence (constants, Boolean formulas linked to literals).+ | AppNode !Op ![Int]+ -- ^ Application whose congruence class depends on its arguments.+ deriving (Eq, Show)++-- | Meaning of a SAT variable for the theory.+data Atom+ = AEq !Int !Int+ -- ^ The variable is the equality of two terms.+ | ABool !Int !Bool+ -- ^ The variable decides the value of a Boolean term. When the flag is+ -- 'False' the term holds iff the variable is false.+ deriving (Eq, Show)++data Reason+ = RLit !Lit+ | RCong !Int !Int+ -- ^ The two applications are congruent.+ deriving (Show)++data EState = EState+ { esRepr :: !(IntMap Int)+ -- ^ Representative of each term (absent means itself).+ , esMembers :: !(IntMap [Int])+ -- ^ Members of each class, keyed by representative.+ , esUses :: !(IntMap [Int])+ -- ^ Applications having an argument in the class.+ , esSig :: !(Map (Op, [Int]) Int)+ -- ^ Signature table: operator and argument representatives.+ , esConst :: !(IntMap Int)+ -- ^ The constant (literal value) a class contains, if any.+ , esParent :: !(IntMap (Int, Reason))+ -- ^ Proof forest edges.+ , esDiseqs :: !(IntMap [(Int, Int, Lit)])+ -- ^ Asserted disequalities with the literal that asserted them,+ -- indexed by both sides.+ }++-- | The EUF solver: registered terms and atoms, the current closure state+-- and the snapshots of the open decision levels.+data EUF = EUF+ { eNodes :: !(IORef (IntMap NodeKind))+ , eConsts :: !(IORef IntSet.IntSet)+ -- ^ Terms that denote literal values; distinct constants are distinct.+ , eAtoms :: !(IORef (IntMap [Atom]))+ , eTrue :: !Int+ , eFalse :: !Int+ , eState :: !(IORef EState)+ , eStack :: !(IORef [EState])+ , eConflict :: !(IORef (Maybe [Lit]))+ , ePending :: !(IORef [[Lit]])+ -- ^ Transitivity lemmas produced with the current conflict.+ , eFinal :: !(IORef (Maybe EState))+ , eMkEq :: !(IORef (Maybe (Int -> Int -> IO Lit)))+ -- ^ Creates (or finds) the equality atom of two terms.+ , eLemmaKeys :: !(IORef (Set.Set (Int, Int, Int)))+ -- ^ Transitivity lemmas already produced, as (n0, previous, next).+ , eAtomsByTerm :: !(IORef (IntMap [(Var, Atom)]))+ -- ^ Atoms mentioning each term.+ , eCandidates :: !(IORef [(Var, Atom)])+ -- ^ Atoms that may have become implied since the last check.+ , eValue :: !(IORef (Maybe (Lit -> IO LBool)))+ -- ^ Current value of a literal in the SAT solver.+ }++-- | Create an empty EUF solver. The arguments are the term ids of the+-- constants @true@ and @false@.+newEUF :: Int -> Int -> IO EUF+newEUF t f = do+ euf <-+ EUF+ <$> newIORef IntMap.empty+ <*> newIORef IntSet.empty+ <*> newIORef IntMap.empty+ <*> pure t+ <*> pure f+ <*> newIORef emptyState+ <*> newIORef []+ <*> newIORef Nothing+ <*> newIORef []+ <*> newIORef Nothing+ <*> newIORef Nothing+ <*> newIORef Set.empty+ <*> newIORef IntMap.empty+ <*> newIORef []+ <*> newIORef Nothing+ addNode euf t Leaf True+ addNode euf f Leaf True+ pure euf++emptyState :: EState+emptyState = EState IntMap.empty IntMap.empty IntMap.empty Map.empty IntMap.empty IntMap.empty IntMap.empty++-- | Provide the function creating equality atoms, which enables+-- transitivity lemmas (see @transitivityLemmas@).+setEqAtomMaker :: EUF -> (Int -> Int -> IO Lit) -> IO ()+setEqAtomMaker euf f = writeIORef (eMkEq euf) (Just f)++-- | Provide access to the current assignment, which enables theory+-- propagation.+setValueOracle :: EUF -> (Lit -> IO LBool) -> IO ()+setValueOracle euf f = writeIORef (eValue euf) (Just f)++-- | Term ids of the constants @true@ and @false@ given to 'newEUF'.+trueNode, falseNode :: EUF -> Int+trueNode = eTrue+falseNode = eFalse++-- | Whether a term id was registered with 'addNode'.+isRegistered :: EUF -> Int -> IO Bool+isRegistered euf t = IntMap.member t <$> readIORef (eNodes euf)++-- | True when terms other than @true@ and @false@ were registered.+hasNodes :: EUF -> IO Bool+hasNodes euf = (> 2) . IntMap.size <$> readIORef (eNodes euf)++-- | Every registered term with its kind, by term id.+registeredNodes :: EUF -> IO (IntMap NodeKind)+registeredNodes = readIORef . eNodes++-- | Register a term. Arguments of applications must be registered first.+-- The flag marks terms denoting literal values.+--+-- Terms may also be registered during search (array axioms create new+-- applications). The term is then added to every saved snapshot as well, so+-- that backtracking does not forget it; when its signature is already in a+-- snapshot's table, it is merged with the congruent application there.+addNode :: EUF -> Int -> NodeKind -> Bool -> IO ()+addNode euf t kind isConst = do+ modifyIORef' (eNodes euf) (IntMap.insert t kind)+ if isConst then modifyIORef' (eConsts euf) (IntSet.insert t) else pure ()+ nodes <- readIORef (eNodes euf)+ (st, touched) <- insertNode nodes t kind isConst <$> readIORef (eState euf)+ writeIORef (eState euf) st+ modifyIORef' (eStack euf) (map (fst . insertNode nodes t kind isConst))+ byTerm <- readIORef (eAtomsByTerm euf)+ modifyIORef' (eCandidates euf) (concatMap (\x -> IntMap.findWithDefault [] x byTerm) touched ++)++-- | Add a new term to a closure state.+insertNode :: IntMap NodeKind -> Int -> NodeKind -> Bool -> EState -> (EState, [Int])+insertNode nodes t kind isConst st =+ let st1 = if isConst then st {esConst = IntMap.insert t t (esConst st)} else st+ in case kind of+ Leaf -> (st1, [])+ AppNode op args ->+ let sig = (op, map (find st1) args)+ st2 =+ st1+ { esUses =+ foldl'+ (\m a -> IntMap.insertWith (++) (find st1 a) [t] m)+ (esUses st1)+ (IntSet.toList (IntSet.fromList args))+ }+ in case Map.lookup sig (esSig st2) of+ Just v+ | v /= t ->+ -- A new term has no constant and no uses, so merging+ -- it cannot conflict.+ case merge nodes t v (RCong t v) st2 of+ Right r -> r+ Left (st', _, _) -> (st', [])+ _ -> (st2 {esSig = Map.insert sig t (esSig st2)}, [])++-- | Attach an atom to a SAT variable.+addAtom :: EUF -> Var -> Atom -> IO ()+addAtom euf v a = do+ modifyIORef' (eAtoms euf) (IntMap.insertWith (++) v [a])+ let terms = case a of+ AEq x y -> [x, y]+ ABool t _ -> [t]+ modifyIORef' (eAtomsByTerm euf) $ \m ->+ foldl' (\acc t -> IntMap.insertWith (++) t [(v, a)] acc) m terms++-------------------------------------------------------------------------------+-- Congruence closure++find :: EState -> Int -> Int+find st t = IntMap.findWithDefault t t (esRepr st)++members :: EState -> Int -> [Int]+members st r = IntMap.findWithDefault [r] r (esMembers st)++-- | Merge two terms and close under congruence. On conflict, returns the+-- state in which two distinct constants became equal, and the constants.+-- Otherwise returns the new state and the terms whose atoms may now be+-- implied.+merge :: IntMap NodeKind -> Int -> Int -> Reason -> EState -> Either (EState, Int, Int) (EState, [Int])+merge nodes a0 b0 r0 st0 = go [(a0, b0, r0)] [] st0+ where+ go [] touched st = Right (st, touched)+ go ((a, b, r) : rest) touched st+ | find st a == find st b = go rest touched st+ | otherwise =+ let ra = find st a+ rb = find st b+ -- Proof forest: a -> b, labelled with the reason.+ st1 = st {esParent = IntMap.insert a (b, r) (reroot a (esParent st))}+ (small, big) =+ if length (members st ra) <= length (members st rb) then (ra, rb) else (rb, ra)+ moved = members st small+ st2 =+ st1+ { esRepr = foldl' (\m x -> IntMap.insert x big m) (esRepr st1) moved+ , esMembers =+ IntMap.insert big (moved ++ members st big) (IntMap.delete small (esMembers st1))+ }+ constClash = case (IntMap.lookup small (esConst st), IntMap.lookup big (esConst st)) of+ (Just c1, Just c2) | c1 /= c2 -> Just (c1, c2)+ _ -> Nothing+ constFromSmall =+ IntMap.member small (esConst st) && not (IntMap.member big (esConst st))+ st3 = case IntMap.lookup small (esConst st) of+ Just c | constFromSmall -> st2 {esConst = IntMap.insert big c (esConst st2)}+ _ -> st2+ -- Atoms of moved terms may now relate terms of one class; if+ -- the class gained a constant, atoms of every member may now+ -- be decided by constants.+ touched' = moved ++ (if constFromSmall then members st big else []) ++ touched+ (st4, pending) = foldl' (rehash big) (st3, []) (IntMap.findWithDefault [] small (esUses st))+ in case constClash of+ Just (c1, c2) -> Left (st4, c1, c2)+ Nothing -> go (rest ++ pending) touched' st4++ rehash big (st, pending) u = case IntMap.lookup u nodes of+ Just (AppNode op args) ->+ let sig = (op, map (find st) args)+ st' = st {esUses = IntMap.insertWith (++) big [u] (esUses st)}+ in case Map.lookup sig (esSig st) of+ Just v+ | v /= u && find st v /= find st u -> (st', (u, v, RCong u v) : pending)+ | otherwise -> (st', pending)+ Nothing -> (st' {esSig = Map.insert sig u (esSig st')}, pending)+ _ -> (st, pending)++-- | Make @a@ the root of its proof tree by reversing the path to the root.+reroot :: Int -> IntMap (Int, Reason) -> IntMap (Int, Reason)+reroot a parents = case IntMap.lookup a parents of+ Nothing -> parents+ Just _ -> go a Nothing parents+ where+ go x newEdge ps =+ let old = IntMap.lookup x ps+ ps' = case newEdge of+ Nothing -> IntMap.delete x ps+ Just e -> IntMap.insert x e ps+ in case old of+ Nothing -> ps'+ Just (p, r) -> go p (Just (x, r)) ps'++-- | Literals that imply @a = b@, for two terms of the same class.+explain :: IntMap NodeKind -> EState -> Int -> Int -> [Lit]+explain nodes st a0 b0 = Set.toList (go [(a0, b0)] Set.empty Set.empty)+ where+ go [] _ acc = acc+ go ((a, b) : rest) seen acc+ | a == b || Set.member (a, b) seen = go rest seen acc+ | otherwise =+ let pathA = ancestors a+ pathB = ancestors b+ inB = IntSet.fromList (map fst pathB)+ lca = case filter (`IntSet.member` inB) (map fst pathA) of+ (c : _) -> c+ [] -> error "EUF.explain: terms are not in the same class"+ edges = takeWhile ((/= lca) . fst) pathA ++ takeWhile ((/= lca) . fst) pathB+ reasons = [r | (_, Just r) <- edges]+ lits = [l | RLit l <- reasons]+ congs = concat [argPairs u v | RCong u v <- reasons]+ in go (rest ++ congs) (Set.insert (a, b) seen) (foldr Set.insert acc lits)++ -- Path to the root: each node with the reason of its outgoing edge.+ ancestors x = case IntMap.lookup x (esParent st) of+ Nothing -> [(x, Nothing)]+ Just (p, r) -> (x, Just r) : ancestors p++ argPairs u v = case (IntMap.lookup u nodes, IntMap.lookup v nodes) of+ (Just (AppNode _ as), Just (AppNode _ bs)) -> zip as bs+ _ -> []++-- | Proof-forest edges on the path from @a@ to @b@, oriented from @a@.+proofPath :: EState -> Int -> Int -> [(Int, Int, Reason)]+proofPath st a b =+ let up x = case IntMap.lookup x (esParent st) of+ Nothing -> []+ Just (p, r) -> (x, p, r) : up p+ ea = up a+ eb = up b+ nodesB = IntSet.fromList (b : [p | (_, p, _) <- eb])+ lca = head' [x | x <- a : [p | (_, p, _) <- ea], x `IntSet.member` nodesB]+ toLca = takeWhile (\(x, _, _) -> x /= lca)+ in toLca ea ++ reverse [(p, x, r) | (x, p, r) <- toLca eb]+ where+ head' = \case+ (x : _) -> x+ [] -> error "EUF.proofPath: terms are not in the same class"++-- | Transitivity lemmas for a conflict between @a@ and @b@.+--+-- For every run n0 = n1 = ... = nk of asserted equalities on the proof path,+-- add the atoms @n0 = ni@ with lemmas @n0 = n(i-1) /\ n(i-1) = ni -> n0 = ni@.+-- Without them, problems such as chains of diamonds need exponentially+-- many conflicts, because learnt clauses could only mention the original+-- atoms.+transitivityLemmas :: EUF -> EState -> Int -> Int -> IO [[Lit]]+transitivityLemmas euf st a b =+ readIORef (eMkEq euf) >>= \case+ Nothing -> pure []+ Just mkEq -> do+ atoms <- readIORef (eAtoms euf)+ let isEqEdge (x, p, RLit l) =+ not (litSign l)+ && any (\case AEq u v -> (u, v) == (x, p) || (u, v) == (p, x); _ -> False)+ (IntMap.findWithDefault [] (litVar l) atoms)+ isEqEdge _ = False+ runs = filter ((>= 2) . length) (splitRuns isEqEdge (proofPath st a b))+ concat <$> mapM (lemmasForRun mkEq) runs+ where+ splitRuns p xs = case dropWhile (not . p) xs of+ [] -> []+ ys -> let (run, rest) = span p ys in run : splitRuns p rest+ lemmasForRun mkEq run = case run of+ ((n0, _, _) : _) ->+ fmap concat . mapM (step mkEq n0) $ drop 1 run+ [] -> pure []+ step mkEq n0 (prev, next, r) = do+ keys <- readIORef (eLemmaKeys euf)+ -- One lemma per way of reaching @next@: in a diamond, both branches+ -- must be able to derive the same shortcut.+ let key = (n0, prev, next)+ case r of+ RLit l | n0 /= next && Set.notMember key keys -> do+ modifyIORef' (eLemmaKeys euf) (Set.insert key)+ ePrev <- mkEq n0 prev+ eNext <- mkEq n0 next+ pure [[eNext, litNeg ePrev, litNeg l]]+ _ -> pure []++-- | Record a conflict between two terms of the same class.+raiseConflict :: EUF -> EState -> Int -> Int -> [Lit] -> IO ()+raiseConflict euf st a b extra = do+ nodes <- readIORef (eNodes euf)+ lemmas <- transitivityLemmas euf st a b+ writeIORef (eConflict euf) (Just (extra ++ explain nodes st a b))+ writeIORef (ePending euf) lemmas++-------------------------------------------------------------------------------+-- DPLL(T) interface++-- | Hooks connecting the EUF solver to the SAT engine.+eufHooks :: EUF -> TheoryHooks+eufHooks euf =+ TheoryHooks+ { thNewLevel = readIORef (eState euf) >>= \st -> modifyIORef' (eStack euf) (st :)+ , thBacktrack = \lvl -> do+ stack <- readIORef (eStack euf)+ let excess = length stack - lvl+ if excess <= 0+ then pure ()+ else case drop (excess - 1) stack of+ (st : older) -> do+ writeIORef (eState euf) st+ writeIORef (eStack euf) older+ writeIORef (eConflict euf) Nothing+ writeIORef (ePending euf) []+ writeIORef (eCandidates euf) []+ [] -> pure ()+ , thAssert = assertLit euf+ , thPropagate = check euf+ , thFinalCheck = do+ r <- check euf+ case r of+ TheoryOk -> readIORef (eState euf) >>= writeIORef (eFinal euf) . Just+ _ -> pure ()+ pure r+ }++assertLit :: EUF -> Lit -> IO ()+assertLit euf l = do+ conflict <- readIORef (eConflict euf)+ atoms <- IntMap.findWithDefault [] (litVar l) <$> readIORef (eAtoms euf)+ case conflict of+ Just _ -> pure ()+ Nothing -> mapM_ apply atoms+ where+ positive = not (litSign l)+ apply atom = do+ st <- readIORef (eState euf)+ nodes <- readIORef (eNodes euf)+ let result = case atom of+ AEq a b+ | positive -> merge nodes a b (RLit l) st+ | otherwise ->+ let d = [(a, b, l)]+ in Right (st {esDiseqs = IntMap.insertWith (++) a d (IntMap.insertWith (++) b d (esDiseqs st))}, [a])+ ABool t pol ->+ merge nodes t (if positive == pol then eTrue euf else eFalse euf) (RLit l) st+ case result of+ Right (st', touched) -> do+ writeIORef (eState euf) st'+ byTerm <- readIORef (eAtomsByTerm euf)+ modifyIORef' (eCandidates euf) (concatMap (\t -> IntMap.findWithDefault [] t byTerm) touched ++)+ -- A disequality can only become violated when one of its sides+ -- changes class (or when it is asserted).+ case [ d+ | t <- touched+ , d@(a, b, _) <- IntMap.findWithDefault [] t (esDiseqs st')+ , find st' a == find st' b+ ] of+ ((a, b, dl) : _) -> raiseConflict euf st' a b [dl]+ [] -> pure ()+ Left (st', c1, c2) -> raiseConflict euf st' c1 c2 []++check :: EUF -> IO TheoryResult+check euf = do+ conflict <- readIORef (eConflict euf)+ case conflict of+ Just _ -> report+ Nothing -> do+ st <- readIORef (eState euf)+ props <- propagations euf st+ pure (if null props then TheoryOk else TheoryLemmas (map removable props))+ where+ -- The conflict is reported as a clause, after the lemmas that introduce+ -- shortcut equalities.+ report = do+ expl <- maybe [] id <$> readIORef (eConflict euf)+ lemmas <- readIORef (ePending euf)+ writeIORef (ePending euf) []+ pure $+ if null lemmas+ then TheoryConflict expl+ else TheoryLemmas (map permanent lemmas ++ [removable (map litNeg expl)])++-- | Clauses propagating the atoms implied by the closure: equalities whose+-- sides are in one class, equalities between classes holding different+-- constants, and Boolean terms equal to @true@ or @false@. The implied+-- literal comes first, followed by the negated explanation.+propagations :: EUF -> EState -> IO [[Lit]]+propagations euf st = do+ candidates <- readIORef (eCandidates euf)+ writeIORef (eCandidates euf) []+ readIORef (eValue euf) >>= \case+ Nothing -> pure []+ Just value -> do+ nodes <- readIORef (eNodes euf)+ let expl = explain nodes st+ constOf t = IntMap.lookup (find st t) (esConst st)+ implied = \case+ (v, AEq a b)+ | find st a == find st b -> Just (posLit v, expl a b)+ | Just ca <- constOf a+ , Just cb <- constOf b+ , ca /= cb ->+ Just (negLit v, expl a ca ++ expl b cb)+ (v, ABool t pol)+ | find st t == find st (eTrue euf) ->+ Just (if pol then posLit v else negLit v, expl t (eTrue euf))+ | find st t == find st (eFalse euf) ->+ Just (if pol then negLit v else posLit v, expl t (eFalse euf))+ _ -> Nothing+ unique = IntMap.toList (IntMap.fromList candidates)+ fmap concat . mapM (\(v, a) -> clauseFor value (v, a) (implied (v, a))) $ unique+ where+ clauseFor value _ = \case+ Nothing -> pure []+ Just (l, reasons) ->+ value l >>= \case+ LUndef -> pure [l : map litNeg reasons]+ _ -> pure []++-------------------------------------------------------------------------------+-- Models++-- | The equivalence class of a term: its representative and its constant.+data ClassInfo = ClassInfo+ { ciRepr :: !Int+ -- ^ Representative term of the class.+ , ciConst :: !(Maybe Int)+ -- ^ The literal-value term of the class, if any.+ }+ deriving (Eq, Show)++-- | Class of every registered term in the last satisfying assignment.+finalClasses :: EUF -> IO (Maybe (IntMap ClassInfo))+finalClasses euf =+ readIORef (eFinal euf) >>= \case+ Nothing -> pure Nothing+ Just st -> do+ nodes <- readIORef (eNodes euf)+ pure . Just $+ IntMap.mapWithKey+ (\t _ -> let r = find st t in ClassInfo r (IntMap.lookup r (esConst st)))+ nodes++-------------------------------------------------------------------------------+-- Theory combination++-- | Representative of the class of a term in the current state.+currentClass :: EUF -> Int -> IO Int+currentClass euf t = (`find` t) <$> readIORef (eState euf)++-- | Class of every registered term in the current state.+currentClasses :: EUF -> IO (IntMap ClassInfo)+currentClasses euf = do+ st <- readIORef (eState euf)+ nodes <- readIORef (eNodes euf)+ pure (IntMap.mapWithKey (\t _ -> let r = find st t in ClassInfo r (IntMap.lookup r (esConst st))) nodes)++-- | Literals implying the equality of two terms of the same current class.+explainEqual :: EUF -> Int -> Int -> IO [Lit]+explainEqual euf a b = do+ st <- readIORef (eState euf)+ nodes <- readIORef (eNodes euf)+ pure (explain nodes st a b)
+ src/HSMT/Theory/FloatBlast.hs view
@@ -0,0 +1,732 @@+-- | Bit-blasting of the SMT-LIB floating-point theory.+--+-- A floating-point term of the format @(eb, sb)@ is the list of the+-- @eb + sb@ bits of its IEEE pattern, least significant first (trailing+-- significand, then exponent, then sign). Every NaN is the canonical+-- pattern ('HSMT.Core.Float.canonicalNaN'), so equality of values is+-- equality of bits; circuits keep this invariant and 'fpInvariant' imposes+-- it on unconstrained bits. A rounding mode is 3 bits holding+-- 'fromEnum' of 'HSMT.Core.Float.RoundingMode'.+--+-- Arithmetic unpacks its operands into a sign, a signed exponent and a+-- normalized significand (leading one at the top), computes a result with+-- enough extra bits and a sticky bit, and rounds it once (@roundTo@), as in+-- SymFPU (Brain, Schanda and Sun, 2019). Division and square root are+-- defined by constraints (@a = q b + r@ and @R^2 <= X < (R + 1)^2@), like+-- bit-vector division. The remainder iterates over the largest exponent+-- difference of the format, so its circuit grows with @2^eb@.+module HSMT.Theory.FloatBlast+ ( -- * Invariants+ fpInvariant+ , rmInvariant+ -- * Classification+ , fpIsNaN+ , fpIsInf+ , fpIsZero+ , fpIsNormal+ , fpIsSubnormal+ , fpIsNegative+ , fpIsPositive+ -- * Comparisons+ , fpLt+ , fpLeq+ , fpEq+ -- * Operations+ , fpAbs+ , fpNeg+ , fpFromFields+ , fpFromBits+ , fpAdd+ , fpSub+ , fpMul+ , fpDiv+ , fpFma+ , fpSqrt+ , fpRem+ , fpRoundToIntegral+ , fpMin+ , fpMax+ , fpConvert+ , fpFromInt+ , fpToInt+ ) where++import Control.Monad (foldM)++import HSMT.Core.Float (canonicalNaN)+import HSMT.SAT.Types+import HSMT.Theory.BitBlast (Bits, Circuit)+import qualified HSMT.Theory.BitBlast as BB++-- | A floating-point format: exponent and significand widths (the+-- significand width counts the hidden bit).+type Format = (Int, Int)++-------------------------------------------------------------------------------+-- Helpers++bitLen :: Int -> Int+bitLen n = length (takeWhile (> 0) (iterate (`div` 2) n))++-- | Width of the signed exponents of computations over the formats (and+-- over integers of the given widths): exponents and their differences stay+-- within @2^(eb + 1) + 4 sb@ in magnitude.+expWidth :: [Format] -> [Int] -> Int+expWidth fmts ints =+ bitLen (maximum ([2 ^ (eb + 1) + 4 * sb | (eb, sb) <- fmts] <> map (* 4) ints)) + 2++falses :: Circuit -> Int -> Bits+falses c k = replicate k (BB.cFalse c)++trues :: Circuit -> Int -> Bits+trues c k = replicate k (BB.cTrue c)++-- | A signed constant of the given width.+sconst :: Circuit -> Int -> Integer -> Bits+sconst c w k = BB.constBits c w (k `mod` (2 ^ w))++zext :: Circuit -> Int -> Bits -> Bits+zext c w bs = take w (bs <> falses c (w - length bs))++notL :: Lit -> Lit+notL = litNeg++orN, andN :: Circuit -> [Lit] -> IO Lit+orN = BB.orN+andN = BB.andN++-- | Priority selection: the first case whose condition holds.+select :: Circuit -> [(Lit, Bits)] -> Bits -> IO Bits+select c cases def = foldM (\acc (l, bs) -> BB.bvIte c l bs acc) def (reverse cases)++fields :: Format -> Bits -> (Bits, Bits, Lit)+fields (eb, sb) bs = (take (sb - 1) bs, take eb (drop (sb - 1) bs), bs !! (eb + sb - 1))++pattern :: Circuit -> Format -> Integer -> Bits+pattern c (eb, sb) = BB.constBits c (eb + sb)++nanBits :: Circuit -> Format -> Bits+nanBits c (eb, sb) = pattern c (eb, sb) (canonicalNaN eb sb)++infBits :: Circuit -> Format -> Lit -> Bits+infBits c (eb, sb) s = falses c (sb - 1) <> trues c eb <> [s]++zeroBits :: Circuit -> Format -> Lit -> Bits+zeroBits c (eb, sb) s = falses c (eb + sb - 1) <> [s]++-- | Shift left by a constant, within the width.+shl :: Circuit -> Int -> Bits -> Bits+shl c k bs = take (length bs) (falses c k <> bs)++-- | Normalize to a leading one at the top: the shifted bits and the shift+-- (the number of leading zeros, for a non-zero input).+normalize :: Circuit -> Bits -> IO (Bits, Bits)+normalize c bs0 = do+ let n = length bs0+ stages = reverse (takeWhile (< n) (iterate (* 2) 1))+ (bs, counts) <-+ foldM+ ( \(cur, cs) k -> do+ anyTop <- orN c (drop (n - k) cur)+ let z = notL anyTop+ cur' <- BB.bvIte c z (shl c k cur) cur+ pure (cur', z : cs)+ )+ (bs0, [])+ stages+ -- The last stage (shift by one) is the first count bit: low first.+ pure (bs, counts)++-- | Logical right shift by an unsigned amount, with the OR of the bits+-- shifted out.+shiftRightSticky :: Circuit -> Bits -> Bits -> IO (Bits, Lit)+shiftRightSticky c bs0 amount = do+ let n = length bs0+ foldM+ ( \(cur, st) (j, bit) -> do+ let k = 2 ^ (j :: Int) :: Int+ (out, shifted) =+ if k >= n+ then (cur, falses c n)+ else (take k cur, drop k cur <> falses c k)+ o <- orN c out+ lost <- BB.andG c bit o+ st' <- BB.orG c st lost+ cur' <- BB.bvIte c bit shifted cur+ pure (cur', st')+ )+ (bs0, BB.cFalse c)+ (zip [0 ..] amount)++-------------------------------------------------------------------------------+-- Rounding modes++data RM = RM {rmRNE, rmRNA, rmRTP, rmRTN :: Lit}++roundingMode :: Circuit -> Bits -> IO RM+roundingMode c bits = do+ let is k = BB.bvEq c bits (BB.constBits c 3 k)+ RM <$> is 0 <*> is 1 <*> is 2 <*> is 3++-- | Whether to increment a truncated magnitude: its sign, its least+-- significant bit, the first bit cut off and the OR of the others.+roundUp :: Circuit -> RM -> Lit -> Lit -> Lit -> Lit -> IO Lit+roundUp c rm s lsb g st = do+ gs <- BB.orG c g st+ ne <- BB.andG c g =<< BB.orG c st lsb+ up <- BB.andG c (notL s) gs+ down <- BB.andG c s gs+ orN c =<< sequence [BB.andG c (rmRNE rm) ne, BB.andG c (rmRNA rm) g, BB.andG c (rmRTP rm) up, BB.andG c (rmRTN rm) down]++-------------------------------------------------------------------------------+-- Unpacking and rounding++-- | A decoded operand. For finite non-zero values the value is+-- @sig * 2^(exp - (length sig - 1))@ with the top bit of @sig@ set; for the+-- other values @sig@ is @100..0@ (so that divisions are well defined).+data Unpacked = Unpacked+ { uNaN, uInf, uZero, uSign :: Lit+ , uExp :: Bits+ , uSig :: Bits+ }++unpack :: Circuit -> Format -> Int -> Bits -> IO Unpacked+unpack c (eb, sb) ew bits = do+ let (frac, ef, s) = fields (eb, sb) bits+ bias = 2 ^ (eb - 1) - 1 :: Integer+ allOnes <- andN c ef+ anyE <- orN c ef+ anyF <- orN c frac+ nan <- BB.andG c allOnes anyF+ inf <- BB.andG c allOnes (notL anyF)+ zero <- BB.andG c (notL anyE) (notL anyF)+ sub <- BB.andG c (notL anyE) anyF+ expNormal <- BB.bvSub c (zext c ew ef) (sconst c ew bias)+ (sigSub, lz) <- normalize c (frac <> [BB.cFalse c])+ expSub <- BB.bvSub c (sconst c ew (1 - bias)) (zext c ew lz)+ special <- orN c [nan, inf, zero]+ sig0 <- BB.bvIte c sub sigSub (frac <> [BB.cTrue c])+ sig <- BB.bvIte c special (BB.constBits c sb (2 ^ (sb - 1))) sig0+ e <- BB.bvIte c sub expSub expNormal+ pure (Unpacked nan inf zero s e sig)++-- | Round a non-zero value into the format: sign, exponent of the leading+-- bit (signed, width @ew@), normalized significand of at least @sb + 2@+-- bits and the OR of the bits below it. Handles subnormal results,+-- underflow to zero and overflow.+roundTo :: Circuit -> RM -> Format -> Int -> Lit -> Bits -> Bits -> Lit -> IO Bits+roundTo c rm (eb, sb) ew s e sig0 st0 = do+ let sig = if length sig0 >= sb + 2 then sig0 else falses c (sb + 2 - length sig0) <> sig0+ p = length sig+ bias = 2 ^ (eb - 1) - 1 :: Integer+ amtW = bitLen (p + 1)+ be <- BB.bvAdd c e (sconst c ew bias)+ tiny <- BB.bvSLt c be (sconst c ew 1)+ d <- BB.bvSub c (sconst c ew 1) be+ big <- BB.bvSLe c (sconst c ew (toInteger (p + 1))) d+ amount0 <- BB.bvIte c big (BB.constBits c amtW (toInteger (p + 1))) (take amtW d)+ amount <- BB.bvIte c tiny amount0 (falses c amtW)+ (sh, st1) <- shiftRightSticky c sig amount+ let m = drop (p - sb) sh+ g = sh !! (p - sb - 1)+ rest = take (p - sb - 1) sh+ st <- orN c (st0 : st1 : rest)+ inc <- roundUp c rm s (m !! 0) g st+ m' <- BB.bvAdd c (m <> [BB.cFalse c]) (inc : falses c sb)+ let carry = m' !! sb+ hidden = m' !! (sb - 1)+ frac = take (sb - 1) m'+ beInc <- BB.bvAdd c be (carry : falses c (ew - 1))+ field <- BB.bvIte c tiny (hidden : falses c (ew - 1)) beInc+ overflow <- BB.andG c (notL tiny) =<< BB.bvSLe c (sconst c ew (2 ^ eb - 1)) field+ toInf <-+ orN c+ =<< sequence [pure (rmRNE rm), pure (rmRNA rm), BB.andG c (rmRTP rm) (notL s), BB.andG c (rmRTN rm) s]+ let normal = frac <> take eb field <> [s]+ largest = trues c (sb - 1) <> (BB.cFalse c : trues c (eb - 1)) <> [s]+ ovf <- BB.bvIte c toInf (infBits c (eb, sb) s) largest+ BB.bvIte c overflow ovf normal++-- | Round the value @mag * 2^scale@ (an unsigned magnitude, non-zero).+roundInt :: Circuit -> RM -> Format -> Int -> Lit -> Bits -> Bits -> IO Bits+roundInt c rm fmt ew s mag scale = do+ let w = length mag+ (mn, lz) <- normalize c mag+ e <- BB.bvSub c scale (zext c ew lz) >>= BB.bvAdd c (sconst c ew (toInteger (w - 1)))+ roundTo c rm fmt ew s e mn (BB.cFalse c)++exactRM :: Circuit -> RM+exactRM c = RM (BB.cTrue c) (BB.cFalse c) (BB.cFalse c) (BB.cFalse c)++-------------------------------------------------------------------------------+-- Invariants and classification++-- | Clauses forcing bits to be a canonical floating-point pattern.+fpInvariant :: Circuit -> Format -> Bits -> IO ()+fpInvariant c fmt bits = do+ nan <- fpIsNaN c fmt bits+ let canon = nanBits c fmt+ sequence_+ [ BB.emitClause c [notL nan, if BB.isConstLit c k == Just True then b else notL b]+ | (b, k) <- zip bits canon+ ]++-- | Clauses forcing bits to be a rounding mode.+rmInvariant :: Circuit -> Bits -> IO ()+rmInvariant c bits = BB.bvULe c bits (BB.constBits c 3 4) >>= \l -> BB.emitClause c [l]++-- | Classification predicates (@fp.isNaN@, @fp.isInfinite@, @fp.isZero@,+-- @fp.isNormal@, @fp.isSubnormal@, @fp.isNegative@, @fp.isPositive@) of a+-- value of the given format. Zeros and infinities have a sign, so+-- 'fpIsNegative' and 'fpIsPositive' hold for them; both are false for NaN.+fpIsNaN, fpIsInf, fpIsZero, fpIsNormal, fpIsSubnormal, fpIsNegative, fpIsPositive :: Circuit -> Format -> Bits -> IO Lit+fpIsNaN c fmt bits = do+ let (frac, ef, _) = fields fmt bits+ BB.andG c <$> andN c ef <*> orN c frac >>= id+fpIsInf c fmt bits = do+ let (frac, ef, _) = fields fmt bits+ BB.andG c <$> andN c ef <*> (notL <$> orN c frac) >>= id+fpIsZero c fmt bits = do+ let (frac, ef, _) = fields fmt bits+ notL <$> orN c (frac <> ef)+fpIsNormal c fmt bits = do+ let (_, ef, _) = fields fmt bits+ BB.andG c <$> orN c ef <*> (notL <$> andN c ef) >>= id+fpIsSubnormal c fmt bits = do+ let (frac, ef, _) = fields fmt bits+ BB.andG c <$> (notL <$> orN c ef) <*> orN c frac >>= id+fpIsNegative c fmt bits = do+ let (_, _, s) = fields fmt bits+ nan <- fpIsNaN c fmt bits+ BB.andG c s (notL nan)+fpIsPositive c fmt bits = do+ let (_, _, s) = fields fmt bits+ nan <- fpIsNaN c fmt bits+ BB.andG c (notL s) (notL nan)++-------------------------------------------------------------------------------+-- Comparisons++-- | IEEE comparisons @a < b@, @a <= b@ and @a = b@ (@fp.lt@, @fp.leq@,+-- @fp.eq@): false when either argument is NaN, and the two zeros are equal.+fpLt, fpLeq, fpEq :: Circuit -> Format -> Bits -> Bits -> IO Lit+fpLt c fmt a b = do+ nanA <- fpIsNaN c fmt a+ nanB <- fpIsNaN c fmt b+ zeroA <- fpIsZero c fmt a+ zeroB <- fpIsZero c fmt b+ let (_, _, sa) = fields fmt a+ (_, _, sb) = fields fmt b+ magA = init a+ magB = init b+ ltMag <- BB.bvULt c magA magB+ gtMag <- BB.bvULt c magB magA+ both0 <- BB.andG c zeroA zeroB+ whenNeg <- BB.iteG c sb gtMag (BB.cTrue c)+ whenPos <- BB.iteG c sb (BB.cFalse c) ltMag+ r <- BB.iteG c sa whenNeg whenPos+ andN c [notL nanA, notL nanB, notL both0, r]+fpEq c fmt a b = do+ nanA <- fpIsNaN c fmt a+ nanB <- fpIsNaN c fmt b+ both0 <- BB.andG c <$> fpIsZero c fmt a <*> fpIsZero c fmt b >>= id+ same <- BB.bvEq c a b+ andN c [notL nanA, notL nanB] >>= \ok -> BB.andG c ok =<< BB.orG c both0 same+fpLeq c fmt a b = BB.orG c <$> fpLt c fmt a b <*> fpEq c fmt a b >>= id++-------------------------------------------------------------------------------+-- Sign operations and constructors++canonical :: Circuit -> Format -> Bits -> IO Bits+canonical c fmt bits = do+ nan <- fpIsNaN c fmt bits+ BB.bvIte c nan (nanBits c fmt) bits++-- | Absolute value (clears the sign bit) and negation (flips it, keeping NaN+-- canonical).+fpAbs, fpNeg :: Circuit -> Format -> Bits -> IO Bits+fpAbs c _ bits = pure (init bits <> [BB.cFalse c])+fpNeg c fmt bits = do+ nan <- fpIsNaN c fmt bits+ BB.bvIte c nan bits (init bits <> [notL (last bits)])++-- | The @fp@ constructor (bits low first: sign, exponent, trailing+-- significand as given).+fpFromFields :: Circuit -> Format -> Bits -> Bits -> Bits -> IO Bits+fpFromFields c fmt s e f = canonical c fmt (f <> e <> s)++-- | @(_ to_fp eb sb)@ of a bit-vector: its bits as a pattern.+fpFromBits :: Circuit -> Format -> Bits -> IO Bits+fpFromBits = canonical++-------------------------------------------------------------------------------+-- Arithmetic++-- | Sum of two finite non-zero values with normalized significands of the+-- same width: whether it is an exact zero, and the sign, exponent and+-- significand (with three extra bits) to round.+addCore :: Circuit -> Int -> (Lit, Bits, Bits) -> (Lit, Bits, Bits) -> IO (Lit, Lit, Bits, Bits)+addCore c ew (sa, ea, ma) (sb, eb, mb) = do+ let q = length ma+ p = q + 3+ amtW = bitLen p+ eGt <- BB.bvSLt c eb ea+ eEq <- BB.bvEq c ea eb+ mGe <- BB.bvULe c mb ma+ aBig <- BB.orG c eGt =<< BB.andG c eEq mGe+ sx <- BB.iteG c aBig sa sb+ sy <- BB.iteG c aBig sb sa+ ex <- BB.bvIte c aBig ea eb+ ey <- BB.bvIte c aBig eb ea+ mx <- BB.bvIte c aBig ma mb+ my <- BB.bvIte c aBig mb ma+ d <- BB.bvSub c ex ey+ big <- BB.bvSLe c (sconst c ew (toInteger p)) d+ amount <- BB.bvIte c big (BB.constBits c amtW (toInteger p)) (take amtW d)+ let xExt = falses c 3 <> mx+ (ySh, st) <- shiftRightSticky c (falses c 3 <> my) amount+ jam <- BB.orG c (ySh !! 0) st+ let yJam = jam : drop 1 ySh+ isSub <- BB.xorG c sx sy+ -- Effective addition: at most one more bit.+ total <- BB.bvAdd c (xExt <> [BB.cFalse c]) (yJam <> [BB.cFalse c])+ let top = total !! p+ low <- BB.orG c (total !! 0) (total !! 1)+ sumSig <- BB.bvIte c top (low : drop 2 total) (take p total)+ exPlus <- BB.bvAdd c ex (BB.cTrue c : falses c (ew - 1))+ sumExp <- BB.bvIte c top exPlus ex+ -- Effective subtraction: cancellation of leading bits.+ diff <- BB.bvSub c xExt yJam+ nonZero <- orN c diff+ (diffSig, lz) <- normalize c diff+ diffExp <- BB.bvSub c ex (zext c ew lz)+ sig <- BB.bvIte c isSub diffSig sumSig+ e <- BB.bvIte c isSub diffExp sumExp+ exactZero <- BB.andG c isSub (notL nonZero)+ pure (exactZero, sx, e, sig)++-- | @fp.add@, @fp.sub@, @fp.mul@ and @fp.div@: the rounding mode bits come+-- first, then the operands; the result is correctly rounded.+fpAdd, fpSub, fpMul, fpDiv :: Circuit -> Format -> Bits -> Bits -> Bits -> IO Bits+fpAdd c fmt@(eb, sb) rmBits a b = do+ let ew = expWidth [(eb, sb)] []+ rm <- roundingMode c rmBits+ ua <- unpack c fmt ew a+ ub <- unpack c fmt ew b+ (exactZero, s, e, m) <- addCore c ew (uSign ua, uExp ua, uSig ua) (uSign ub, uExp ub, uSig ub)+ r <- roundTo c rm fmt ew s e m (BB.cFalse c)+ opposite <- BB.xorG c (uSign ua) (uSign ub)+ nan <- orN c =<< sequence [pure (uNaN ua), pure (uNaN ub), andN c [uInf ua, uInf ub, opposite]]+ inf <- BB.orG c (uInf ua) (uInf ub)+ infSign <- BB.iteG c (uInf ua) (uSign ua) (uSign ub)+ bothZero <- BB.andG c (uZero ua) (uZero ub)+ zeroSign <- BB.orG c <$> BB.andG c (uSign ua) (uSign ub) <*> (BB.andG c (rmRTN rm) =<< BB.orG c (uSign ua) (uSign ub)) >>= id+ select+ c+ [ (nan, nanBits c fmt)+ , (inf, infBits c fmt infSign)+ , (bothZero, zeroBits c fmt zeroSign)+ , (uZero ua, b)+ , (uZero ub, a)+ , (exactZero, zeroBits c fmt (rmRTN rm))+ ]+ r+fpSub c fmt rmBits a b = fpNeg c fmt b >>= fpAdd c fmt rmBits a+fpMul c fmt@(eb, sb) rmBits a b = do+ let ew = expWidth [(eb, sb)] []+ rm <- roundingMode c rmBits+ ua <- unpack c fmt ew a+ ub <- unpack c fmt ew b+ (s, e, m) <- product' c ew ua ub+ r <- roundTo c rm fmt ew s e m (BB.cFalse c)+ nan <- orN c =<< sequence [pure (uNaN ua), pure (uNaN ub), BB.andG c (uInf ua) (uZero ub), BB.andG c (uZero ua) (uInf ub)]+ inf <- BB.orG c (uInf ua) (uInf ub)+ zero <- BB.orG c (uZero ua) (uZero ub)+ select c [(nan, nanBits c fmt), (inf, infBits c fmt s), (zero, zeroBits c fmt s)] r+fpDiv c fmt@(eb, sb) rmBits a b = do+ let ew = expWidth [(eb, sb)] []+ w = 2 * sb + 2+ rm <- roundingMode c rmBits+ ua <- unpack c fmt ew a+ ub <- unpack c fmt ew b+ s <- BB.xorG c (uSign ua) (uSign ub)+ let num = falses c (sb + 2) <> uSig ua+ den = zext c w (uSig ub)+ q <- BB.bvUDiv c num den+ r0 <- BB.bvURem c num den+ st <- orN c r0+ let qq = take (sb + 3) q+ top = qq !! (sb + 2)+ sig <- BB.bvIte c top qq (shl c 1 qq)+ e0 <- BB.bvSub c (uExp ua) (uExp ub)+ eMinus <- BB.bvSub c e0 (BB.cTrue c : falses c (ew - 1))+ e <- BB.bvIte c top e0 eMinus+ r <- roundTo c rm fmt ew s e sig st+ nan <- orN c =<< sequence [pure (uNaN ua), pure (uNaN ub), BB.andG c (uInf ua) (uInf ub), BB.andG c (uZero ua) (uZero ub)]+ inf <- BB.orG c (uInf ua) (uZero ub)+ zero <- BB.orG c (uZero ua) (uInf ub)+ select c [(nan, nanBits c fmt), (inf, infBits c fmt s), (zero, zeroBits c fmt s)] r++-- | Exact product of two unpacked values: sign, exponent and a normalized+-- significand of twice the width.+product' :: Circuit -> Int -> Unpacked -> Unpacked -> IO (Lit, Bits, Bits)+product' c ew ua ub = do+ let sb = length (uSig ua)+ w = 2 * sb+ s <- BB.xorG c (uSign ua) (uSign ub)+ prod <- BB.bvMul c (zext c w (uSig ua)) (zext c w (uSig ub))+ let top = prod !! (w - 1)+ sig <- BB.bvIte c top prod (shl c 1 prod)+ e0 <- BB.bvAdd c (uExp ua) (uExp ub)+ ePlus <- BB.bvAdd c e0 (BB.cTrue c : falses c (ew - 1))+ e <- BB.bvIte c top ePlus e0+ pure (s, e, sig)++-- | Fused multiply-add @fp.fma rm a b z@, i.e. @a * b + z@ with a single+-- rounding.+fpFma :: Circuit -> Format -> Bits -> Bits -> Bits -> Bits -> IO Bits+fpFma c fmt@(eb, sb) rmBits a b z = do+ let ew = expWidth [(eb, 2 * sb)] []+ rm <- roundingMode c rmBits+ ua <- unpack c fmt ew a+ ub <- unpack c fmt ew b+ uz <- unpack c fmt ew z+ (ps, pe, pm) <- product' c ew ua ub+ (exactZero, s, e, m) <- addCore c ew (ps, pe, pm) (uSign uz, uExp uz, falses c sb <> uSig uz)+ r <- roundTo c rm fmt ew s e m (BB.cFalse c)+ rProd <- roundTo c rm fmt ew ps pe pm (BB.cFalse c)+ prodInf <- BB.orG c (uInf ua) (uInf ub)+ prodZero <- BB.orG c (uZero ua) (uZero ub)+ opposite <- BB.xorG c ps (uSign uz)+ nan <-+ orN c+ =<< sequence+ [ pure (uNaN ua)+ , pure (uNaN ub)+ , pure (uNaN uz)+ , BB.andG c (uInf ua) (uZero ub)+ , BB.andG c (uZero ua) (uInf ub)+ , andN c [prodInf, uInf uz, opposite]+ ]+ inf <- BB.orG c prodInf (uInf uz)+ infSign <- BB.iteG c prodInf ps (uSign uz)+ bothZero <- BB.andG c prodZero (uZero uz)+ zeroSign <- BB.orG c <$> BB.andG c ps (uSign uz) <*> (BB.andG c (rmRTN rm) =<< BB.orG c ps (uSign uz)) >>= id+ select+ c+ [ (nan, nanBits c fmt)+ , (inf, infBits c fmt infSign)+ , (bothZero, zeroBits c fmt zeroSign)+ , (prodZero, z)+ , (uZero uz, rProd)+ , (exactZero, zeroBits c fmt (rmRTN rm))+ ]+ r++-- | Correctly rounded square root (@fp.sqrt@) under the given rounding+-- mode; NaN for negative non-zero arguments.+fpSqrt :: Circuit -> Format -> Bits -> Bits -> IO Bits+fpSqrt c fmt@(eb, sb) rmBits a = do+ let ew = expWidth [(eb, 3 * sb + 8)] []+ k = sb + 2+ rm <- roundingMode c rmBits+ ua <- unpack c fmt ew a+ -- value = sig * 2^t with t = exp - (sb - 1); make t even.+ t <- BB.bvSub c (uExp ua) (sconst c ew (toInteger (sb - 1)))+ let odd' = t !! 0+ sig1 = zext c (sb + 1) (uSig ua)+ sig2 <- BB.bvIte c odd' (shl c 1 sig1) sig1+ t2 <- BB.bvSub c t (odd' : falses c (ew - 1))+ let x = falses c (2 * k) <> sig2+ wx = length x+ wr = (wx + 1) `div` 2+ w2 = 2 * wr + 2+ root <- BB.freshBits c wr+ let rootW = zext c w2 root+ xW = zext c w2 x+ sq <- BB.bvMul c rootW rootW+ BB.bvULe c sq xW >>= \l -> BB.emitClause c [l]+ -- (r + 1)^2 = r^2 + 2r + 1+ twice <- BB.bvAdd c sq (shl c 1 rootW)+ next <- BB.bvAdd c twice (BB.constBits c w2 1)+ BB.bvULt c xW next >>= \l -> BB.emitClause c [l]+ exact <- BB.bvEq c sq xW+ -- sqrt(value) = root * 2^(t2 / 2 - k), up to the sticky bit.+ let half = drop 1 t2 <> [last t2]+ scale <- BB.bvSub c half (sconst c ew (toInteger k))+ r <- do+ (mn, lz) <- normalize c root+ e <- BB.bvSub c scale (zext c ew lz) >>= BB.bvAdd c (sconst c ew (toInteger (wr - 1)))+ roundTo c rm fmt ew (BB.cFalse c) e mn (notL exact)+ negative <- BB.andG c (uSign ua) (notL (uZero ua))+ nan <- BB.orG c (uNaN ua) negative+ select c [(nan, nanBits c fmt), (uInf ua, a), (uZero ua, a)] r++-- | IEEE remainder (@fp.rem@): @a - b * n@ where @n@ is @a / b@ rounded to+-- the nearest integer, ties to even; exact, so it takes no rounding mode.+fpRem :: Circuit -> Format -> Bits -> Bits -> IO Bits+fpRem c fmt@(eb, sb) a b = do+ let ew = expWidth [(eb, sb)] []+ bias = 2 ^ (eb - 1) - 1 :: Integer+ dMax = (bias - (1 - bias)) + toInteger sb - 1+ rm = exactRM c+ ua <- unpack c fmt ew a+ ub <- unpack c fmt ew b+ d <- BB.bvSub c (uExp ua) (uExp ub)+ let w = sb + 1+ ma = zext c w (uSig ua)+ mb = zext c w (uSig ub)+ ge0 <- BB.bvULe c mb ma+ r0 <- BB.bvSub c ma mb >>= \df -> BB.bvIte c ge0 df ma+ (rFinal, qFinal) <-+ foldM+ ( \(r, q) i -> do+ active <- BB.bvSLe c (sconst c ew i) d+ let r2 = shl c 1 r+ ge <- BB.bvULe c mb r2+ rn <- BB.bvSub c r2 mb >>= \df -> BB.bvIte c ge df r2+ r' <- BB.bvIte c active rn r+ q' <- BB.iteG c active ge q+ pure (r', q')+ )+ (r0, ge0)+ [1 .. dMax]+ -- Round the quotient to nearest, ties to even.+ let twoR = shl c 1 rFinal+ gt <- BB.bvULt c mb twoR+ tie <- BB.bvEq c mb twoR+ up <- BB.orG c gt =<< BB.andG c tie qFinal+ mag <- BB.bvSub c mb rFinal >>= \df -> BB.bvIte c up df rFinal+ sgn <- BB.xorG c (uSign ua) up+ magZero <- notL <$> orN c mag+ scaleB <- BB.bvSub c (uExp ub) (sconst c ew (toInteger (sb - 1)))+ r1 <- roundInt c rm fmt ew sgn mag scaleB+ -- Exponent difference -1: |x| >= |y| / 2.+ gtHalf <- BB.bvULt c mb ma+ mag2 <- BB.bvSub c (shl c 1 mb) ma+ scaleA <- BB.bvSub c (uExp ua) (sconst c ew (toInteger (sb - 1)))+ r2 <- roundInt c rm fmt ew (notL (uSign ua)) mag2 scaleA+ minusOne <- BB.bvEq c d (sconst c ew (-1))+ negD <- BB.bvSLt c d (sconst c ew 0)+ nan <- orN c [uNaN ua, uNaN ub, uInf ua, uZero ub]+ keep <- BB.orG c (uInf ub) (uZero ua)+ close <- BB.andG c minusOne gtHalf+ select+ c+ [ (nan, nanBits c fmt)+ , (keep, a)+ , (close, r2)+ , (negD, a)+ , (magZero, zeroBits c fmt (uSign ua))+ ]+ r1++-- | Round a finite value to an integer magnitude (at most @2^sb@), given+-- its unpacked form: the magnitude and whether the value already was an+-- integer.+integerPart :: Circuit -> RM -> Format -> Int -> Unpacked -> IO (Bits, Lit)+integerPart c rm (_, sb) ew ua = do+ isInt <- BB.bvSLe c (sconst c ew (toInteger (sb - 1))) (uExp ua)+ sAmt <- BB.bvSub c (sconst c ew (toInteger (sb - 1))) (uExp ua)+ let amtW = bitLen (sb + 1)+ big <- BB.bvSLe c (sconst c ew (toInteger (sb + 1))) sAmt+ amount <- BB.bvIte c big (BB.constBits c amtW (toInteger (sb + 1))) (take amtW sAmt)+ (sh, st) <- shiftRightSticky c (BB.cFalse c : uSig ua) amount+ let g = sh !! 0+ m = drop 1 sh+ inc <- roundUp c rm (uSign ua) (m !! 0) g st+ n <- BB.bvAdd c (m <> [BB.cFalse c]) (inc : falses c sb)+ pure (n, isInt)++-- | Round to an integral value in the same format (@fp.roundToIntegral@)+-- under the given rounding mode; the sign of zero results is kept.+fpRoundToIntegral :: Circuit -> Format -> Bits -> Bits -> IO Bits+fpRoundToIntegral c fmt@(eb, sb) rmBits a = do+ let ew = expWidth [(eb, sb)] []+ rm <- roundingMode c rmBits+ ua <- unpack c fmt ew a+ (n, isInt) <- integerPart c rm fmt ew ua+ nZero <- notL <$> orN c n+ r <- roundInt c (exactRM c) fmt ew (uSign ua) n (sconst c ew 0)+ special <- orN c [uNaN ua, uInf ua, uZero ua, isInt]+ select c [(special, a), (nZero, zeroBits c fmt (uSign ua))] r++-- | @fp.min@ / @fp.max@: the result when specified, and whether the+-- arguments are zeros of different signs (unspecified result).+fpMin, fpMax :: Circuit -> Format -> Bits -> Bits -> IO (Bits, Lit)+fpMin c fmt a b = minMax c fmt a b True+fpMax c fmt a b = minMax c fmt a b False++minMax :: Circuit -> Format -> Bits -> Bits -> Bool -> IO (Bits, Lit)+minMax c fmt a b isMin = do+ nanA <- fpIsNaN c fmt a+ nanB <- fpIsNaN c fmt b+ takeB <- if isMin then fpLt c fmt b a else fpLt c fmt a b+ r <- select c [(nanA, b), (nanB, a), (takeB, b)] a+ zeroA <- fpIsZero c fmt a+ zeroB <- fpIsZero c fmt b+ differ <- BB.xorG c (last a) (last b)+ unspecified <- andN c [zeroA, zeroB, differ]+ pure (r, unspecified)++-------------------------------------------------------------------------------+-- Conversions++-- | Conversion between formats.+fpConvert :: Circuit -> Format -> Format -> Bits -> Bits -> IO Bits+fpConvert c from to rmBits a = do+ let ew = expWidth [from, to] []+ rm <- roundingMode c rmBits+ ua <- unpack c from ew a+ r <- roundTo c rm to ew (uSign ua) (uExp ua) (uSig ua) (BB.cFalse c)+ select+ c+ [ (uNaN ua, nanBits c to)+ , (uInf ua, infBits c to (uSign ua))+ , (uZero ua, zeroBits c to (uSign ua))+ ]+ r++-- | Conversion from a signed (flag set) or unsigned bit-vector.+fpFromInt :: Circuit -> Format -> Bool -> Bits -> Bits -> IO Bits+fpFromInt c fmt@(eb, sb) signed rmBits x = do+ let w = length x+ ew = expWidth [(eb, sb)] [w]+ rm <- roundingMode c rmBits+ let s = if signed then last x else BB.cFalse c+ mag <- if signed then BB.bvNeg c x >>= \nx -> BB.bvIte c s nx x else pure x+ zero <- notL <$> orN c mag+ r <- roundInt c rm fmt ew s mag (sconst c ew 0)+ BB.bvIte c zero (zeroBits c fmt (BB.cFalse c)) r++-- | Conversion to a signed (flag set) or unsigned bit-vector of the given+-- width: the result and whether it is specified (not NaN, infinite or out+-- of range).+fpToInt :: Circuit -> Format -> Bool -> Int -> Bits -> Bits -> IO (Bits, Lit)+fpToInt c fmt@(eb, sb) signed w rmBits a = do+ let ew = expWidth [(eb, sb)] [w + 2]+ ww = max (sb + 1) (w + 2)+ amtW = bitLen ww+ rm <- roundingMode c rmBits+ ua <- unpack c fmt ew a+ (nSmall, isInt) <- integerPart c rm fmt ew ua+ shiftAmt <- BB.bvSub c (uExp ua) (sconst c ew (toInteger (sb - 1)))+ large <- BB.bvShl c (zext c ww (uSig ua)) (zext c ww (take amtW shiftAmt))+ nMag <- BB.bvIte c isInt large (zext c ww nSmall)+ big <- BB.bvSLe c (sconst c ew (toInteger (w + 1))) (uExp ua)+ nZero <- notL <$> orN c nMag+ let s = uSign ua+ fits <-+ if signed+ then do+ limit <- BB.bvIte c s (BB.constBits c ww (2 ^ (w - 1))) (BB.constBits c ww (2 ^ (w - 1) - 1))+ BB.bvULe c nMag limit+ else do+ small <- BB.bvULt c nMag (BB.constBits c ww (2 ^ w))+ BB.andG c small =<< BB.orG c nZero (notL s)+ inRange <- andN c [notL (uNaN ua), notL (uInf ua), notL big, fits]+ specified <- BB.orG c (uZero ua) inRange+ negated <- BB.bvNeg c nMag+ value <- BB.bvIte c s negated nMag+ result <- BB.bvIte c (uZero ua) (falses c w) (take w value)+ pure (result, specified)
+ src/HSMT/Tutorial.hs view
@@ -0,0 +1,336 @@+-- | A tutorial on hsmt. This module exports nothing; its documentation is+-- the tutorial. Every example below is also part of the test suite+-- (@test/HSMT/TutorialSpec.hs@).+--+-- = Getting started+--+-- An SMT solver decides whether a formula over some theories (integers,+-- bit-vectors, arrays...) has a solution, and gives one when it does. With+-- hsmt, formulas are Haskell values built inside the 'HSMT.SMT' monad:+--+-- > {-# LANGUAGE DataKinds, LambdaCase, OverloadedLabels, OverloadedStrings, TypeApplications #-}+-- > import Data.Text (Text)+-- > import qualified Data.Text as T+-- > import HSMT+-- >+-- > example :: IO (Maybe (Integer, Integer))+-- > example = runSMT defaultConfig $ do+-- > x <- declare @IntS "x"+-- > y <- declare @IntS "y"+-- > assert (x + y .== 10)+-- > assert (x - y .== 4)+-- > checkSat >>= \case+-- > Sat m -> pure (Just (eval m x, eval m y))+-- > _ -> pure Nothing+--+-- @example@ gives @Just (7, 3)@. (The extensions and imports above are the+-- ones all the examples of this tutorial need.) The steps are always the+-- same:+--+-- 1. 'HSMT.runSMT' starts a solver instance with a 'HSMT.Config'+-- ('HSMT.defaultConfig' is fine to begin with).+-- 2. 'HSMT.declare' introduces a constant of a sort, chosen with a type+-- application. Constants are expressions, 'HSMT.Expr' @ctx s@.+-- 3. 'HSMT.assert' adds a Boolean expression to the assertions.+-- 4. 'HSMT.checkSat' decides the conjunction of the assertions. It answers+-- 'HSMT.Sat' with a model, 'HSMT.Unsat' with an unsatisfiable core, or+-- 'HSMT.Unknown' with the reason the solver gave up.+-- 5. 'HSMT.eval' evaluates any expression under a model, giving a Haskell+-- value: 'Integer' for integers, 'Bool' for Booleans, and so on (the+-- type family 'HSMT.Value').+--+-- = Sorts and type safety+--+-- Sorts are types of the kind 'HSMT.Sort': 'HSMT.BoolS', 'HSMT.IntS',+-- 'HSMT.StringS', 'HSMT.BVS' @n@, 'HSMT.ArrayS' @i e@, 'HSMT.RecordS'+-- @fields@, 'HSMT.UninterpS' @name@, 'HSMT.FPS' @eb sb@ and+-- 'HSMT.RoundingModeS'. An expression carries its sort in its type, so+-- ill-sorted formulas do not compile:+--+-- > assert (x .== "hello") -- rejected: x is an integer, "hello" a string+-- > bvAdd (bv @8 1) (bv @16 1) -- rejected: widths differ+-- > p ! #weight -- rejected: "Record has no field weight"+--+-- The parameter @ctx@ of 'HSMT.Expr' and 'HSMT.Model' identifies the solver+-- instance: like 'Control.Monad.ST.ST', 'HSMT.runSMT' is rank 2, so+-- expressions and models cannot escape it or be mixed between instances.+--+-- = Theories+--+-- == Booleans and integers+--+-- Booleans have 'HSMT.notB', '(HSMT..&&)', '(HSMT..||)', '(HSMT..=>)',+-- 'HSMT.xorB', 'HSMT.andB', 'HSMT.orB' and 'HSMT.ite'; equality '(HSMT..==)'+-- and 'HSMT.distinct' work at every sort. Integers have a 'Num' instance,+-- the comparisons '(HSMT..<)', '(HSMT..<=)', '(HSMT..>)', '(HSMT..>=)' and+-- Euclidean 'HSMT.idiv' and 'HSMT.imod'. Arithmetic must be linear: one+-- factor of each product, and each divisor, must be a constant.+--+-- > -- Is there an even number between 7 and 9 that is also a multiple of 3?+-- > multipleOfSix :: IO Bool+-- > multipleOfSix = runSMT defaultConfig $ do+-- > n <- declare @IntS "n"+-- > assert (n .> 7 .&& n .< 9)+-- > assert (n `imod` 2 .== 0 .&& n `imod` 3 .== 0)+-- > checkSat >>= \case+-- > Unsat _ -> pure False+-- > _ -> pure True+--+-- @multipleOfSix@ is @False@.+--+-- == Bit-vectors+--+-- @'HSMT.BVS' n@ is the sort of bit-vectors of width @n@, with arithmetic+-- modulo @2^n@ ('Num' instance), bitwise operations, shifts, signed and+-- unsigned division and comparisons, and 'HSMT.bvConcat', 'HSMT.bvExtract',+-- 'HSMT.bvZeroExtend' and 'HSMT.bvSignExtend', whose widths are checked by+-- the type checker. Models give 'HSMT.BitVector' values.+--+-- > -- x & (x - 1) clears the lowest set bit: it is zero only for powers of+-- > -- two (and zero). Find a power of two above 1000.+-- > powerOfTwo :: IO (Maybe (BitVector 16))+-- > powerOfTwo = runSMT defaultConfig $ do+-- > x <- declare @(BVS 16) "x"+-- > assert (bvAnd x (x - 1) .== 0)+-- > assert (bvUGt x 1000)+-- > assert (bvULt x 2000)+-- > checkSat >>= \case+-- > Sat m -> pure (Just (eval m x))+-- > _ -> pure Nothing+--+-- @powerOfTwo@ gives @Just (BitVector 1024)@.+--+-- == Arrays+--+-- @'HSMT.ArrayS' i e@ maps indices of sort @i@ to elements of sort @e@,+-- with 'HSMT.select', 'HSMT.store' and 'HSMT.constArray'. Array equality is+-- extensional.+--+-- > swapTwice :: IO Bool+-- > swapTwice = runSMT defaultConfig $ do+-- > a <- declare @(ArrayS IntS IntS) "a"+-- > i <- declare @IntS "i"+-- > j <- declare @IntS "j"+-- > let swap b = store (store b i (select b j)) j (select b i)+-- > assert (swap (swap a) ./= a)+-- > checkSat >>= \case+-- > Unsat _ -> pure True+-- > _ -> pure False+--+-- @swapTwice@ is @True@: swapping twice gives the array back.+--+-- == Strings+--+-- Strings are sequences of Unicode code points, with literals (through+-- @OverloadedStrings@), concatenation '(HSMT.<+>)', 'HSMT.strLen',+-- 'HSMT.substr', 'HSMT.strAt', 'HSMT.contains', 'HSMT.prefixOf',+-- 'HSMT.suffixOf', 'HSMT.indexOf', 'HSMT.replace', conversions to and from+-- integers, and the lexicographic order.+--+-- > greeting :: IO (Maybe Text)+-- > greeting = runSMT defaultConfig $ do+-- > name <- declare @StringS "name"+-- > let s = "hello, " <+> name+-- > assert (strLen s .== 10)+-- > assert (suffixOf "!" name .&& contains name "b")+-- > checkSat >>= \case+-- > Sat m -> pure (Just (eval m s))+-- > _ -> pure Nothing+--+-- The answer is a string such as @\"hello, b!\"@ preceded by an extra+-- character before the @b@. The procedure for strings considers strings up+-- to some length (growing from 8 to 32 characters); problems that are+-- unsatisfiable only because of longer strings are answered with+-- 'HSMT.Unknown'.+--+-- == Regular expressions+--+-- @'HSMT.RegLanS'@ is the sort of regular languages, built from string+-- literals ('HSMT.toRe', or a literal directly with @OverloadedStrings@),+-- 'HSMT.reRange', 'HSMT.reAllChar', 'HSMT.reAll', 'HSMT.reNone', and the+-- operators 'HSMT.reConcat', 'HSMT.reUnion', 'HSMT.reInter', 'HSMT.reStar',+-- 'HSMT.rePlus', 'HSMT.reOpt', 'HSMT.reComp', 'HSMT.reDiff',+-- 'HSMT.reLoop' and 'HSMT.rePower'. 'HSMT.inRe' tests membership.+-- Regular expressions must be ground: one that depends on a variable (such+-- as @toRe s@ for a declared @s@) makes the check answer 'HSMT.Unknown'.+--+-- > -- An identifier of 3 to 5 characters that contains a 9 and is not a+-- > -- keyword.+-- > identifier :: IO (Maybe Text)+-- > identifier = runSMT defaultConfig $ do+-- > s <- declare @StringS "s"+-- > let letter = reUnion [reRange 'a' 'z', reRange 'A' 'Z']+-- > ident = reConcat [letter, reStar (reUnion [letter, reRange '0' '9'])]+-- > assert (inRe s (reInter [ident, reLoop 3 5 reAllChar]))+-- > assert (notB (inRe s (reUnion ["else", "then"])))+-- > assert (contains s "9")+-- > checkSat >>= \case+-- > Sat m -> pure (Just (eval m s))+-- > _ -> pure Nothing+--+-- The answer is a string such as @\"a9\"@ followed by up to three more+-- letters or digits. Membership is decided by running the automaton of the+-- expression over the bounded encoding of the string, so the remark about+-- long strings above applies to regular expressions too.+--+-- == Uninterpreted sorts and functions+--+-- 'HSMT.declareFun' declares a function about which nothing is known+-- except that equal arguments give equal results. Its domain is a list of+-- sorts, and the result is a curried Haskell function on expressions.+-- @'HSMT.UninterpS' name@ is a sort with no structure at all.+--+-- > congruence :: IO Bool+-- > congruence = runSMT defaultConfig $ do+-- > f <- declareFun @'[UninterpS "U"] @(UninterpS "U") "f"+-- > a <- declare @(UninterpS "U") "a"+-- > assert (f (f (f a)) .== a)+-- > assert (f (f (f (f (f a)))) .== a)+-- > assert (f a ./= a)+-- > checkSat >>= \case+-- > Unsat _ -> pure True+-- > _ -> pure False+--+-- @congruence@ is @True@: the first two assertions imply @f a = a@.+--+-- == Records+--+-- @'HSMT.RecordS' fields@ is a record sort with named fields, written with+-- @OverloadedLabels@. Records are built with 'HSMT.record', read with+-- '(HSMT.!)' and updated with 'HSMT.setField'; in a model, 'HSMT.field'+-- reads the fields of a value.+--+-- > type Point = RecordS '[ '("x", IntS), '("y", IntS)]+-- >+-- > reflection :: IO (Maybe (Integer, Integer))+-- > reflection = runSMT defaultConfig $ do+-- > p <- declare @Point "p"+-- > let q = record (#x := p ! #y :& #y := p ! #x :& FNil)+-- > assert (q .== setField #x 3 p)+-- > assert (p ! #x .> 0)+-- > checkSat >>= \case+-- > Sat m -> pure (Just (field #x (eval m p), field #y (eval m p)))+-- > _ -> pure Nothing+--+-- @reflection@ gives @Just (3, 3)@.+--+-- == Floating point+--+-- @'HSMT.FPS' eb sb@ is the IEEE 754 format with @eb@ exponent bits and+-- @sb@ significand bits (counting the hidden bit), with the abbreviations+-- 'HSMT.Float16S', 'HSMT.Float32S' and 'HSMT.Float64S'. Arithmetic takes a+-- rounding mode ('HSMT.rne', 'HSMT.rna', 'HSMT.rtp', 'HSMT.rtn',+-- 'HSMT.rtz'). The IEEE comparisons ('HSMT.fpEq', 'HSMT.fpLt'...) are false+-- on NaN and identify the two zeros, while '(HSMT..==)' is the identity of+-- values. 'HSMT.toFloat' and 'HSMT.toDouble' convert model values.+--+-- > -- A float that is not equal to itself.+-- > notReflexive :: IO (Maybe Bool)+-- > notReflexive = runSMT defaultConfig $ do+-- > x <- declare @Float32S "x"+-- > assert (notB (fpEq x x))+-- > checkSat >>= \case+-- > Sat m -> pure (Just (isNaN (toFloat (eval m x))))+-- > _ -> pure Nothing+--+-- @notReflexive@ gives @Just True@: only NaN differs from itself.+--+-- = Incremental solving+--+-- One solver instance can answer many queries, reusing what it learned.+-- 'HSMT.push' opens a scope of assertions and 'HSMT.pop' discards it+-- ('HSMT.scoped' does both around an action). 'HSMT.checkSatAssuming'+-- checks the assertions together with formulas that hold for that check+-- only.+--+-- When the answer is 'HSMT.Unsat', the 'HSMT.Core' lists assertions and+-- assumptions that are already unsatisfiable together+-- ('HSMT.coreAssertions', 'HSMT.coreAssumptions'). With+-- 'HSMT.cfgMinimizeCores' the core is minimal: removing any element makes+-- it satisfiable. A classic use is to name constraints with Boolean+-- constants and assume them:+--+-- > conflicting :: IO [Int]+-- > conflicting = runSMT defaultConfig {cfgMinimizeCores = True} $ do+-- > x <- declare @IntS "x"+-- > labels <- mapM (\i -> declare @BoolS ("c" <> T.pack (show i))) [0 .. 3 :: Int]+-- > let constraints = [x .> 10, x .< 20, x .== 5, x .> 0]+-- > sequence_ [assert (l .=> c) | (l, c) <- zip labels constraints]+-- > checkSatAssuming labels >>= \case+-- > Unsat core -> pure [i | (i, l) <- zip [0 ..] labels, l `elem` coreAssumptions core]+-- > _ -> pure []+--+-- @conflicting@ gives @[0, 2]@: @x > 10@ and @x = 5@ conflict.+--+-- Hard problems can be bounded with 'HSMT.cfgTimeout' (milliseconds per+-- check) and 'HSMT.cfgConflictLimit'; a check that reaches a limit answers+-- 'HSMT.Unknown', and the instance stays usable.+--+-- = Models+--+-- By default ('HSMT.cfgValidateModels') every model is checked against the+-- assertions by an independent evaluator before 'HSMT.checkSat' returns+-- it. A model gives a value to every expression of the instance, not only+-- to the declared constants: @eval m (f 3)@ or @eval m (x * 2 + y)@ work as+-- well.+--+-- = External solvers+--+-- The same programs can run on an external SMT solver instead of the+-- Haskell engine: 'HSMT.cfgBackend' selects it. With+-- @'HSMT.External' 'HSMT.z3Backend'@, hsmt starts Z3 (found through the+-- environment variable @HSMT_Z3@ or the @PATH@), sends it the formulas in+-- SMT-LIB, and reads its answers, cores and models back, so 'HSMT.eval'+-- works as usual:+--+-- > viaZ3 :: IO (Maybe (Integer, Integer))+-- > viaZ3 = runSMT defaultConfig {cfgBackend = External z3Backend} $ do+-- > x <- declare @IntS "x"+-- > y <- declare @IntS "y"+-- > assert (x * y .== 12 .&& x .> y .&& y .> 1)+-- > checkSat >>= \case+-- > Sat m -> pure (Just (eval m x, eval m y))+-- > _ -> pure Nothing+--+-- @viaZ3@ gives @Just (6, 2)@ or @Just (4, 3)@: Z3 decides nonlinear+-- arithmetic, which the engine does not. Other solvers are described by an+-- 'HSMT.ExternalSolver' (executable, arguments, 'HSMT.Dialect' and+-- logic). Models are validated by hsmt's own evaluator, as with the+-- engine; results that SMT-LIB leaves unspecified (such as division by+-- zero) follow the solver on the terms of the formulas and the evaluator's+-- defaults elsewhere. Unsatisfiable answers cost a second, tracked check+-- that computes the core (bounded in time; if it gives up, the core is+-- every formula).+--+-- = The SMT-LIB front end+--+-- The @hsmt@ executable reads SMT-LIB 2.6 scripts:+--+-- > $ hsmt problem.smt2+-- > $ hsmt --timeout=5000 < problem.smt2+-- > $ hsmt --solver=z3 problem.smt2+--+-- It supports the commands for declarations and definitions (including+-- @define-sort@, @define-const@ and single-constructor datatypes, read as+-- records), @assert@ (with @:named@), @push@, @pop@, @reset@,+-- @reset-assertions@, @check-sat@, @check-sat-assuming@, @get-model@,+-- @get-value@, @get-assertions@, @get-unsat-core@, @get-info@,+-- @get-option@, @set-option@ (@:print-success@, @:timeout@,+-- @:smt.core.minimize@, @:produce-unsat-cores@), @echo@ and @exit@, and+-- terms with @let@. Errors answer @(error ...)@ and the script goes on.+-- With @--solver@, the checks are decided by an external solver and the+-- other commands are still answered by hsmt. From Haskell,+-- 'HSMT.SMTLib.Run.runScriptWith' runs a script and passes each response+-- to a callback.+--+-- = Limitations+--+-- * Integer arithmetic is linear; other products and divisions answer+-- 'HSMT.Unknown'.+-- * Strings are decided for bounded lengths, so some unsatisfiable+-- problems answer 'HSMT.Unknown'. Regular expressions must be ground.+-- * There are no quantifiers, real numbers or general algebraic+-- datatypes.+-- * Bit-vectors and floating point are bit-blasted, so wide+-- multiplications and divisions can be slow.+module HSMT.Tutorial () where
+ src/HSMT/Util/GrowVec.hs view
@@ -0,0 +1,181 @@+-- | Minimal growable mutable vectors living in 'IO'.+module HSMT.Util.GrowVec+ ( -- * Unboxed+ UVec+ , newUVec+ , uSize+ , uRead+ , uWrite+ , uPush+ , uPop+ , uShrink+ , uClear+ , uToList+ , uModify+ -- * Boxed+ , BVec+ , newBVec+ , bSize+ , bRead+ , bWrite+ , bPush+ , bShrink+ , bClear+ , bToList+ ) where++import Control.Monad (when)+import Data.IORef+import qualified Data.Vector.Mutable as MV+import qualified Data.Vector.Unboxed.Mutable as MU++-- | Growable unboxed vector.+data UVec a = UVec+ { uvData :: !(IORef (MU.IOVector a))+ , uvSize :: !(MU.IOVector Int)+ }++-- | An empty vector with the given initial capacity (at least 4).+newUVec :: MU.Unbox a => Int -> IO (UVec a)+newUVec cap = do+ d <- MU.new (max 4 cap)+ s <- MU.replicate 1 0+ r <- newIORef d+ pure (UVec r s)++-- | Number of elements.+uSize :: UVec a -> IO Int+uSize v = MU.unsafeRead (uvSize v) 0+{-# INLINE uSize #-}++-- | Read an element. The index is not bounds-checked.+uRead :: MU.Unbox a => UVec a -> Int -> IO a+uRead v i = do+ d <- readIORef (uvData v)+ MU.unsafeRead d i+{-# INLINE uRead #-}++-- | Overwrite an element. The index is not bounds-checked.+uWrite :: MU.Unbox a => UVec a -> Int -> a -> IO ()+uWrite v i x = do+ d <- readIORef (uvData v)+ MU.unsafeWrite d i x+{-# INLINE uWrite #-}++-- | Apply a function to an element in place. The index is not+-- bounds-checked.+uModify :: MU.Unbox a => UVec a -> Int -> (a -> a) -> IO ()+uModify v i f = do+ d <- readIORef (uvData v)+ MU.unsafeModify d f i+{-# INLINE uModify #-}++-- | Append an element, doubling the capacity when full.+uPush :: MU.Unbox a => UVec a -> a -> IO ()+uPush v x = do+ n <- uSize v+ d <- readIORef (uvData v)+ d' <-+ if n < MU.length d+ then pure d+ else do+ g <- MU.unsafeGrow d (MU.length d)+ writeIORef (uvData v) g+ pure g+ MU.unsafeWrite d' n x+ MU.unsafeWrite (uvSize v) 0 (n + 1)+{-# INLINE uPush #-}++-- | Remove and return the last element. The vector must be non-empty.+uPop :: MU.Unbox a => UVec a -> IO a+uPop v = do+ n <- uSize v+ x <- uRead v (n - 1)+ MU.unsafeWrite (uvSize v) 0 (n - 1)+ pure x+{-# INLINE uPop #-}++-- | Truncate to the given size (which must not exceed the current size).+uShrink :: UVec a -> Int -> IO ()+uShrink v n = do+ s <- uSize v+ when (n <= s) $ MU.unsafeWrite (uvSize v) 0 n+{-# INLINE uShrink #-}++-- | Remove all elements (the capacity is kept).+uClear :: UVec a -> IO ()+uClear v = MU.unsafeWrite (uvSize v) 0 0++-- | The elements, in index order.+uToList :: MU.Unbox a => UVec a -> IO [a]+uToList v = do+ n <- uSize v+ mapM (uRead v) [0 .. n - 1]++-- | Growable boxed vector.+data BVec a = BVec+ { bvData :: !(IORef (MV.IOVector a))+ , bvSize :: !(MU.IOVector Int)+ }++-- | An empty vector with the given initial capacity (at least 4).+newBVec :: Int -> IO (BVec a)+newBVec cap = do+ d <- MV.new (max 4 cap)+ s <- MU.replicate 1 0+ r <- newIORef d+ pure (BVec r s)++-- | Number of elements.+bSize :: BVec a -> IO Int+bSize v = MU.unsafeRead (bvSize v) 0+{-# INLINE bSize #-}++-- | Read an element. The index is not bounds-checked.+bRead :: BVec a -> Int -> IO a+bRead v i = do+ d <- readIORef (bvData v)+ MV.unsafeRead d i+{-# INLINE bRead #-}++-- | Overwrite an element. The index is not bounds-checked.+bWrite :: BVec a -> Int -> a -> IO ()+bWrite v i x = do+ d <- readIORef (bvData v)+ MV.unsafeWrite d i x+{-# INLINE bWrite #-}++-- | Append an element, doubling the capacity when full.+bPush :: BVec a -> a -> IO ()+bPush v x = do+ n <- bSize v+ d <- readIORef (bvData v)+ d' <-+ if n < MV.length d+ then pure d+ else do+ g <- MV.unsafeGrow d (MV.length d)+ writeIORef (bvData v) g+ pure g+ MV.unsafeWrite d' n x+ MU.unsafeWrite (bvSize v) 0 (n + 1)+{-# INLINE bPush #-}++-- | Truncate to the given size. Dropped slots keep their old contents until+-- overwritten.+bShrink :: BVec a -> Int -> IO ()+bShrink v n = do+ s <- bSize v+ when (n <= s) $ MU.unsafeWrite (bvSize v) 0 n+{-# INLINE bShrink #-}++-- | Remove all elements (the capacity is kept; old slots are not+-- released until overwritten).+bClear :: BVec a -> IO ()+bClear v = MU.unsafeWrite (bvSize v) 0 0++-- | The elements, in index order.+bToList :: BVec a -> IO [a]+bToList v = do+ n <- bSize v+ mapM (bRead v) [0 .. n - 1]
+ test-common/HSMT/Benchmarks.hs view
@@ -0,0 +1,64 @@+-- | The SMT-LIB benchmarks in @bench/smtlib@, shared by the test suite and+-- the benchmark program.+--+-- Each file states the expected answer of each check with+-- @(set-info :status ...)@ before it, as the SMT-LIB benchmark library+-- does; Z3 checks these annotations as well.+module HSMT.Benchmarks+ ( benchmarkDir+ , benchmarkFiles+ , expectedStatuses+ , knownLimitations+ , answerText+ ) where++import Control.Monad (filterM)+import Data.List (isSuffixOf, sort)+import Data.Text (Text)+import System.Directory (doesDirectoryExist, doesFileExist, listDirectory)+import System.FilePath (makeRelative, (</>))++import HSMT.SMT.Engine (EngineResult (..))+import HSMT.SMTLib.Parser (SExpr (..), parseSExprsPartial)++benchmarkDir :: FilePath+benchmarkDir = "bench" </> "smtlib"++-- | Every @.smt2@ file under 'benchmarkDir', relative to it, in order.+benchmarkFiles :: IO [FilePath]+benchmarkFiles = do+ exists <- doesDirectoryExist benchmarkDir+ if exists then sort . map (makeRelative benchmarkDir) <$> walk benchmarkDir else pure []+ where+ walk dir = do+ entries <- map (dir </>) <$> listDirectory dir+ files <- filterM doesFileExist entries+ dirs <- filterM doesDirectoryExist entries+ ((filter (".smt2" `isSuffixOf`) files) <>) . concat <$> mapM walk dirs++-- | The status in effect at each @check-sat@ and @check-sat-assuming@ of a+-- script, in order (@unknown@ when none was given).+expectedStatuses :: Text -> [Text]+expectedStatuses txt = go "unknown" (fst (parseSExprsPartial txt))+ where+ go st = \case+ [] -> []+ SList [SSym "set-info", SKey "status", SSym s] : rest -> go s rest+ SList (SSym c : _) : rest | c `elem` ["check-sat", "check-sat-assuming"] -> st : go st rest+ _ : rest -> go st rest++-- | Benchmarks hsmt answers with @unknown@ (or not in reasonable time), and+-- why. The test suite accepts @unknown@ from these, and only from these.+knownLimitations :: [(FilePath, Text)]+knownLimitations =+ [ ("QF_S" </> "no_conjugate.smt2", "unsatisfiable for every length; the string encoding is bounded")+ , ("QF_S" </> "replace_contains.smt2", "unsatisfiable for every length; the string encoding is bounded")+ , ("QF_SLIA" </> "from_int_roundtrip.smt2", "str.from_int over unbounded integers")+ , ("QF_BV" </> "mul_commutes16.smt2", "equivalence of multipliers; bit-blasting has no word-level rewriting")+ ]++answerText :: EngineResult -> Text+answerText = \case+ ESat _ -> "sat"+ EUnsat _ -> "unsat"+ EUnknown _ -> "unknown"
+ test-common/HSMT/Gen/Expr.hs view
@@ -0,0 +1,625 @@+-- | Sort-directed QuickCheck generators of well-sorted core expressions.+--+-- Shared by the unit test suite (printer/parser round trips) and by the+-- differential suite against Z3. The configuration selects the sorts in play+-- and the theories whose interpreted operators may appear; literals of every+-- sort in play are always allowed.+module HSMT.Gen.Expr+ ( Theory (..)+ , GenConfig (..)+ , eufConfig+ , liaConfig+ , ufliaConfig+ , bvConfig+ , ufbvConfig+ , axConfig+ , aliaConfig+ , abvConfig+ , recordConfig+ , recordMixConfig+ , stringConfig+ , sliaConfig+ , regexConfig+ , sliaRegexConfig+ , genRegex+ , fpConfig+ , fpMixConfig+ , allTheoriesConfig+ , Signature (..)+ , genSignature+ , genTerm+ , genProblem+ , shrinkExpr+ , shrinkProblem+ , sortOfExpr+ , fpLiteral+ ) where++import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import qualified Data.Text as T+import Test.QuickCheck++import HSMT.Core.Expr+import qualified HSMT.Core.Float as F+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Typing++data Theory = TArith | TBitVec | TArray | TString | TRecord | TFloat | TRegex+ deriving (Eq, Ord, Show, Enum, Bounded)++data GenConfig = GenConfig+ { gcSorts :: [Sort]+ -- ^ Sorts (besides Bool) of symbols and terms.+ , gcTheories :: Set Theory+ -- ^ Theories whose operators may be used.+ , gcDepth :: Int+ -- ^ Maximum term depth.+ , gcAssertions :: (Int, Int)+ -- ^ Range of the number of assertions of a problem.+ , gcFunctions :: Bool+ -- ^ Whether to declare uninterpreted functions.+ , gcDivisors :: [Integer]+ -- ^ Literal divisors of integer division and remainder.+ }+ deriving (Show)++-- | Uninterpreted functions, equalities and literals (QF_UF with literal+-- values of other sorts).+eufConfig :: GenConfig+eufConfig =+ GenConfig+ { gcSorts = [UninterpretedSort "U", UninterpretedSort "V", IntSort, BVSort 2]+ , gcTheories = Set.empty+ , gcDepth = 3+ , gcAssertions = (1, 7)+ , gcFunctions = True+ , gcDivisors = [-2, -1, 1, 2, 3]+ }++-- | Linear integer arithmetic (QF_LIA), including division by literals and+-- by zero.+liaConfig :: GenConfig+liaConfig =+ GenConfig+ { gcSorts = [IntSort]+ , gcTheories = Set.singleton TArith+ , gcDepth = 3+ , gcAssertions = (1, 6)+ , gcFunctions = False+ , gcDivisors = [-3, -2, 0, 2, 3, 5]+ }++-- | Uninterpreted functions over integers (QF_UFLIA).+ufliaConfig :: GenConfig+ufliaConfig =+ liaConfig+ { gcSorts = [IntSort, UninterpretedSort "U"]+ , gcFunctions = True+ }++-- | Fixed-width bit-vectors (QF_BV), with extraction, concatenation and+-- extension between the widths in play.+bvConfig :: GenConfig+bvConfig =+ GenConfig+ { gcSorts = [BVSort 1, BVSort 2, BVSort 3, BVSort 4, BVSort 8]+ , gcTheories = Set.singleton TBitVec+ , gcDepth = 3+ , gcAssertions = (1, 6)+ , gcFunctions = False+ , gcDivisors = []+ }++-- | Uninterpreted functions over bit-vectors (QF_UFBV).+ufbvConfig :: GenConfig+ufbvConfig =+ bvConfig+ { gcSorts = [BVSort 2, BVSort 4, BVSort 8, UninterpretedSort "U"]+ , gcFunctions = True+ }++-- | Arrays over uninterpreted sorts with uninterpreted functions (QF_AUF),+-- including arrays of Booleans and nested arrays.+axConfig :: GenConfig+axConfig =+ GenConfig+ { gcSorts =+ [ UninterpretedSort "U"+ , ArraySort (UninterpretedSort "U") (UninterpretedSort "U")+ , ArraySort (UninterpretedSort "U") BoolSort+ , ArraySort (UninterpretedSort "U") (ArraySort (UninterpretedSort "U") (UninterpretedSort "U"))+ ]+ , gcTheories = Set.singleton TArray+ , gcDepth = 3+ , gcAssertions = (1, 6)+ , gcFunctions = True+ , gcDivisors = []+ }++-- | Arrays with linear integer arithmetic (QF_ALIA).+aliaConfig :: GenConfig+aliaConfig =+ liaConfig+ { gcSorts = [IntSort, ArraySort IntSort IntSort, ArraySort IntSort BoolSort, ArraySort BoolSort IntSort]+ , gcTheories = Set.fromList [TArith, TArray]+ , gcDivisors = [-2, 2, 3]+ }++-- | Arrays with bit-vectors (QF_ABV), over index sorts that are expanded+-- (widths 2 and 4) and that are not (width 8).+abvConfig :: GenConfig+abvConfig =+ bvConfig+ { gcSorts =+ [ BVSort 2+ , BVSort 4+ , BVSort 8+ , ArraySort (BVSort 2) (BVSort 4)+ , ArraySort (BVSort 4) BoolSort+ , ArraySort (BVSort 8) (BVSort 2)+ ]+ , gcTheories = Set.fromList [TBitVec, TArray]+ }++-- | Records over uninterpreted sorts and Booleans, with uninterpreted+-- functions: nested records, the empty record and a record with only four+-- values.+recordConfig :: GenConfig+recordConfig =+ GenConfig+ { gcSorts = [u, r1, RecordSort [("in", r1), ("v", u)], RecordSort [], RecordSort [("c", BoolSort), ("d", BoolSort)]]+ , gcTheories = Set.singleton TRecord+ , gcDepth = 3+ , gcAssertions = (1, 6)+ , gcFunctions = True+ , gcDivisors = []+ }+ where+ u = UninterpretedSort "U"+ r1 = RecordSort [("u", u), ("p", BoolSort)]++-- | Records with integer and bit-vector fields, arrays of records and arrays+-- indexed by records (an infinite record sort and an expanded finite one).+recordMixConfig :: GenConfig+recordMixConfig =+ GenConfig+ { gcSorts =+ [ IntSort+ , BVSort 2+ , ri+ , rf+ , ArraySort IntSort ri+ , ArraySort rf IntSort+ , ArraySort ri (BVSort 2)+ ]+ , gcTheories = Set.fromList [TArith, TBitVec, TArray, TRecord]+ , gcDepth = 3+ , gcAssertions = (1, 6)+ , gcFunctions = True+ , gcDivisors = [-2, 2, 3]+ }+ where+ ri = RecordSort [("a", IntSort), ("b", BVSort 2)]+ rf = RecordSort [("c", BoolSort), ("d", BVSort 1)]++-- | Strings (QF_S); integer arguments are literals.+stringConfig :: GenConfig+stringConfig =+ GenConfig+ { gcSorts = [StringSort]+ , gcTheories = Set.singleton TString+ , gcDepth = 3+ , gcAssertions = (1, 5)+ , gcFunctions = False+ , gcDivisors = []+ }++-- | Strings with linear integer arithmetic and uninterpreted functions+-- (QF_SLIA with functions).+sliaConfig :: GenConfig+sliaConfig =+ stringConfig+ { gcSorts = [StringSort, IntSort]+ , gcTheories = Set.fromList [TString, TArith]+ , gcFunctions = True+ , gcDivisors = [-2, 2, 3]+ }++-- | Strings with membership in ground regular expressions.+regexConfig :: GenConfig+regexConfig = stringConfig {gcTheories = Set.fromList [TString, TRegex]}++-- | 'sliaConfig' with membership in ground regular expressions.+sliaRegexConfig :: GenConfig+sliaRegexConfig = sliaConfig {gcTheories = Set.fromList [TString, TArith, TRegex]}++-- | A ground regular expression of at most the given depth, over the+-- characters of the generated string literals.+genRegex :: Int -> Gen Expr+genRegex d+ | d <= 0 = leaf+ | otherwise =+ frequency+ [ (3, leaf)+ , (3, App ReConcat <$> (chooseInt (2, 3) >>= \k -> vectorOf k sub))+ , (3, App ReUnion <$> vectorOf 2 sub)+ , (1, App ReInter <$> vectorOf 2 sub)+ , (2, App ReStar . pure <$> sub)+ , (1, App RePlus . pure <$> sub)+ , (1, App ReOpt . pure <$> sub)+ , (1, App ReComp . pure <$> sub)+ , (1, App ReDiff <$> vectorOf 2 sub)+ , (1, do+ i <- chooseInt (0, 2)+ j <- chooseInt (0, 3)+ App (ReLoop i j) . pure <$> sub)+ , (1, chooseInt (0, 3) >>= \n -> App (RePower n) . pure <$> sub)+ ]+ where+ sub = genRegex (d - 1)+ str w = constant (StrConst w)+ leaf =+ frequency+ [ (5, App StrToRe . pure . str <$> elements ["", "a", "b", "ab", "ba", "aab", "\"", "é"])+ , (2, (\(a, b) -> App ReRange [str a, str b]) <$> elements [("a", "b"), ("a", "c"), ("b", "b"), ("b", "a"), ("ab", "c")])+ , (1, pure (constant ReAllChar))+ , (1, pure (constant ReAll))+ , (1, pure (constant ReNone))+ ]++-- | Floating point (QF_FP) over two small formats, with rounding-mode+-- constants and conversions between the formats. Z3's bit-blaster rejects+-- or answers unknown on formats whose significand is not wider than the+-- exponent, so the formats have @sb >= eb + 2@.+fpConfig :: GenConfig+fpConfig =+ GenConfig+ { gcSorts = [FPSort 3 5, FPSort 4 6, RoundingModeSort]+ , gcTheories = Set.singleton TFloat+ , gcDepth = 3+ , gcAssertions = (1, 5)+ , gcFunctions = False+ , gcDivisors = []+ }++-- | Floating point with bit-vectors and uninterpreted functions (QF_UFBVFP):+-- conversions to and from bit-vectors, and Float16.+fpMixConfig :: GenConfig+fpMixConfig =+ fpConfig+ { gcSorts = [FPSort 3 5, FPSort 5 11, RoundingModeSort, BVSort 3, BVSort 8]+ , gcTheories = Set.fromList [TFloat, TBitVec]+ , gcFunctions = True+ , gcDepth = 2+ }++-- | Every theory and a variety of sorts.+allTheoriesConfig :: GenConfig+allTheoriesConfig =+ GenConfig+ { gcSorts =+ [ IntSort+ , BVSort 1+ , BVSort 2+ , BVSort 3+ , StringSort+ , UninterpretedSort "U"+ , ArraySort IntSort IntSort+ , ArraySort (BVSort 2) BoolSort+ , rec1+ , RecordSort [("in", rec1), ("flag", BoolSort)]+ , FPSort 3 5+ , FPSort 4 6+ , RoundingModeSort+ ]+ , gcTheories = Set.fromList [minBound .. maxBound]+ , gcDepth = 3+ , gcAssertions = (1, 4)+ , gcFunctions = True+ , gcDivisors = [-2, -1, 1, 2, 3]+ }+ where+ rec1 = RecordSort [("a", IntSort), ("b", BVSort 2)]++-- | Declared constants (by sort) and functions.+data Signature = Signature+ { sigConsts :: Map Sort [Symbol]+ , sigFuns :: [Symbol]+ }+ deriving (Show)++allSorts :: GenConfig -> [Sort]+allSorts cfg = BoolSort : gcSorts cfg++genSignature :: GenConfig -> Gen Signature+genSignature cfg = do+ consts <- sequence [constsOf i s | (i, s) <- zip [0 :: Int ..] (allSorts cfg)]+ nFuns <- if gcFunctions cfg then chooseInt (0, 3) else pure 0+ funs <- sequence [mkFunction k | k <- [0 .. nFuns - 1]]+ pure (Signature (Map.fromList consts) funs)+ where+ constsOf i s = do+ n <- if s == BoolSort then chooseInt (0, 2) else chooseInt (1, 3)+ -- "f" and "p" are reserved for functions and Boolean constants.+ let prefix = if s == BoolSort then "p" else T.singleton (cycle "abcdeghijkmnqrstuvwyz" !! (i - 1))+ pure (s, [Symbol (prefix <> T.pack (show j)) [] s | j <- [0 .. n - 1]])+ mkFunction k = do+ arity <- chooseInt (1, 2)+ args <- vectorOf arity (elements (allSorts cfg))+ result <- frequency [(1, pure BoolSort), (3, elements (gcSorts cfg))]+ pure (Symbol ("f" <> T.pack (show k)) args result)++has :: GenConfig -> Theory -> Bool+has cfg t = Set.member t (gcTheories cfg)++-- | A term of the given sort with at most the given depth.+genTerm :: GenConfig -> Signature -> Int -> Sort -> Gen Expr+genTerm cfg sig = go+ where+ sorts = allSorts cfg+ inPlay s = s `elem` sorts++ go d s+ | d <= 0 = leaf s+ | otherwise = frequency ((3, leaf s) : compound (d - 1) s)++ leaf s = oneof (map (pure . constant . Uninterpreted) consts <> literal s)+ where+ consts = Map.findWithDefault [] s (sigConsts sig)++ literal = \case+ BoolSort -> [constant . BoolConst <$> arbitrary]+ IntSort -> [constant . IntConst <$> chooseInteger (-3, 3)]+ BVSort w -> [constant . BVConst w <$> chooseInteger (0, 2 ^ w - 1)]+ StringSort -> [constant . StrConst <$> elements ["", "a", "b", "ab", "ba", "aab", "\"", "\\u", "é"]]+ ArraySort i e | has cfg TArray -> [(\x -> App (ConstArray i) [x]) <$> leaf e]+ RecordSort fs -> [App (RecordMk (map fst fs)) <$> traverse (leaf . snd) fs]+ FPSort eb sb -> [constant . FPConst eb sb <$> fpLiteral eb sb]+ RoundingModeSort -> [constant . RMConst <$> elements F.allRoundingModes]+ _ -> []++ build op argSorts d = App op <$> traverse (go d) argSorts++ compound d s =+ [ (2, build (Uninterpreted f) (symArgs f) d)+ | f <- sigFuns sig+ , symResult f == s+ ]+ <> [(1, build Ite [BoolSort, s, s] d)]+ <> [(1, build Select [ArraySort i s, i] d) | has cfg TArray, ArraySort i e <- sorts, e == s]+ <> [ (1, build (RecordGet f) [r] d)+ | has cfg TRecord+ , r@(RecordSort fs) <- sorts+ , (f, fs') <- fs+ , fs' == s+ ]+ <> specific d s+ <> floating d s++ -- Floating-point operators, by result sort.+ floating d = \case+ _ | not (has cfg TFloat) -> []+ BoolSort ->+ [ (2, elements fpSorts >>= \t -> elements [FPLeq, FPLt, FPGeq, FPGt, FPEq] >>= \op -> build op [t, t] d)+ , ( 2+ , elements fpSorts >>= \t ->+ elements [FPIsNormal, FPIsSubnormal, FPIsZero, FPIsInfinite, FPIsNaN, FPIsNegative, FPIsPositive]+ >>= \op -> build op [t] d+ )+ ]+ t@(FPSort eb sb) ->+ [ (1, elements [FPAbs, FPNeg] >>= \op -> build op [t] d)+ , (4, elements [FPAdd, FPSub, FPMul, FPDiv] >>= \op -> build op [RoundingModeSort, t, t] d)+ , (1, build FPFma [RoundingModeSort, t, t, t] d)+ , (1, elements [FPSqrt, FPRoundToIntegral] >>= \op -> build op [RoundingModeSort, t] d)+ , (1, elements [FPRem, FPMin, FPMax] >>= \op -> build op [t, t] d)+ , (1, build FPFromFields [BVSort 1, BVSort eb, BVSort (sb - 1)] d)+ ]+ <> [(1, build (ToFP eb sb) [RoundingModeSort, u] d) | u <- fpSorts, u /= t]+ <> [ (1, build (ToFP eb sb) [BVSort w] d)+ | has cfg TBitVec+ , BVSort w <- sorts+ , w == eb + sb+ ]+ <> [ (1, elements [ToFP eb sb, ToFPUnsigned eb sb] >>= \op -> build op [RoundingModeSort, BVSort w] d)+ | has cfg TBitVec+ , BVSort w <- sorts+ ]+ BVSort w+ | has cfg TBitVec ->+ [ (1, elements [FPToUBV w, FPToSBV w] >>= \op -> build op [RoundingModeSort, t] d)+ | t <- fpSorts+ ]+ _ -> []++ fpSorts = [t | t@(FPSort _ _) <- sorts]++ specific d = \case+ BoolSort ->+ [ (1, build Not [BoolSort] d)+ , (1, nary And BoolSort d)+ , (1, nary Or BoolSort d)+ , (1, build Xor [BoolSort, BoolSort] d)+ , (1, build Implies [BoolSort, BoolSort] d)+ , (4, elements sorts >>= \t -> build Eq [t, t] d)+ , (2, elements sorts >>= \t -> nary Distinct t d)+ ]+ <> [ (1, elements [Le, Lt, Ge, Gt] >>= \op -> build op [IntSort, IntSort] d)+ | has cfg TArith && inPlay IntSort+ ]+ <> [ (1, elements bvPreds >>= \op -> build op [BVSort w, BVSort w] d)+ | has cfg TBitVec+ , BVSort w <- sorts+ ]+ <> [ (1, elements [StrContains, StrPrefixOf, StrSuffixOf, StrLt, StrLe] >>= \op -> build op [StringSort, StringSort] d)+ | has cfg TString && inPlay StringSort+ ]+ <> [ (3, App StrInRe <$> sequence [go d StringSort, genRegex 3])+ | has cfg TRegex && inPlay StringSort+ ]+ IntSort ->+ [ (w, g)+ | has cfg TArith+ , (w, g) <-+ [ (2, nary Add IntSort d)+ , (1, build Sub [IntSort, IntSort] d)+ , (1, build Neg [IntSort] d)+ , (1, App Mul <$> sequence [intLit, go d IntSort])+ , (1, App IntDiv <$> sequence [go d IntSort, divisor])+ , (1, App IntMod <$> sequence [go d IntSort, divisor])+ , (1, build Abs [IntSort] d)+ ]+ ]+ <> [ (w, g)+ | has cfg TString && inPlay StringSort+ , (w, g) <-+ [ (1, build StrLen [StringSort] d)+ , (1, build StrIndexOf [StringSort, StringSort, IntSort] d)+ , (1, build StrToInt [StringSort] d)+ ]+ ]+ BVSort w+ | has cfg TBitVec ->+ [ (1, elements [BVNot, BVNeg] >>= \op -> build op [BVSort w] d)+ , (3, elements bvBinary >>= \op -> build op [BVSort w, BVSort w] d)+ ]+ <> [ (1, do+ lo <- chooseInt (0, w' - w)+ build (BVExtract (lo + w - 1) lo) [BVSort w'] d)+ | BVSort w' <- sorts+ , w' > w+ ]+ <> [ (1, build BVConcat [BVSort a, BVSort (w - a)] d)+ | BVSort a <- sorts+ , a < w+ , inPlay (BVSort (w - a))+ ]+ <> [ (1, elements [BVZeroExtend (w - w'), BVSignExtend (w - w')] >>= \op -> build op [BVSort w'] d)+ | BVSort w' <- sorts+ , w' < w+ ]+ StringSort+ | has cfg TString ->+ [ (2, build StrConcat [StringSort, StringSort] d)+ , (1, build StrAt [StringSort, IntSort] d)+ , (1, build StrSubstr [StringSort, IntSort, IntSort] d)+ , (1, build StrReplace [StringSort, StringSort, StringSort] d)+ , (1, build StrFromInt [IntSort] d)+ ]+ ArraySort i e+ | has cfg TArray -> [(2, build Store [ArraySort i e, i, e] d)]+ RecordSort fs+ | has cfg TRecord && not (null fs) ->+ [(2, elements fs >>= \(f, s) -> build (RecordSet f) [RecordSort fs, s] d)]+ _ -> []++ nary op s d = chooseInt (2, 3) >>= \k -> build op (replicate k s) d++ intLit = constant . IntConst <$> elements [-2, -1, 1, 2, 3]+ divisor = constant . IntConst <$> elements (gcDivisors cfg)++ bvPreds = [BVULt, BVULe, BVUGt, BVUGe, BVSLt, BVSLe, BVSGt, BVSGe]+ bvBinary =+ [ BVAnd, BVOr, BVXor, BVAdd, BVSub, BVMul, BVUDiv, BVURem, BVSDiv, BVSRem+ , BVSMod, BVShl, BVLShr, BVAShr+ ]++-- | A floating-point literal: special values, the extremes of each kind,+-- and random patterns.+fpLiteral :: Int -> Int -> Gen Integer+fpLiteral eb sb =+ F.canonicalize eb sb+ <$> frequency+ [ (3, elements specials)+ , (4, chooseInteger (0, 2 ^ (eb + sb) - 1))+ ]+ where+ enc = F.encode eb sb+ sig = 2 ^ (sb - 1)+ expField e = e * sig+ neg = (2 ^ (eb + sb - 1) +)+ specials =+ [ enc F.NaN+ , enc (F.Inf False)+ , enc (F.Inf True)+ , enc (F.Zero False)+ , enc (F.Zero True)+ , 1 -- smallest subnormal+ , neg 1+ , sig - 1 -- largest subnormal+ , expField 1 -- smallest normal+ , expField (2 ^ eb - 2) + sig - 1 -- largest finite+ , neg (expField (2 ^ eb - 2) + sig - 1)+ , expField (2 ^ (eb - 1) - 1) -- one+ , neg (expField (2 ^ (eb - 1) - 1))+ , expField (2 ^ (eb - 1)) -- two+ , expField (2 ^ (eb - 1) - 1) + 1 -- just above one+ ]++-- | A list of assertions. Most assertions are small clauses over atoms,+-- which gives a reasonable mix of satisfiable and unsatisfiable problems;+-- the rest are arbitrary Boolean terms.+genProblem :: GenConfig -> Gen [Expr]+genProblem cfg = do+ sig <- genSignature cfg+ n <- chooseInt (gcAssertions cfg)+ vectorOf n (assertion sig)+ where+ assertion sig =+ frequency+ [ (3, clause sig)+ , (1, chooseInt (1, gcDepth cfg) >>= \d -> genTerm cfg sig d BoolSort)+ ]+ clause sig = do+ k <- frequency [(3, pure 1), (2, pure 2), (1, pure 3)]+ lits <- vectorOf k (literal sig)+ pure $ case lits of+ [l] -> l+ _ -> App Or lits+ literal sig = do+ a <- atom sig+ positive <- frequency [(2, pure True), (1, pure False)]+ pure (if positive then a else App Not [a])+ atom sig = do+ s <- elements (allSorts cfg)+ d <- chooseInt (0, gcDepth cfg - 1)+ frequency $+ [(2, App Eq <$> vectorOf 2 (genTerm cfg sig d s))]+ <> [ (3, elements [Le, Lt, Ge, Gt] >>= \op -> App op <$> vectorOf 2 (genTerm cfg sig d IntSort))+ | Set.member TArith (gcTheories cfg) && IntSort `elem` gcSorts cfg+ ]+ <> [ (3, elements bvPredicates >>= \op -> App op <$> vectorOf 2 (genTerm cfg sig d w))+ | Set.member TBitVec (gcTheories cfg)+ , w@(BVSort _) <- [s]+ ]+ <> [ (3, App StrInRe <$> sequence [genTerm cfg sig d StringSort, genRegex 3])+ | Set.member TRegex (gcTheories cfg) && StringSort `elem` gcSorts cfg+ ]+ bvPredicates = [BVULt, BVULe, BVUGt, BVUGe, BVSLt, BVSLe, BVSGt, BVSGe]++-- | Sort of a generated (hence well-sorted) expression.+sortOfExpr :: Expr -> Sort+sortOfExpr e = either (error . show) id (sortOf e)++-- | Replace the expression by a proper subterm of the same sort, or shrink+-- one argument. Both keep the expression well sorted.+shrinkExpr :: Expr -> [Expr]+shrinkExpr e@(App op args) =+ sameSortSubterms <> [App op args' | args' <- shrinkOne args]+ where+ s = sortOfExpr e+ sameSortSubterms =+ Set.toList . Set.fromList $+ [t | a <- args, t <- subtermsOf a, sortOfExpr t == s]+ shrinkOne [] = []+ shrinkOne (x : xs) = [x' : xs | x' <- shrinkExpr x] <> [x : xs' | xs' <- shrinkOne xs]++subtermsOf :: Expr -> [Expr]+subtermsOf e@(App _ args) = e : concatMap subtermsOf args++shrinkProblem :: [Expr] -> [[Expr]]+shrinkProblem = filter (not . null) . shrinkList shrinkExpr
+ test-diff/Differential/Oracle.hs view
@@ -0,0 +1,516 @@+-- | Comparison of hsmt against Z3: results, models, incremental sequences+-- and the semantics of ground terms.+module Differential.Oracle+ ( Outcome (..)+ , checkProblem+ , Step (..)+ , genSteps+ , shrinkSteps+ , stepsScript+ , checkSteps+ , checkBackends+ , checkGroundTerm+ , confirmMismatch+ , regressionText+ ) where++import Control.Exception (SomeException, evaluate, try)+import Data.Text (Text)+import qualified Data.Text as T+import System.Timeout (timeout)+import Test.QuickCheck++import qualified HSMT.API.Expr as API+import qualified HSMT.API.Model as API+import qualified HSMT.API.Monad as API+import HSMT.Backend (Backend (..), ExternalSolver (..), z3Backend)+import HSMT.Core.Eval+import Data.Maybe (isNothing)+import HSMT.Core.Expr+import qualified HSMT.Core.Float as F+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Value+import HSMT.Gen.Expr+import HSMT.SMT.Engine+import HSMT.SMTLib.Printer+import HSMT.SMTLib.Syntax++import Differential.Z3++data Outcome+ = Agree Text+ -- ^ Both solvers agree; the text classifies the case.+ | Skip Text+ -- ^ One solver gave up; the case is discarded.+ | Mismatch Text [Command] [Answer]+ -- ^ A divergence: an explanation, the script that exhibits it and Z3's+ -- answers to that script (the expected ones).+ deriving (Show)++hsmtTimeoutSecs :: Int+hsmtTimeoutSecs = 10++-- | Run hsmt on a problem, with minimal cores, turning crashes and timeouts+-- into answers. The engine's own time limit is exercised; the outer one is a+-- safety net.+runHsmt :: [Expr] -> IO (Either Text EngineResult)+runHsmt as = do+ let opts =+ defaultCheckOptions+ { coTimeout = Just (fromIntegral hsmtTimeoutSecs)+ , coMinimizeCore = True+ }+ run = newSession >>= \sess -> checkSession sess opts as >>= evaluate+ r <- try (timeout (2 * hsmtTimeoutSecs * 1000000) run)+ pure $ case r of+ Right Nothing -> Right (EUnknown "hsmt timeout (hard limit)")+ Right (Just (EUnknown "timeout")) -> Right (EUnknown "hsmt timeout")+ Left (e :: SomeException) -> Left ("hsmt crashed: " <> T.pack (show e))+ Right (Just x) -> Right x++answerOf :: EngineResult -> Answer+answerOf = \case+ ESat _ -> AnsSat+ EUnsat _ -> AnsUnsat+ EUnknown _ -> AnsUnknown++-- | Decide a problem with both solvers. When both answer sat, the model of+-- hsmt is checked by the evaluator and, independently, by Z3.+checkProblem :: Z3 -> [Expr] -> IO Outcome+checkProblem z3 as = do+ mine <- runHsmt as+ theirs <- runZ3 z3 (z3Script cmds)+ case (mine, theirs) of+ (_, Left err) -> pure (Mismatch ("z3 rejected the script: " <> err) cmds [AnsUnknown])+ (Left err, Right zs) -> pure (Mismatch err cmds zs)+ (Right r, Right [z]) -> compareResult r z+ (Right _, Right zs) -> pure (Mismatch "unexpected number of z3 answers" cmds zs)+ where+ cmds = problemScript as++ compareResult r z = case (answerOf r, z) of+ (AnsUnknown, _) | EUnknown why <- r -> pure (Skip ("hsmt unknown: " <> why))+ (_, AnsUnknown) -> pure (Skip "z3 unknown")+ (a, b)+ | a /= b ->+ pure (Mismatch ("hsmt says " <> renderAnswer a <> ", z3 says " <> renderAnswer b) cmds [b])+ (AnsSat, _) | ESat interp <- r -> checkModel interp+ _ | EUnsat idx <- r -> checkMinimalCore z3 as [a | (i, a) <- zip [0 ..] as, i `elem` idx]+ _ -> pure (Agree "unsat")++ checkModel interp+ | bad <- [a | a <- as, evalExpr interp a /= Right (VBool True)]+ , not (null bad) =+ pure (Mismatch ("hsmt model fails the evaluator on " <> T.pack (show bad)) cmds [AnsSat])+ | otherwise = do+ let script =+ [SetLogic "ALL"]+ <> modelCommands interp as+ <> map Assert as+ <> [CheckSat]+ rejected why = Mismatch (why <> "\n" <> renderScript script) cmds [AnsSat]+ runZ3 z3 (z3Script script) >>= \case+ Right [AnsSat] -> pure (Agree "sat")+ Right [AnsUnknown] -> pure (Skip "z3 unknown on model check")+ Right zs -> pure (rejected ("z3 rejects the model of hsmt: " <> T.pack (show zs)))+ Left err -> pure (rejected ("z3 rejected the model script: " <> err))++-- | A minimal core of hsmt must be unsatisfiable for Z3, and removing any+-- of its formulas must make it satisfiable. One Z3 process checks the core+-- and then each formula's removal in its own scope.+checkMinimalCore :: Z3 -> [Expr] -> [Expr] -> IO Outcome+checkMinimalCore z3 as core =+ runZ3 z3 (z3Script script) >>= \case+ Left err -> pure (Mismatch ("z3 rejected the core script: " <> err) script [])+ Right (AnsUnknown : _) -> pure (Skip "z3 unknown on the core")+ Right (AnsSat : _) -> pure (Mismatch "the unsat core of hsmt is satisfiable" script [AnsSat])+ Right zs@(AnsUnsat : removals)+ -- The time limit of Z3 covers the whole script: a timeout answers+ -- unknown and drops the remaining answers.+ | AnsUnknown `elem` removals -> pure (Skip "z3 unknown on core minimality")+ | length removals /= length core -> pure (Mismatch "unexpected number of z3 answers" script zs)+ | AnsUnsat `elem` removals ->+ -- The bounded string encoding may miss refutations of core+ -- subsets, which then stay in the core.+ pure $+ if mentionsStrings+ then Agree "unsat (core not minimal: string bound)"+ else Mismatch "the unsat core of hsmt is not minimal" script zs+ | otherwise -> pure (Agree ("unsat, core of " <> T.pack (show (length core)) <> " of " <> T.pack (show (length as))))+ Right zs -> pure (Mismatch "unexpected z3 answers" script zs)+ where+ script =+ [SetLogic "ALL"]+ <> declarationsFor as+ <> [Push 1]+ <> map Assert core+ <> [CheckSat, Pop 1]+ <> concat+ [ [Push 1] <> [Assert c | (j, c) <- zip [0 :: Int ..] core, j /= i] <> [CheckSat, Pop 1]+ | i <- [0 .. length core - 1]+ ]+ mentionsStrings = any (hasString . sortOfExpr) (concatMap allSubterms as)+ hasString = \case+ StringSort -> True+ ArraySort i e -> hasString i || hasString e+ RecordSort fs -> any (hasString . snd) fs+ _ -> False+ allSubterms e@(App _ args) = e : concatMap allSubterms args++-------------------------------------------------------------------------------+-- Incremental sequences++data Step = SAssert Expr | SPush | SPop | SCheck | SCheckAssuming [Expr]+ deriving (Show)++-- | A well-bracketed sequence of commands ending with a @check-sat@.+genSteps :: GenConfig -> Gen [Step]+genSteps cfg = do+ sig <- genSignature cfg+ n <- chooseInt (4, 14)+ body <- go sig n (0 :: Int)+ pure (body <> [SCheck])+ where+ go _ 0 _ = pure []+ go sig k depth = do+ step <-+ frequency $+ [ (5, SAssert <$> assertion sig)+ , (2, pure SPush)+ , (2, pure SCheck)+ , (1, SCheckAssuming <$> (chooseInt (1, 3) >>= \m -> vectorOf m (assertion sig)))+ ]+ <> [(2, pure SPop) | depth > 0]+ let depth' = case step of+ SPush -> depth + 1+ SPop -> depth - 1+ _ -> depth+ (step :) <$> go sig (k - 1) depth'+ assertion sig = do+ s <- elements (BoolSort : gcSorts cfg)+ frequency+ [ (3, App Eq <$> vectorOf 2 (genTerm cfg sig 2 s))+ , (1, App Not . pure . App Eq <$> vectorOf 2 (genTerm cfg sig 2 s))+ , (1, genTerm cfg sig 2 BoolSort)+ ]++wellBracketed :: [Step] -> Bool+wellBracketed = go (0 :: Int)+ where+ go d [] = d >= 0+ go d (s : ss) = case s of+ SPush -> go (d + 1) ss+ SPop -> d > 0 && go (d - 1) ss+ _ -> go d ss++shrinkSteps :: [Step] -> [[Step]]+shrinkSteps =+ filter (\ss -> wellBracketed ss && any isCheck ss) . shrinkList shrinkStep+ where+ shrinkStep = \case+ SAssert e -> map SAssert (shrinkExpr e)+ SCheckAssuming es -> SCheck : map SCheckAssuming (filter (not . null) (shrinkList shrinkExpr es))+ _ -> []+ isCheck = \case+ SCheck -> True+ SCheckAssuming _ -> True+ _ -> False++stepsScript :: [Step] -> [Command]+stepsScript steps =+ [SetLogic "ALL"] <> declarationsFor (concatMap formulas steps) <> map toCommand steps+ where+ formulas = \case+ SAssert e -> [e]+ SCheckAssuming es -> es+ _ -> []+ toCommand = \case+ SAssert e -> Assert e+ SPush -> Push 1+ SPop -> Pop 1+ SCheck -> CheckSat+ SCheckAssuming es -> CheckSatAssuming es++-- | Run the sequence through the public monadic API and through one Z3+-- process, comparing every @check-sat@. The unsatisfiable cores of hsmt+-- (assertions and assumptions) must be unsatisfiable for Z3 as well.+checkSteps :: Z3 -> [Step] -> IO Outcome+checkSteps z3 steps = do+ mine <-+ try . timeout (hsmtTimeoutSecs * 1000000) $+ API.runSMT API.defaultConfig {API.cfgValidateModels = False} (concat <$> mapM run steps)+ theirs <- runZ3 z3 (z3Script cmds)+ case (mine, theirs) of+ (_, Left err) -> pure (Mismatch ("z3 rejected the script: " <> err) cmds [])+ (Left (e :: SomeException), Right zs) -> pure (Mismatch ("hsmt crashed: " <> T.pack (show e)) cmds zs)+ (Right Nothing, _) -> pure (Skip "hsmt timeout")+ (Right (Just results), Right zs)+ -- A Z3 timeout ends the script: the remaining answers are missing.+ | length zs < length as && (null zs || last zs == AnsUnknown) -> pure (Skip "z3 timeout")+ | length as /= length zs -> pure (Mismatch "different number of answers" cmds zs)+ | or [a /= z | (a, z) <- pairs] ->+ pure (Mismatch ("hsmt: " <> T.pack (show as) <> ", z3: " <> T.pack (show zs)) cmds zs)+ | null pairs -> pure (Skip "every check-sat unknown")+ | otherwise -> checkCores [c | (_, Just c) <- results]+ where+ as = map fst results+ pairs = [(a, z) | (a, z) <- zip as zs, a /= AnsUnknown, z /= AnsUnknown]+ where+ cmds = stepsScript steps+ run :: Step -> API.SMT c [(Answer, Maybe [Expr])]+ run = \case+ SAssert e -> [] <$ API.assert (API.Expr e)+ SPush -> [] <$ API.push+ SPop -> [] <$ API.pop+ SCheck -> pure <$> (API.checkSat >>= answer)+ SCheckAssuming es -> pure <$> (API.checkSatAssuming (map API.Expr es) >>= answer)+ answer :: API.Result c -> API.SMT c (Answer, Maybe [Expr])+ answer = \case+ API.Sat _ -> pure (AnsSat, Nothing)+ API.Unsat c ->+ pure (AnsUnsat, Just (map API.unExpr (API.coreAssertions c <> API.coreAssumptions c)))+ API.Unknown _ -> pure (AnsUnknown, Nothing)+ checks = length [() | s <- steps, isCheck s]+ isCheck = \case+ SCheck -> True+ SCheckAssuming _ -> True+ _ -> False+ checkCores [] = pure (Agree (T.pack (show checks) <> " checks"))+ checkCores cores = do+ let script =+ [SetLogic "ALL"]+ <> declarationsFor (concatMap formulasOf steps)+ <> concat [[Push 1] <> map Assert c <> [CheckSat, Pop 1] | c <- cores]+ runZ3 z3 (z3Script script) >>= \case+ Left err -> pure (Mismatch ("z3 rejected the core script: " <> err) script [])+ Right zs+ | AnsSat `elem` zs -> pure (Mismatch "an unsat core of hsmt is satisfiable" script zs)+ | otherwise -> pure (Agree (T.pack (show checks) <> " checks"))+ formulasOf = \case+ SAssert e -> [e]+ SCheckAssuming es -> es+ _ -> []++-------------------------------------------------------------------------------+-- Engine against the external backend++-- | One check of a sequence run through the API: the answer, whether the+-- model (if any) satisfies the active formulas under the reference+-- evaluator, and the core (if any).+data CheckInfo = CheckInfo Answer Bool (Maybe [Expr])++-- | Run a sequence through the API with the given configuration.+runSteps :: API.Config -> [Step] -> IO (Either Text [CheckInfo])+runSteps cfg steps = do+ r <- try . timeout (3 * hsmtTimeoutSecs * 1000000) $ API.runSMT cfg (concat <$> mapM run steps)+ pure $ case r of+ Left (e :: SomeException) -> Left ("crashed: " <> T.pack (show e))+ Right Nothing -> Left "timeout"+ Right (Just xs) -> Right xs+ where+ run :: Step -> API.SMT c [CheckInfo]+ run = \case+ SAssert e -> [] <$ API.assert (API.Expr e)+ SPush -> [] <$ API.push+ SPop -> [] <$ API.pop+ SCheck -> API.checkSat >>= info []+ SCheckAssuming es -> API.checkSatAssuming (map API.Expr es) >>= info es+ info :: [Expr] -> API.Result c -> API.SMT c [CheckInfo]+ info extra r = do+ active <- API.assertions+ pure . pure $ case r of+ API.Sat m ->+ let holds e = evalExpr (API.modelInterpretation m) e == Right (VBool True)+ in CheckInfo AnsSat (all holds (active <> extra)) Nothing+ API.Unsat c -> CheckInfo AnsUnsat True (Just (map API.unExpr (API.coreAssertions c <> API.coreAssumptions c)))+ API.Unknown _ -> CheckInfo AnsUnknown True Nothing++-- | Run a sequence through the API with the engine and with Z3 as external+-- backend: definite answers must agree, every model must satisfy the+-- active formulas, and the cores of the external backend must be+-- unsatisfiable for Z3. The external backend gets the formulas rewritten+-- around Z3's known errors ('expandFma', 'expandArrayEqs'), which does not+-- change their meaning.+checkBackends :: Z3 -> [Step] -> IO Outcome+checkBackends z3 steps = do+ let base =+ API.defaultConfig+ { API.cfgValidateModels = False+ , API.cfgTimeout = Just (hsmtTimeoutSecs * 1000)+ , API.cfgMinimizeCores = True+ }+ external = External z3Backend {solverPath = z3Path z3}+ rewritten = map (mapStep (expandArrayEqs . expandFma)) steps+ native <- runSteps base steps+ theirs <- runSteps base {API.cfgBackend = external} rewritten+ case (native, theirs) of+ (Left "timeout", _) -> pure (Skip "hsmt timeout")+ (_, Left "timeout") -> pure (Skip "external backend timeout")+ (Left e, _) -> pure (Mismatch ("engine " <> e) cmds [])+ (_, Left e) -> pure (Mismatch ("external backend " <> e) cmds [])+ (Right ms, Right ts)+ | or [not ok | CheckInfo _ ok _ <- ms] -> pure (Mismatch "a model of the engine fails the evaluator" cmds (answers ts))+ | or [not ok | CheckInfo _ ok _ <- ts] -> pure (Mismatch "a model of the external backend fails the evaluator" cmds (answers ts))+ | or [a /= b | (a, b) <- pairs] ->+ pure (Mismatch ("engine: " <> T.pack (show (answers ms)) <> ", external: " <> T.pack (show (answers ts))) cmds (answers ts))+ | null pairs -> pure (Skip "every check-sat unknown")+ | otherwise -> checkCores [c | CheckInfo _ _ (Just c) <- ts]+ where+ pairs = [(a, b) | (a, b) <- zip (answers ms) (answers ts), a /= AnsUnknown, b /= AnsUnknown]+ where+ cmds = stepsScript steps+ answers xs = [a | CheckInfo a _ _ <- xs]+ checks = length [() | s <- steps, isCheck s]+ isCheck = \case+ SCheck -> True+ SCheckAssuming _ -> True+ _ -> False+ mapStep f = \case+ SAssert e -> SAssert (f e)+ SCheckAssuming es -> SCheckAssuming (map f es)+ st -> st+ checkCores [] = pure (Agree (T.pack (show checks) <> " checks"))+ checkCores cores = do+ let script =+ [SetLogic "ALL"]+ <> declarationsFor (concat cores)+ <> concat [[Push 1] <> map Assert c <> [CheckSat, Pop 1] | c <- cores]+ runZ3 z3 (z3Script script) >>= \case+ Left err -> pure (Mismatch ("z3 rejected the core script: " <> err) script [])+ Right zs+ | AnsSat `elem` zs -> pure (Mismatch "an unsat core of the external backend is satisfiable" script zs)+ | otherwise -> pure (Agree (T.pack (show checks) <> " checks"))++-------------------------------------------------------------------------------+-- Ground terms++-- | The reference evaluator and Z3 must agree on the value of a ground+-- term: Z3 must find @(distinct t v)@ unsatisfiable, where @v@ is the value+-- computed by the evaluator.+checkGroundTerm :: Z3 -> Expr -> IO Outcome+checkGroundTerm z3 t+ | hitsUnspecified t = pure (Skip "unspecified floating-point result")+ | otherwise = checkGroundTerm' z3 t++-- | Whether evaluating the ground term meets a result that SMT-LIB leaves+-- unspecified (Z3 may then pick any value).+hitsUnspecified :: Expr -> Bool+hitsUnspecified e@(App op args) = any hitsUnspecified args || here+ where+ vals = traverse (evalExpr emptyInterpretation) args+ here = case (op, vals) of+ (FPMin, Right [VFP eb sb x, VFP _ _ y]) -> isNothing (F.fpMin eb sb x y)+ (FPMax, Right [VFP eb sb x, VFP _ _ y]) -> isNothing (F.fpMax eb sb x y)+ (FPToUBV w, Right [VRM rm, VFP eb sb x]) -> isNothing (F.fpToInteger rm eb sb (0, 2 ^ w - 1) x)+ (FPToSBV w, Right [VRM rm, VFP eb sb x]) ->+ isNothing (F.fpToInteger rm eb sb (negate (2 ^ (w - 1)), 2 ^ (w - 1) - 1) x)+ _ -> const False e++checkGroundTerm' :: Z3 -> Expr -> IO Outcome+checkGroundTerm' z3 t = case evalExpr emptyInterpretation t of+ Left err -> pure (Mismatch ("evaluator error: " <> T.pack (show err)) (problemScript [t]) [])+ Right v -> do+ let claim = App Distinct [t, valueExpr v]+ script = problemScript [claim]+ runZ3 z3 (z3Script script) >>= \case+ Right [AnsUnsat] -> pure (Agree (renderSort (valueSort v)))+ Right [AnsUnknown] -> pure (Skip "z3 unknown")+ -- No answer at all: Z3 was killed (e.g. the suite was interrupted).+ Right [] -> pure (Skip "z3 gave no answer")+ Right zs ->+ pure (Mismatch ("z3 disagrees with the evaluator value " <> prettyValue v) script zs)+ Left err -> pure (Mismatch ("z3 rejected the script: " <> err) script [])++-- | Z3 is not infallible: before reporting a divergence, the script is+-- solved again by Z3 in two other ways: with its alternative SMT core+-- (@sat.smt=true@), and with equalities between arrays over small finite+-- index sorts expanded pointwise. When any of them disagrees with the first+-- answer (or fails, e.g. because Z3 could not validate its own model), Z3 is+-- not a reliable oracle for the case and it is discarded (and counted).+--+-- Known instances (Z3 4.16.0): equalities and disequalities between stored+-- arrays over a finite index sort, e.g.+-- @(= (store ((as const (Array (_ BitVec 2) Bool)) false) #b10 true)+-- (store ((as const (Array (_ BitVec 2) Bool)) true) #b01 false))@, are+-- reported satisfiable although the arrays differ at index @#b00@; some of+-- them fool both cores.+confirmMismatch :: Z3 -> Outcome -> IO Outcome+confirmMismatch z3 = \case+ m@(Mismatch _ cmds zs) | not (null zs) -> do+ let alternatives =+ [ (z3 {z3Options = ["sat.smt=true"]}, cmds)+ , (z3, map (mapAssertions expandArrayEqs) cmds)+ ]+ answers <- mapM (\(z, cs) -> runZ3 z (z3Script cs)) alternatives+ pure $+ if any (/= Right zs) answers+ then Skip "z3 configurations disagree"+ else m+ other -> pure other++-- | The text of a script for Z3, working around its known errors (see+-- 'expandFma').+z3Script :: [Command] -> Text+z3Script = renderScript . map (mapAssertions expandFma)++mapAssertions :: (Expr -> Expr) -> Command -> Command+mapAssertions f = \case+ Assert e -> Assert (f e)+ CheckSatAssuming es -> CheckSatAssuming (map f es)+ c -> c++-- | Z3 4.16.0 computes wrong results of @fp.fma@ in small formats (for+-- instance @(fp.fma RTZ (fp #b1 #b010 #b00) (fp #b1 #b101 #b00) (fp #b1+-- #b011 #b01))@ is 0.75, Z3 says 3). Scripts for Z3 compute the product and+-- the sum in a format wide enough for both to be exact (exponent width+-- @eb + 2@, significand width @2^(eb+1) + 2 sb@), then round once.+expandFma :: Expr -> Expr+expandFma (App op args0) = case (op, args) of+ (FPFma, [rm, a, b, c])+ | FPSort eb sb <- sortOfExpr a+ , eb <= 5 ->+ let (eb', sb') = (eb + 2, 2 ^ (eb + 1) + 2 * sb)+ widen x = App (ToFP eb' sb') [App (RMConst F.RNE) [], x]+ -- Both are exact; the rounding mode of the sum only decides the+ -- sign of a zero sum.+ exact = App FPAdd [rm, App FPMul [App (RMConst F.RNE) [], widen a, widen b], widen c]+ in App (ToFP eb sb) [rm, exact]+ _ -> App op args+ where+ args = map expandFma args0++-- | Replace (dis)equalities between arrays whose index sort has at most 256+-- elements (written as literals) by pointwise comparisons.+expandArrayEqs :: Expr -> Expr+expandArrayEqs (App op args0) = case (op, args) of+ (Eq, a : _ : _) | Just ks <- indicesOf a -> App And [pointwise ks x y | (x, y) <- zip args (drop 1 args)]+ (Distinct, a : _ : _)+ | Just ks <- indicesOf a ->+ App And [App Not [pointwise ks x y] | (i, x) <- zip [0 :: Int ..] args, y <- drop (i + 1) args]+ _ -> App op args+ where+ args = map expandArrayEqs args0+ pointwise ks x y = App And [expandArrayEqs (App Eq [App Select [x, k], App Select [y, k]]) | k <- ks]+ indicesOf a = case sortOfExpr a of+ ArraySort idx _ | Just ks <- literals idx, length ks <= 256 -> Just ks+ _ -> Nothing+ -- Literals of Booleans, bit-vectors of at most 8 bits and records of+ -- those.+ literals = \case+ BoolSort -> Just [constant (BoolConst b) | b <- [False, True]]+ BVSort w | w <= 8 -> Just [constant (BVConst w v) | v <- [0 .. 2 ^ w - 1]]+ RecordSort fs -> map (App (RecordMk (map fst fs))) . sequence <$> traverse (literals . snd) fs+ _ -> Nothing++-------------------------------------------------------------------------------+-- Regressions++-- | The text of a regression file: the script with Z3's answers.+regressionText :: Text -> [Command] -> [Answer] -> Text+regressionText why cmds expected =+ T.unlines (map ("; " <>) (T.lines why))+ <> "; expected: "+ <> T.unwords (map renderAnswer expected)+ <> "\n"+ <> renderScript cmds
+ test-diff/Differential/Z3.hs view
@@ -0,0 +1,56 @@+-- | Running Z3 as an external process.+module Differential.Z3+ ( Z3 (..)+ , findZ3+ , runZ3+ ) where++import Control.Exception (IOException, try)+import qualified Data.Text as T+import System.Directory (findExecutable)+import System.Environment (lookupEnv)+import System.Exit (ExitCode (..))+import System.Process (proc, readCreateProcessWithExitCode)+import System.Timeout (timeout)++import HSMT.SMTLib.Syntax++data Z3 = Z3+ { z3Path :: FilePath+ , z3TimeoutSecs :: Int+ , z3Options :: [String]+ -- ^ Extra @param=value@ settings.+ }++-- | Locate Z3 through @HSMT_Z3@ or the @PATH@.+findZ3 :: IO (Maybe FilePath)+findZ3 =+ lookupEnv "HSMT_Z3" >>= \case+ Just p | not (null p) -> pure (Just p)+ _ -> findExecutable "z3"++-- | Run a script and return the answers of its @check-sat@ commands. Z3+-- errors (including rejected input) are reported as 'Left'; a timeout+-- yields 'AnsUnknown' answers.+runZ3 :: Z3 -> T.Text -> IO (Either T.Text [Answer])+runZ3 z3 script = do+ let args = ["-in", "-smt2", "-T:" <> show (z3TimeoutSecs z3)] <> z3Options z3+ run = readCreateProcessWithExitCode (proc (z3Path z3) args) (T.unpack script)+ r <- timeout ((z3TimeoutSecs z3 + 5) * 1000000) (try run)+ pure $ case r of+ Nothing -> Right [AnsUnknown]+ Just (Left (e :: IOException)) -> Left ("cannot run z3: " <> T.pack (show e))+ Just (Right (code, out, err)) -> do+ let ls = filter (not . T.null) (map T.strip (T.lines (T.pack out)))+ errors = filter ("(error" `T.isPrefixOf`) ls+ case (errors, code) of+ (e : _, _) -> Left e+ ([], ExitFailure _) | not (null err) -> Left (T.pack err)+ _ -> traverse answer ls+ where+ answer = \case+ "sat" -> Right AnsSat+ "unsat" -> Right AnsUnsat+ "unknown" -> Right AnsUnknown+ "timeout" -> Right AnsUnknown+ other -> Left ("unexpected z3 output: " <> other)
+ test-diff/Main.hs view
@@ -0,0 +1,159 @@+-- | Differential tests of hsmt against Z3 (see section 7.1 of PLANO.md).+--+-- Z3 is located through @HSMT_Z3@ or the @PATH@; without it the suite is+-- skipped. Every divergence is shrunk and saved to @test/regressions@, which+-- the regular test suite replays without Z3.+module Main (main) where++import Data.Bits (xor)+import Data.Char (ord)+import Data.List (isPrefixOf)+import qualified Data.Text as T+import qualified Data.Text.IO as T+import Numeric (showHex)+import System.Directory (createDirectoryIfMissing)+import System.Environment (getArgs)+import System.FilePath ((</>))+import Test.QuickCheck+import Test.QuickCheck.Monadic (monadicIO, run)+import Test.Tasty+import Test.Tasty.QuickCheck++import qualified Data.Map.Strict as Map+import HSMT.Core.Sort+import HSMT.Gen.Expr+import HSMT.SMTLib.Printer++import Differential.Oracle+import Differential.Z3++main :: IO ()+main = do+ args <- getArgs+ findZ3 >>= \case+ Nothing -> do+ putStrLn "z3 not found (set HSMT_Z3 or add it to PATH): differential tests skipped"+ defaultMain (testGroup "differential (skipped: z3 not found)" [])+ Just path -> do+ let z3 = Z3 path 10 []+ -- About 1000 cases per property unless given on the command line.+ sized'+ | any ("--quickcheck-tests" `isPrefixOf`) args = id+ | otherwise = localOption (QuickCheckTests 1000)+ defaultMain . sized' $+ testGroup+ "differential vs Z3"+ [ testProperty "evaluator agrees with Z3 on ground terms" (prop_groundTerms z3 groundConfig)+ , testProperty "evaluator agrees with Z3 on floating-point ground terms" (prop_groundTerms z3 fpGroundConfig)+ , testProperty "QF_UF: results and models agree" (prop_problems z3 eufConfig)+ , testProperty "QF_UF: incremental sequences agree" (prop_incremental z3 eufConfig)+ , testProperty "QF_LIA: results and models agree" (prop_problems z3 liaConfig)+ , testProperty "QF_UFLIA: results and models agree" (prop_problems z3 ufliaConfig)+ , testProperty "QF_UFLIA: incremental sequences agree" (prop_incremental z3 ufliaConfig)+ , testProperty "QF_BV: results and models agree" (prop_problems z3 bvConfig)+ , testProperty "QF_UFBV: results and models agree" (prop_problems z3 ufbvConfig)+ , testProperty "QF_UFBV: incremental sequences agree" (prop_incremental z3 ufbvConfig)+ , testProperty "QF_AUF: results and models agree" (prop_problems z3 axConfig)+ , testProperty "QF_AUF: incremental sequences agree" (prop_incremental z3 axConfig)+ , testProperty "QF_ALIA: results and models agree" (prop_problems z3 aliaConfig)+ , testProperty "QF_ABV: results and models agree" (prop_problems z3 abvConfig)+ , testProperty "QF_ABV: incremental sequences agree" (prop_incremental z3 abvConfig)+ , testProperty "records over UF: results and models agree" (prop_problems z3 recordConfig)+ , testProperty "records over UF: incremental sequences agree" (prop_incremental z3 recordConfig)+ , testProperty "records with LIA, BV and arrays: results and models agree" (prop_problems z3 recordMixConfig)+ , testProperty "records with LIA, BV and arrays: incremental sequences agree" (prop_incremental z3 recordMixConfig)+ , testProperty "QF_S: results and models agree" (prop_problems z3 stringConfig)+ , testProperty "QF_S: incremental sequences agree" (prop_incremental z3 stringConfig)+ , testProperty "QF_SLIA: results and models agree" (prop_problems z3 sliaConfig)+ , testProperty "QF_SLIA: incremental sequences agree" (prop_incremental z3 sliaConfig)+ , testProperty "QF_S with regular expressions: results and models agree" (prop_problems z3 regexConfig)+ , testProperty "QF_S with regular expressions: incremental sequences agree" (prop_incremental z3 regexConfig)+ , testProperty "QF_SLIA with regular expressions: results and models agree" (prop_problems z3 sliaRegexConfig)+ , testProperty "QF_SLIA with regular expressions: incremental sequences agree" (prop_incremental z3 sliaRegexConfig)+ , testProperty "QF_FP: results and models agree" (prop_problems z3 fpConfig)+ , testProperty "QF_FP: incremental sequences agree" (prop_incremental z3 fpConfig)+ , testProperty "QF_UFBVFP: results and models agree" (prop_problems z3 fpMixConfig)+ , testProperty "QF_UFBVFP: incremental sequences agree" (prop_incremental z3 fpMixConfig)+ , testProperty "API, engine and Z3 backend: QF_UFLIA" (prop_backends z3 ufliaConfig)+ , testProperty "API, engine and Z3 backend: QF_AUFBV and records" (prop_backends z3 recordMixConfig)+ , testProperty "API, engine and Z3 backend: QF_SLIA with regular expressions" (prop_backends z3 sliaRegexConfig)+ , testProperty "API, engine and Z3 backend: QF_UFBVFP" (prop_backends z3 fpMixConfig)+ , testProperty "API, engine and Z3 backend: every theory" (prop_backends z3 allTheoriesConfig)+ ]++-- | Turn an outcome into a property; divergences are saved as regressions.+judge :: Outcome -> Property+judge = \case+ Agree what -> label (T.unpack what) True+ Skip why -> label ("skipped: " <> T.unpack why) True+ Mismatch why cmds expected ->+ whenFail (saveRegression (regressionText why cmds expected)) $+ counterexample (T.unpack why) False++-- | Check a case, confirming divergences with a second Z3 configuration.+check :: Z3 -> IO Outcome -> Property+check z3 act = monadicIO (judge <$> run (act >>= confirmMismatch z3))++prop_problems :: Z3 -> GenConfig -> Property+prop_problems z3 cfg =+ forAllShrinkBlind (genProblem cfg) shrinkProblem $ \as ->+ counterexample (T.unpack (renderScript (problemScript as))) $+ check z3 (checkProblem z3 as)++prop_incremental :: Z3 -> GenConfig -> Property+prop_incremental z3 cfg =+ forAllShrinkBlind (genSteps cfg) shrinkSteps $ \steps ->+ counterexample (T.unpack (renderScript (stepsScript steps))) $+ check z3 (checkSteps z3 steps)++-- | The same sequence through the API with the engine and with Z3 as+-- external backend.+prop_backends :: Z3 -> GenConfig -> Property+prop_backends z3 cfg =+ forAllShrinkBlind (genSteps cfg) shrinkSteps $ \steps ->+ counterexample (T.unpack (renderScript (stepsScript steps))) $+ check z3 (checkBackends z3 steps)++-- | Ground terms over every theory: no symbols, only literals and+-- operators. Integer division only takes non-zero literal divisors, whose+-- semantics is fully specified by SMT-LIB.+prop_groundTerms :: Z3 -> GenConfig -> Property+prop_groundTerms z3 cfg =+ forAllShrinkBlind gen shrinkExpr $ \t ->+ counterexample (T.unpack (renderExpr t)) $+ check z3 (checkGroundTerm z3 t)+ where+ gen = do+ s <- elements (BoolSort : gcSorts cfg)+ d <- chooseInt (1, 4)+ genTerm cfg (Signature Map.empty []) d s++-- | Every theory, without uninterpreted sorts.+groundConfig :: GenConfig+groundConfig = allTheoriesConfig {gcSorts = filter (not . uninterp) (gcSorts allTheoriesConfig)}+ where+ uninterp = \case+ UninterpretedSort _ -> True+ _ -> False++-- | Floating point in several formats (including Float32), with+-- bit-vectors for the conversions.+fpGroundConfig :: GenConfig+fpGroundConfig =+ fpMixConfig+ { gcSorts = [FPSort 3 3, FPSort 3 5, FPSort 4 2, FPSort 5 11, FPSort 8 24, RoundingModeSort, BVSort 4, BVSort 8, BVSort 16]+ , gcDepth = 4+ , gcFunctions = False+ }++-- | Save a regression under a name derived from its contents.+saveRegression :: T.Text -> IO ()+saveRegression txt = do+ let dir = "test" </> "regressions"+ file = dir </> ("diff-" <> showHex (fnv1a txt) "" <> ".smt2")+ createDirectoryIfMissing True dir+ T.writeFile file txt+ putStrLn ("regression saved to " <> file)++fnv1a :: T.Text -> Word+fnv1a = T.foldl' (\h c -> (h `xor` fromIntegral (ord c)) * 1099511628211) 14695981039346656037
+ test/HSMT/APISpec.hs view
@@ -0,0 +1,205 @@+{-# LANGUAGE OverloadedLabels #-}++module HSMT.APISpec (tests, testsWith) where++import Control.Exception (try)+import qualified Data.Text as T+import Test.Tasty+import Test.Tasty.HUnit hiding (assert)++import HSMT++type Person = 'RecordS '[ '("name", 'StringS), '("age", 'IntS)]++type Point = 'RecordS '[ '("x", 'IntS), '("y", 'IntS)]++isSat :: Result ctx -> Bool+isSat = \case Sat _ -> True; _ -> False++isUnknown :: Result ctx -> Bool+isUnknown = \case Unknown _ -> True; _ -> False++isUnsat :: Result ctx -> Bool+isUnsat = \case Unsat _ -> True; _ -> False++tests :: TestTree+tests = testsWith defaultConfig++-- | The tests with the given configuration (and its backend).+testsWith :: Config -> TestTree+testsWith base =+ testGroup+ "API"+ [ testCase "propositional sat with model" $ do+ r <- runSMT base $ do+ p <- declare @'BoolS "p"+ q <- declare @'BoolS "q"+ assert (p .|| q)+ assert (notB p)+ checkSat >>= \case+ Sat m -> pure (Just (eval m p, eval m q))+ _ -> pure Nothing+ r @?= Just (False, True)+ , testCase "propositional unsat" $ do+ r <- runSMT base $ do+ p <- declare @'BoolS "p"+ q <- declare @'BoolS "q"+ assert (p .=> q)+ assert p+ assert (notB q)+ isUnsat <$> checkSat+ r @?= True+ , testCase "Boolean equalities, xor and ite" $ do+ r <- runSMT base $ do+ a <- declare @'BoolS "a"+ b <- declare @'BoolS "b"+ c <- declare @'BoolS "c"+ assert (a `xorB` b)+ assert (ite a (b .== c) (notB c))+ assert (distinct [a, c])+ checkSat >>= \case+ Sat m -> pure (Just (map (eval m) [a, b, c]))+ _ -> pure Nothing+ r @?= Just [True, False, False]+ , testCase "push and pop" $ do+ (r1, r2, r3) <- runSMT base $ do+ p <- declare @'BoolS "p"+ assert p+ push+ assert (notB p)+ r1 <- checkSat+ pop+ r2 <- checkSat+ r3 <- scoped (assert (p .&& notB p) >> checkSat)+ pure (isUnsat r1, isSat r2, isUnsat r3)+ (r1, r2, r3) @?= (True, True, True)+ , testCase "duplicate declarations are rejected" $ do+ r <- try $ runSMT base $ do+ _ <- declare @'BoolS "p"+ _ <- declare @'IntS "p"+ pure ()+ case r of+ Left (DuplicateDeclaration "p") -> pure ()+ other -> assertFailure ("unexpected: " <> show other)+ , testCase "nonlinear arithmetic: unknown with the engine" $ do+ r <- runSMT base $ do+ x <- declare @'IntS "x"+ y <- declare @'IntS "y"+ assert (x * y .== 6)+ -- External solvers may decide it.+ (if cfgBackend base == Native then isUnknown else isSat) <$> checkSat+ r @?= True+ , testCase "strings" $ do+ r <- runSMT base $ do+ s <- declare @'StringS "s"+ n <- declare @'IntS "n"+ assert (strLen s .== 5)+ assert (prefixOf "ab" s)+ assert (strToInt (substr s 2 3) .== n)+ assert (n .> 900)+ m <-+ checkSat >>= \case+ Sat m -> pure (Just (T.take 2 (eval m s), eval m n > 900))+ _ -> pure Nothing+ assert (indexOf s "9" 0 .== (-1))+ (,) m . isUnsat <$> checkSat+ r @?= (Just ("ab", True), True)+ , testCase "linear integer arithmetic" $ do+ r <- runSMT base $ do+ x <- declare @'IntS "x"+ y <- declare @'IntS "y"+ assert (x + 1 .> 3)+ assert (x .< 5)+ v <-+ checkSat >>= \case+ Sat m -> pure (Just (eval m x))+ _ -> pure Nothing+ assert (2 * x .== 2 * y + 1)+ parity <- isUnsat <$> checkSat+ pure (v, parity)+ fmap (`elem` [3, 4]) (fst r) @?= Just True+ snd r @?= True+ , testCase "arrays" $ do+ r <- runSMT base $ do+ a <- declare @('ArrayS 'IntS 'IntS) "a"+ b <- declare @('ArrayS 'IntS 'IntS) "b"+ i <- declare @'IntS "i"+ assert (b .== store a i 7)+ assert (select a i .== 3)+ assert (distinct [select b 0, select a 0])+ m <-+ checkSat >>= \case+ Sat m -> pure (Just (eval m i, eval m (select b i), eval m (select a i)))+ _ -> pure Nothing+ -- b differs from a only at i, so b[0] /= a[0] forces i = 0.+ assert (i .> 0)+ (,) m . isUnsat <$> checkSat+ r @?= (Just (0, 7, 3), True)+ , testCase "records" $ do+ r <- runSMT base $ do+ p <- declare @Point "p"+ q <- declare @Point "q"+ assert (p ! #x .> 2)+ assert (q .== setField #y (p ! #x + 1) p)+ assert (q ! #y .< 5)+ m <-+ checkSat >>= \case+ Sat m -> pure (Just (eval m (p ! #x), eval m (q ! #y), field #x (eval m q)))+ _ -> pure Nothing+ assert (p .== record (#x := 4 :& #y := 0 :& FNil))+ (,) m . isUnsat <$> checkSat+ r @?= (Just (3, 4, 3), True)+ , testCase "models evaluate expressions of every theory" $ do+ r <- runSMT base $ do+ p <- declare @'BoolS "p"+ assert p+ checkSat >>= \case+ Sat m -> do+ let person = record (#name := "Ana" :& #age := 30 :& FNil) :: Expr ctx Person+ older = setField #age (person ! #age + 1) person+ arr = store (constArray @'IntS (bv @8 0)) 3 (bv 200)+ pure $+ Just+ ( eval m (2 * 3 - 10 `idiv` 3 :: Expr ctx 'IntS)+ , eval m (bvExtract @7 @4 (bv @8 0xA5))+ , eval m (strLen ("ab" <+> "cde"))+ , eval m (select arr 3 + bv 100)+ , eval m (older ! #age)+ , field #name (eval m older)+ )+ _ -> pure Nothing+ r @?= Just (3, BitVector 0xA, 5, BitVector 44, 31, "Ana")+ , testCase "floating point" $ do+ r <- runSMT base $ do+ x <- declare @Float32S "x"+ y <- declare @Float32S "y"+ assert (fpEq (fpAdd rne x y) (fpValue 1))+ assert (fpGt x (fpValue 0.75) .&& fpGt y (fpValue 0.125))+ sums <-+ checkSat >>= \case+ Sat m -> pure (Just (toFloat (eval m x) + toFloat (eval m y) == 1, toFloat (eval m x) > 0.75))+ _ -> pure Nothing+ -- Addition is not associative in Float16.+ a <- declare @Float16S "a"+ b <- declare @Float16S "b"+ c <- declare @Float16S "c"+ let lhs = fpAdd rne (fpAdd rne a b) c+ rhs = fpAdd rne a (fpAdd rne b c)+ nonAssoc <- scoped $ do+ assert (notB (fpEq lhs rhs) .&& notB (fpIsNaN lhs) .&& notB (fpIsNaN rhs))+ checkSat >>= \case+ Sat m -> pure (eval m lhs /= eval m rhs)+ _ -> pure False+ -- A square is never negative.+ square <- scoped (assert (fpLt (fpMul rne x x) (fpZero False)) >> isUnsat <$> checkSat)+ pure (sums, nonAssoc, square)+ r @?= (Just (True, True), True, True)+ , testCase "uninterpreted functions are declared with their domain" $ do+ r <- runSMT base $ do+ f <- declareFun @'[ 'IntS, 'BoolS] @'BoolS "f"+ x <- declare @'IntS "x"+ p <- declare @'BoolS "p"+ assert (f x p .|| notB (f x p))+ isSat <$> checkSat+ r @?= True+ ]
+ test/HSMT/ArraySpec.hs view
@@ -0,0 +1,107 @@+module HSMT.ArraySpec (tests) where++import Data.Text (Text)+import qualified Data.Text as T+import Test.Tasty+import Test.Tasty.HUnit++import HSMT.SMT.Engine+import HSMT.SMTLib.Run++tests :: TestTree+tests =+ testGroup+ "Arrays"+ [ testCase "read over write" $ do+ let base =+ [ "(declare-fun a () (Array Int Int))"+ , "(declare-fun i () Int)"+ , "(declare-fun j () Int)"+ ]+ expect (base <> ["(assert (not (= (select (store a i 5) i) 5)))"]) ["unsat"]+ expect+ (base <> ["(assert (not (= (select (store a i 5) j) (select a j))))", "(check-sat)", "(assert (distinct i j))"])+ ["sat", "unsat"]+ , testCase "extensionality" $ do+ let base =+ [ "(declare-fun a () (Array Int Int))"+ , "(declare-fun b () (Array Int Int))"+ , "(declare-fun i () Int)"+ , "(declare-fun j () Int)"+ ]+ -- Writing back the value read leaves the array unchanged.+ expect (base <> ["(assert (distinct a (store a i (select a i))))"]) ["unsat"]+ -- Stores at different indices commute.+ expect+ (base <> ["(assert (distinct (store (store a i 1) j 2) (store (store a j 2) i 1)))", "(check-sat)", "(assert (distinct i j))"])+ ["sat", "unsat"]+ expect (base <> ["(assert (distinct a b))", "(check-sat)", "(assert (= (select a i) (select b i)))"]) ["sat", "sat"]+ , testCase "constant arrays" $ do+ let k v = "((as const (Array Int Int)) " <> v <> ")"+ expect ["(assert (= " <> k "0" <> " (store " <> k "1" <> " 3 0)))"] ["unsat"]+ expect ["(assert (distinct " <> k "0" <> " (store " <> k "0" <> " 3 0)))"] ["unsat"]+ expect+ [ "(declare-fun x () Int)"+ , "(assert (= (store " <> k "x" <> " 1 2) (store " <> k "3" <> " 1 2)))"+ , "(check-sat)"+ , "(assert (distinct x 3))"+ ]+ ["sat", "unsat"]+ , testCase "finite index sorts" $ do+ -- Only four arrays from Bool to Bool exist.+ let arrays n = ["(declare-fun a" <> tshow i <> " () (Array Bool Bool))" | i <- [1 .. n]]+ names n = T.unwords ["a" <> tshow i | i <- [1 .. n :: Int]]+ expect (arrays 4 <> ["(assert (distinct " <> names 4 <> "))"]) ["sat"]+ expect (arrays 5 <> ["(assert (distinct " <> names 5 <> "))"]) ["unsat"]+ -- Overwriting every index changes the default.+ let k v = "((as const (Array (_ BitVec 2) Bool)) " <> v <> ")"+ full = "(store (store (store (store " <> k "false" <> " #b00 true) #b01 true) #b10 true) #b11 true)"+ expect ["(assert (= " <> full <> " " <> k "true" <> "))"] ["sat"]+ expect ["(assert (= (store " <> k "false" <> " #b10 true) (store " <> k "true" <> " #b01 false)))"] ["unsat"]+ , testCase "uninterpreted functions over arrays" $ do+ let base =+ [ "(declare-sort U 0)"+ , "(declare-fun a () (Array U U))"+ , "(declare-fun b () (Array U U))"+ , "(declare-fun i () U)"+ , "(declare-fun f ((Array U U)) U)"+ ]+ expect (base <> ["(assert (= a (store b i (select b i))))", "(assert (distinct (f a) (f b)))"]) ["unsat"]+ -- f distinguishes a and b, so they must differ somewhere.+ expect (base <> ["(assert (distinct (f a) (f b)))", "(assert (= (select a i) (select b i)))"]) ["sat"]+ , testCase "nested arrays" $ do+ let base =+ [ "(declare-fun m () (Array Int (Array Int Int)))"+ , "(declare-fun i () Int)"+ , "(declare-fun j () Int)"+ ]+ expect+ (base <> ["(assert (not (= (select (select (store m i (store (select m i) j 7)) i) j) 7)))"])+ ["unsat"]+ expect (base <> ["(assert (distinct (select m i) (select m j)))", "(check-sat)", "(assert (= i j))"]) ["sat", "unsat"]+ , testCase "arrays of bit-vectors" $ do+ let base =+ [ "(declare-fun a () (Array (_ BitVec 8) (_ BitVec 8)))"+ , "(declare-fun i () (_ BitVec 8))"+ ]+ expect+ (base <> ["(assert (= (bvadd (select a i) #x01) (select (store a (bvadd i #x01) #x00) i)))"])+ ["unsat"]+ expect (base <> ["(assert (bvult (select a i) (select a (bvadd i #x00))))"]) ["unsat"]+ ]++tshow :: Int -> Text+tshow = T.pack . show++-- | Run a script (with model validation) and compare its answers; a final+-- @check-sat@ is appended.+expect :: [Text] -> [Text] -> Assertion+expect cmds answers =+ runScriptText True (T.unlines (cmds <> ["(check-sat)"])) >>= \case+ Left err -> assertFailure (T.unpack err)+ Right rs -> map answer rs @?= answers+ where+ answer = \case+ ESat _ -> "sat"+ EUnsat _ -> "unsat"+ EUnknown why -> "unknown: " <> why
+ test/HSMT/BVSpec.hs view
@@ -0,0 +1,97 @@+module HSMT.BVSpec (tests) where++import Data.Text (Text)+import Test.QuickCheck+import Test.QuickCheck.Monadic (monadicIO, run)+import qualified Test.QuickCheck.Monadic as QC+import Test.Tasty+import Test.Tasty.HUnit+import Test.Tasty.QuickCheck (testProperty)++import HSMT.Core.Eval+import HSMT.Core.Expr+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Value+import HSMT.SMT.Engine++tests :: TestTree+tests =+ testGroup+ "Bit-vectors"+ [ testCase "modular arithmetic" $ do+ r1 <- solve [eq (App BVMul [x, lit 8 3]) (lit 8 15)]+ r1 @?= "sat"+ -- 2x is even, 15 is odd.+ r2 <- solve [eq (App BVMul [x, lit 8 2]) (lit 8 15)]+ r2 @?= "unsat"+ r3 <- solve [App BVULt [x, lit 8 0]]+ r3 @?= "unsat"+ , testCase "division by zero follows SMT-LIB" $ do+ r <- solve [App Not [eq (App BVUDiv [x, lit 8 0]) (lit 8 255)]]+ r @?= "unsat"+ r' <- solve [App Not [eq (App BVURem [x, lit 8 0]) x]]+ r' @?= "unsat"+ , testCase "congruence meets bit-vectors" $ do+ let f t = App (Uninterpreted (Symbol "f" [BVSort 8] (BVSort 8))) [t]+ r1 <- solve [eq x (App BVAdd [y, lit 8 1]), App Not [eq (f (App BVSub [x, lit 8 1])) (f y)]]+ r1 @?= "unsat"+ -- f maps three different arguments to three values, but x is 0 or 1.+ r2 <- solve [App Distinct [f (lit 8 0), f (lit 8 1), f x], App BVULe [x, lit 8 1]]+ r2 @?= "unsat"+ r3 <- solve [App Distinct [f (lit 8 0), f (lit 8 1), f x]]+ r3 @?= "sat"+ , testProperty "every operator agrees with the evaluator" prop_operators+ ]+ where+ x = var "x" 8+ y = var "y" 8++var :: Text -> Int -> Expr+var n w = constant (Uninterpreted (Symbol n [] (BVSort w)))++lit :: Int -> Integer -> Expr+lit w v = constant (BVConst w v)++eq :: Expr -> Expr -> Expr+eq a b = App Eq [a, b]++solve :: [Expr] -> IO String+solve as =+ solveAssertions True as >>= \case+ ESat _ -> pure "sat"+ EUnsat _ -> pure "unsat"+ EUnknown why -> pure ("unknown: " <> show why)++-- | For random operands, the circuit of each operator must produce exactly+-- the value computed by the reference evaluator. The operands are+-- variables fixed by equalities, so the circuits are not constant-folded.+prop_operators :: Property+prop_operators = forAll gen $ \(op, w, vals) -> monadicIO $ do+ let names = ["a", "b"]+ args = [var n w | n <- take (length vals) names]+ fixes = [eq a (lit w v) | (a, v) <- zip args vals]+ term = App op args+ expected = either (error . show) id (evalExpr emptyInterpretation (App op [lit w v | v <- vals]))+ valueTerm = case expected of+ VBV w' v -> lit w' v+ VBool b -> constant (BoolConst b)+ other -> error (show other)+ agrees <- run (solve (fixes <> [eq term valueTerm]))+ differs <- run (solve (fixes <> [App Not [eq term valueTerm]]))+ QC.monitor (counterexample (show (op, w, vals, expected, agrees, differs)))+ QC.assert (agrees == "sat" && differs == "unsat")+ where+ gen = do+ w <- elements [1, 2, 3, 4, 5, 8]+ (op, arity) <-+ elements $+ [(o, 2) | o <- binary]+ <> [(o, 1) | o <- [BVNot, BVNeg, BVZeroExtend 2, BVSignExtend 3]]+ <> [(BVExtract (w - 1) 0, 1), (BVExtract (w - 1) (w - 1), 1), (BVConcat, 2)]+ vals <- vectorOf arity (frequency [(1, elements [0, 2 ^ w - 1, 2 ^ (w - 1)]), (3, chooseInteger (0, 2 ^ w - 1))])+ pure (op, w, vals)+ binary =+ [ BVAnd, BVOr, BVXor, BVAdd, BVSub, BVMul, BVUDiv, BVURem, BVSDiv, BVSRem, BVSMod+ , BVShl, BVLShr, BVAShr, BVULt, BVULe, BVUGt, BVUGe, BVSLt, BVSLe, BVSGt, BVSGe+ ]
+ test/HSMT/EUFSpec.hs view
@@ -0,0 +1,325 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE ExplicitNamespaces #-}+module HSMT.EUFSpec (tests) where++import Control.Monad (forM_)+import Data.List (nub, zip4)+import qualified Data.Text as T+import qualified Data.Map.Strict as Map+import Test.QuickCheck.Monadic (monadicIO, run)+import qualified Test.QuickCheck.Monadic as QC+import Test.Tasty+import Test.Tasty.HUnit hiding (assert)+import Test.Tasty.QuickCheck++import GHC.TypeLits (KnownNat, type (<=))++import HSMT++type U = 'UninterpS "U"++isSat, isUnsat :: Result ctx -> Bool+isSat = \case Sat _ -> True; _ -> False+isUnsat = \case Unsat _ -> True; _ -> False++checkUnsat :: (forall ctx. SMT ctx ()) -> Assertion+checkUnsat setup = do+ r <- runSMT defaultConfig (setup >> checkSat >>= pure . describe)+ r @?= "unsat"++checkSatisfiable :: (forall ctx. SMT ctx ()) -> Assertion+checkSatisfiable setup = do+ r <- runSMT defaultConfig (setup >> checkSat >>= pure . describe)+ r @?= "sat"++describe :: Result ctx -> String+describe = \case+ Sat _ -> "sat"+ Unsat _ -> "unsat"+ Unknown why -> "unknown: " <> show why++-------------------------------------------------------------------------------+-- Random ground formulas with a brute-force oracle++-- | Terms over constants a, b, c, the literals 0 and 1, and a unary f.+data T = A | B | C | Lit Integer | F T+ deriving (Eq, Ord, Show)++data Fm = EqT T T | NotF Fm | AndF Fm Fm | OrF Fm Fm+ deriving (Show)++genT :: Bool -> Gen T+genT withLits = sized (\n -> go (min 3 n))+ where+ leaves = [A, B, C] ++ (if withLits then [Lit 0, Lit 1] else [])+ go 0 = elements leaves+ go d = frequency [(3, elements leaves), (2, F <$> go (d - 1))]++-- | A conjunction of small clauses over equalities and disequalities, which+-- yields a good mix of satisfiable and unsatisfiable problems.+genFm :: Bool -> Gen Fm+genFm withLits = do+ n <- chooseInt (2, 7)+ clauses <- vectorOf n clause+ pure (foldr1 AndF clauses)+ where+ atom = do+ e <- EqT <$> genT withLits <*> genT withLits+ positive <- frequency [(2, pure True), (1, pure False)]+ pure (if positive then e else NotF e)+ clause = do+ k <- frequency [(3, pure 1), (2, pure 2)]+ foldr1 OrF <$> vectorOf k atom++-- | Formulas with few distinct terms, so that enumerating partitions (Bell+-- numbers) stays cheap.+smallFm :: Bool -> Gen Fm+smallFm withLits = genFm withLits `suchThat` ((<= 8) . length . termsOf)++subtermsOf :: T -> [T]+subtermsOf t = t : case t of+ F u -> subtermsOf u+ _ -> []++termsOf :: Fm -> [T]+termsOf = nub . concatMap subtermsOf . go+ where+ go = \case+ EqT a b -> [a, b]+ NotF f -> go f+ AndF f g -> go f ++ go g+ OrF f g -> go f ++ go g++-- | All partitions of a list, as maps from element to block index.+partitions :: [T] -> [Map.Map T Int]+partitions = go Map.empty 0+ where+ go acc _ [] = [acc]+ go acc nBlocks (x : xs) =+ concat [go (Map.insert x b acc) (max nBlocks (b + 1)) xs | b <- [0 .. nBlocks]]++-- | A partition is a model when it respects congruence and literals, and+-- does not need more values than the sort has.+consistent :: Maybe Int -> [T] -> Map.Map T Int -> Bool+consistent card ts p = congruent && literalsDistinct && fits+ where+ fits = maybe True (\k -> length (nub (Map.elems p)) <= k) card+ same x y = p Map.! x == p Map.! y+ congruent = and [same (F x) (F y) | F x <- ts, F y <- ts, same x y]+ literalsDistinct = and [not (same x y) | x@(Lit i) <- ts, y@(Lit j) <- ts, i /= j]++holds :: Map.Map T Int -> Fm -> Bool+holds p = \case+ EqT a b -> p Map.! a == p Map.! b+ NotF f -> not (holds p f)+ AndF f g -> holds p f && holds p g+ OrF f g -> holds p f || holds p g++bruteForceSat :: Maybe Int -> Fm -> Bool+bruteForceSat card f =+ let ts = termsOf f+ in any (\p -> consistent card ts p && holds p f) (partitions ts)++prop_eufAgreesWithBruteForce :: Property+prop_eufAgreesWithBruteForce = forAll (smallFm False) $ \fm -> monadicIO $ do+ r <- run (solveU fm)+ let expected = bruteForceSat Nothing fm+ QC.monitor (cover 20 expected "sat" . cover 10 (not expected) "unsat")+ QC.monitor (cover 20 (length (termsOf fm) >= 5) "at least 5 terms")+ QC.assert (r == if expected then "sat" else "unsat")+ where+ solveU fm = runSMT defaultConfig $ do+ a <- declare @U "a"+ b <- declare @U "b"+ c <- declare @U "c"+ f <- declareFun @'[U] @U "f"+ let term = \case+ A -> a+ B -> b+ C -> c+ F t -> f (term t)+ Lit _ -> error "no literals in U"+ assert (toFormula term fm)+ describe <$> checkSat++prop_eufWithLiterals :: Property+prop_eufWithLiterals = forAll (smallFm True) $ \fm -> monadicIO $ do+ r <- run (solveInt fm)+ let expected = bruteForceSat Nothing fm+ QC.monitor (cover 20 expected "sat" . cover 10 (not expected) "unsat")+ QC.monitor (cover 20 (length (termsOf fm) >= 5) "at least 5 terms")+ QC.assert (r == if expected then "sat" else "unsat")+ where+ solveInt fm = runSMT defaultConfig $ do+ a <- declare @'IntS "a"+ b <- declare @'IntS "b"+ c <- declare @'IntS "c"+ f <- declareFun @'[ 'IntS] @'IntS "f"+ let term = \case+ A -> a+ B -> b+ C -> c+ Lit n -> int n+ F t -> f (term t)+ assert (toFormula term fm)+ describe <$> checkSat++-- | Finite sorts: bit-vectors of width 1 and 2, with literals 0 and 1.+prop_eufFiniteSort :: Int -> Property+prop_eufFiniteSort width = forAll (smallFm True) $ \fm -> monadicIO $ do+ r <- run (if width == 1 then solveBV @1 fm else solveBV @2 fm)+ let expected = bruteForceSat (Just (2 ^ width)) fm+ QC.monitor (cover 20 expected "sat" . cover 10 (not expected) "unsat")+ QC.assert (r == if expected then "sat" else "unsat")++solveBV :: forall w. (KnownNat w, 1 <= w) => Fm -> IO String+solveBV fm = runSMT defaultConfig $ do+ a <- declare @('BVS w) "a"+ b <- declare @('BVS w) "b"+ c <- declare @('BVS w) "c"+ f <- declareFun @'[ 'BVS w] @('BVS w) "f"+ let term = \case+ A -> a+ B -> b+ C -> c+ Lit n -> fromInteger n+ F t -> f (term t)+ assert (toFormula term fm)+ describe <$> checkSat++toFormula :: (T -> Expr ctx s) -> Fm -> Expr ctx 'BoolS+toFormula term = go+ where+ go = \case+ EqT x y -> term x .== term y+ NotF g -> notB (go g)+ AndF g h -> go g .&& go h+ OrF g h -> go g .|| go h++-- | x0 = x1 = ... = xn through either branch of each diamond, and x0 /= xn.+diamonds :: Int -> SMT ctx ()+diamonds n = do+ let v p i = declare @U (T.pack (p <> show i))+ xs <- mapM (v "x") [0 .. n]+ ys <- mapM (v "y") [0 .. n - 1]+ zs <- mapM (v "z") [0 .. n - 1]+ forM_ (zip4 xs (drop 1 xs) ys zs) $ \(xi, xj, yi, zi) ->+ assert ((xi .== yi .&& yi .== xj) .|| (xi .== zi .&& zi .== xj))+ case (xs, reverse xs) of+ (x0 : _, xn : _) -> assert (x0 ./= xn)+ _ -> pure ()++-------------------------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "EUF"+ [ testCase "congruence" $ checkUnsat $ do+ x <- declare @U "x"+ y <- declare @U "y"+ f <- declareFun @'[U] @U "f"+ assert (x .== y)+ assert (f x ./= f y)+ , testCase "transitivity" $ checkUnsat $ do+ x <- declare @U "x"+ y <- declare @U "y"+ z <- declare @U "z"+ assert (x .== y .&& y .== z .&& x ./= z)+ , testCase "f^3(a) = a and f^5(a) = a imply f(a) = a" $ checkUnsat $ do+ a <- declare @U "a"+ f <- declareFun @'[U] @U "f"+ let iter n = foldr (const f) a [1 .. n :: Int]+ assert (iter 3 .== a)+ assert (iter 5 .== a)+ assert (f a ./= a)+ , testCase "binary functions" $ checkUnsat $ do+ a <- declare @U "a"+ b <- declare @U "b"+ g <- declareFun @'[U, U] @U "g"+ assert (g a b .== a)+ assert (g (g a b) b ./= a)+ , testCase "distinct literals" $ checkUnsat $ do+ x <- declare @'IntS "x"+ assert (x .== 1 .&& x .== 2)+ , testCase "functions over literals" $ checkUnsat $ do+ x <- declare @'IntS "x"+ f <- declareFun @'[ 'IntS] @'IntS "f"+ assert (x .== 1 .&& f x .== 2 .&& f 1 .== 3)+ , testCase "string and bit-vector literals" $ do+ checkUnsat $ do+ s <- declare @'StringS "s"+ assert (s .== "a" .&& s .== "b")+ checkUnsat $ do+ v <- declare @('BVS 8) "v"+ assert (v .== 3 .&& v .== 4)+ , testCase "ite over terms" $ checkUnsat $ do+ p <- declare @'BoolS "p"+ a <- declare @U "a"+ b <- declare @U "b"+ y <- declare @U "y"+ assert (y .== ite p a b)+ assert (y ./= a .&& y ./= b)+ , testCase "Boolean-valued functions" $ checkUnsat $ do+ x <- declare @U "x"+ y <- declare @U "y"+ p <- declareFun @'[U] @'BoolS "p"+ assert (p x .&& notB (p y) .&& x .== y)+ , testCase "Boolean arguments" $ checkUnsat $ do+ q <- declare @'BoolS "q"+ g <- declareFun @'[ 'BoolS] @U "g"+ assert (q .&& g true ./= g q)+ , testCase "distinct is satisfiable over an infinite sort" $ checkSatisfiable $ do+ xs <- mapM (\n -> declare @U n) ["a", "b", "c", "d"]+ assert (distinct xs)+ , testCase "a sat model is usable" $ do+ r <- runSMT defaultConfig $ do+ x <- declare @'IntS "x"+ y <- declare @'IntS "y"+ f <- declareFun @'[ 'IntS] @'IntS "f"+ assert (f x .== 7 .&& f y ./= 7 .&& x ./= 5)+ checkSat >>= \case+ Sat m -> pure (Just (eval m (f x), eval m x /= eval m y))+ _ -> pure Nothing+ r @?= Just (7, True)+ , testCase "bit-vector domains are finite" $ do+ checkUnsat $ do+ xs <- mapM (\n -> declare @('BVS 1) n) ["a", "b", "c"]+ assert (distinct xs)+ checkSatisfiable $ do+ xs <- mapM (\n -> declare @('BVS 1) n) ["a", "b"]+ assert (distinct xs)+ -- Pigeonhole through congruence: f maps 2 values to 3 distinct ones.+ checkUnsat $ do+ xs <- mapM (\n -> declare @('BVS 1) n) ["a", "b", "c"]+ f <- declareFun @'[ 'BVS 1] @U "f"+ assert (distinct (map f xs))+ , testCase "the only value left is chosen" $ do+ r <- runSMT defaultConfig $ do+ x <- declare @('BVS 2) "x"+ assert (distinct [x, 0, 1, 2])+ checkSat >>= \case+ Sat m -> pure (Just (eval m x))+ _ -> pure Nothing+ r @?= Just (BitVector 3)+ , testCase "incremental use" $ do+ r <- runSMT defaultConfig $ do+ x <- declare @U "x"+ y <- declare @U "y"+ f <- declareFun @'[U] @U "f"+ assert (f x ./= f y)+ r1 <- isSat <$> checkSat+ r2 <- scoped (assert (x .== y) >> isUnsat <$> checkSat)+ r3 <- isSat <$> checkSat+ pure (r1, r2, r3)+ r @?= (True, True, True)+ , localOption (mkTimeout 30000000) $+ testCase "chains of diamonds (need transitivity lemmas)" $+ -- 110 used to hang when only one branch of a diamond could derive+ -- the shortcut equality.+ mapM_ (\n -> checkUnsat (diamonds n)) [20, 60, 110, 150]+ , testProperty "agrees with brute force (uninterpreted sort)" (checkCoverage (withMaxSuccess 1500 prop_eufAgreesWithBruteForce))+ , testProperty "agrees with brute force (1-bit vectors)" (checkCoverage (withMaxSuccess 1500 (prop_eufFiniteSort 1)))+ , testProperty "agrees with brute force (2-bit vectors)" (checkCoverage (withMaxSuccess 1500 (prop_eufFiniteSort 2)))+ , testProperty "agrees with brute force (integers with literals)" (checkCoverage (withMaxSuccess 1500 prop_eufWithLiterals))+ ]
+ test/HSMT/EvalSpec.hs view
@@ -0,0 +1,143 @@+module HSMT.EvalSpec (tests) where++import Data.Bits (shiftL, shiftR)+import Data.Int (Int8)+import qualified Data.Map.Strict as Map+import Data.Word (Word8)+import Test.Tasty+import Test.Tasty.HUnit+import Test.Tasty.QuickCheck++import HSMT.Core.Eval+import HSMT.Core.Expr+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Typing+import HSMT.Core.Value++ev :: Op -> [Value] -> Value+ev op vs = either (error . show) id (applyOp emptyInterpretation op vs)++bv8 :: Word8 -> Value+bv8 = VBV 8 . fromIntegral++sbv8 :: Int8 -> Value+sbv8 x = VBV 8 (fromIntegral (fromIntegral x :: Word8))++-- | Binary bit-vector operators agree with Haskell's 8-bit arithmetic.+bvAgrees :: Op -> (Word8 -> Word8 -> Word8) -> Word8 -> Word8 -> Property+bvAgrees op f a b = ev op [bv8 a, bv8 b] === bv8 (f a b)++sbvAgrees :: Op -> (Int8 -> Int8 -> Int8) -> Int8 -> Int8 -> Property+sbvAgrees op f a b =+ b /= 0 && not (a == minBound && b == -1) ==> ev op [sbv8 a, sbv8 b] === sbv8 (f a b)++tests :: TestTree+tests =+ testGroup+ "Eval"+ [ testGroup+ "integers"+ [ testProperty "euclidean division" $ \a b ->+ b /= 0 ==>+ case (ev IntDiv [VInt a, VInt b], ev IntMod [VInt a, VInt b]) of+ (VInt q, VInt r) -> a === b * q + r .&&. property (0 <= r && r < abs b)+ other -> counterexample (show other) False+ , testCase "div/mod examples" $ do+ ev IntDiv [VInt (-7), VInt 2] @?= VInt (-4)+ ev IntMod [VInt (-7), VInt 2] @?= VInt 1+ ev IntDiv [VInt 7, VInt (-2)] @?= VInt (-3)+ ev IntMod [VInt 7, VInt (-2)] @?= VInt 1+ , testCase "division by zero is uninterpreted" $ do+ let interp = emptyInterpretation {interpDivByZero = FunInterp (Map.fromList [([VInt 5], VInt 42)]) (VInt 0)}+ applyOp interp IntDiv [VInt 5, VInt 0] @?= Right (VInt 42)+ applyOp interp IntDiv [VInt 6, VInt 0] @?= Right (VInt 0)+ ]+ , testGroup+ "bit-vectors (8 bits)"+ [ testProperty "bvadd" (bvAgrees BVAdd (+))+ , testProperty "bvsub" (bvAgrees BVSub (-))+ , testProperty "bvmul" (bvAgrees BVMul (*))+ , testProperty "bvudiv" (\a b -> b /= 0 ==> bvAgrees BVUDiv div a b)+ , testProperty "bvurem" (\a b -> b /= 0 ==> bvAgrees BVURem mod a b)+ , testProperty "bvsdiv" (sbvAgrees BVSDiv quot)+ , testProperty "bvsrem" (sbvAgrees BVSRem rem)+ , testProperty "bvsmod" (sbvAgrees BVSMod mod)+ , testProperty "bvshl" (\a b -> bvAgrees BVShl (\x y -> if y >= 8 then 0 else x `shiftL` fromIntegral y) a b)+ , testProperty "bvlshr" (\a b -> bvAgrees BVLShr (\x y -> if y >= 8 then 0 else x `shiftR` fromIntegral y) a b)+ , testProperty "bvashr" $ \a b ->+ ev BVAShr [sbv8 a, bv8 b] === sbv8 (a `shiftR` fromIntegral (min 8 b))+ , testProperty "bvslt" $ \a b -> ev BVSLt [sbv8 a, sbv8 b] === VBool (a < b)+ , testCase "division by zero" $ do+ ev BVUDiv [bv8 7, bv8 0] @?= bv8 255+ ev BVURem [bv8 7, bv8 0] @?= bv8 7+ ev BVSDiv [sbv8 (-7), sbv8 0] @?= sbv8 1+ ev BVSDiv [sbv8 7, sbv8 0] @?= sbv8 (-1)+ ev BVSRem [sbv8 (-7), sbv8 0] @?= sbv8 (-7)+ ev BVSMod [sbv8 (-7), sbv8 0] @?= sbv8 (-7)+ , testCase "concat, extract and extensions" $ do+ ev BVConcat [VBV 4 0xA, VBV 4 0x5] @?= VBV 8 0xA5+ ev (BVExtract 7 4) [VBV 8 0xA5] @?= VBV 4 0xA+ ev (BVZeroExtend 4) [VBV 4 0xA] @?= VBV 8 0x0A+ ev (BVSignExtend 4) [VBV 4 0xA] @?= VBV 8 0xFA+ ]+ , testGroup+ "strings"+ [ testCase "substr and at" $ do+ ev StrSubstr [VString "hello", VInt 1, VInt 3] @?= VString "ell"+ ev StrSubstr [VString "hello", VInt 3, VInt 10] @?= VString "lo"+ ev StrSubstr [VString "hello", VInt (-1), VInt 2] @?= VString ""+ ev StrAt [VString "hello", VInt 5] @?= VString ""+ , testCase "indexof" $ do+ ev StrIndexOf [VString "abcabc", VString "c", VInt 3] @?= VInt 5+ ev StrIndexOf [VString "abc", VString "", VInt 3] @?= VInt 3+ ev StrIndexOf [VString "abc", VString "", VInt 4] @?= VInt (-1)+ ev StrIndexOf [VString "abc", VString "d", VInt 0] @?= VInt (-1)+ , testCase "replace" $ do+ ev StrReplace [VString "abab", VString "b", VString "x"] @?= VString "axab"+ ev StrReplace [VString "ab", VString "", VString "x"] @?= VString "xab"+ , testCase "conversions" $ do+ ev StrToInt [VString "0123"] @?= VInt 123+ ev StrToInt [VString "-1"] @?= VInt (-1)+ ev StrToInt [VString ""] @?= VInt (-1)+ ev StrFromInt [VInt (-3)] @?= VString ""+ , testCase "prefix and suffix" $ do+ ev StrPrefixOf [VString "ab", VString "abc"] @?= VBool True+ ev StrSuffixOf [VString "ab", VString "abc"] @?= VBool False+ ]+ , testGroup+ "arrays"+ [ testCase "store of select is the same array" $ do+ let a = mkArray IntSort (Map.fromList [(VInt 1, VInt 5)]) (VInt 0)+ ev Store [a, VInt 1, ev Select [a, VInt 1]] @?= a+ ev Store [a, VInt 2, VInt 0] @?= a+ , testCase "fully overridden finite domain equals a constant array" $ do+ let c = ev (ConstArray BoolSort) [VInt 7]+ a = ev Store [ev Store [ev (ConstArray BoolSort) [VInt 0], VBool False, VInt 7], VBool True, VInt 7]+ a @?= c+ ev Eq [a, c] @?= VBool True+ ]+ , testGroup+ "records"+ [ testCase "get and set" $ do+ let r = ev (RecordMk ["x", "y"]) [VInt 1, VBool True]+ ev (RecordGet "y") [r] @?= VBool True+ ev (RecordGet "x") [ev (RecordSet "x") [r, VInt 9]] @?= VInt 9+ ]+ , testGroup+ "typing"+ [ testCase "rejects ill-sorted terms" $ do+ assertLeft (sortOf (App Add [App (IntConst 1) [], App (BoolConst True) []]))+ assertLeft (sortOf (App (BVExtract 8 0) [App (BVConst 8 0) []]))+ assertLeft (sortOf (App (RecordGet "z") [App (RecordMk ["x"]) [App (IntConst 1) []]]))+ , testCase "infers result sorts" $ do+ sortOf (App BVConcat [App (BVConst 4 0) [], App (BVConst 8 0) []]) @?= Right (BVSort 12)+ sortOf (App Store [App (ConstArray IntSort) [App (StrConst "") []], App (IntConst 0) [], App (StrConst "a") []])+ @?= Right (ArraySort IntSort StringSort)+ ]+ ]+ where+ assertLeft :: Show b => Either a b -> Assertion+ assertLeft = \case+ Left _ -> pure ()+ Right b -> assertFailure ("expected a sort error, got " <> show b)
+ test/HSMT/FloatSpec.hs view
@@ -0,0 +1,182 @@+-- | Floating point: the reference semantics against the IEEE arithmetic of+-- GHC, and the bit-blasted circuits against the reference semantics.+module HSMT.FloatSpec (tests) where++import qualified Data.Text as T+import GHC.Float (castDoubleToWord64, castFloatToWord32, castWord32ToFloat, castWord64ToDouble)+import Test.QuickCheck+import Test.QuickCheck.Monadic (monadicIO, run)+import qualified Test.QuickCheck.Monadic as QC+import Test.Tasty+import Test.Tasty.HUnit+import Test.Tasty.QuickCheck (testProperty)++import HSMT.Core.Eval+import HSMT.Core.Expr+import HSMT.Core.Float+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Value+import HSMT.Gen.Expr (fpLiteral)+import HSMT.SMT.Engine++tests :: TestTree+tests =+ testGroup+ "Floating point"+ [ testGroup+ "reference semantics against GHC (round to nearest even)"+ [ testProperty "Float32" prop_float+ , testProperty "Float64" prop_double+ ]+ , testCase "special values" $ do+ let one = encode 8 24 (Finite False 1)+ two = encode 8 24 (Finite False 2)+ nan = canonicalNaN 8 24+ inf = encode 8 24 (Inf False)+ fpAdd RNE 8 24 one one @?= two+ fpDiv RNE 8 24 one (encode 8 24 (Zero True)) @?= encode 8 24 (Inf True)+ fpMul RNE 8 24 inf (encode 8 24 (Zero False)) @?= nan+ fpAdd RTN 8 24 one (fpNeg 8 24 one) @?= encode 8 24 (Zero True)+ fpAdd RNE 8 24 one (fpNeg 8 24 one) @?= encode 8 24 (Zero False)+ fpSqrt RNE 8 24 (encode 8 24 (Zero True)) @?= encode 8 24 (Zero True)+ fpMin 8 24 (encode 8 24 (Zero True)) (encode 8 24 (Zero False)) @?= Nothing+ fpToInteger RTZ 8 24 (0, 15) (encode 8 24 (Finite False 15.75)) @?= Just 15+ fpToInteger RNE 8 24 (0, 15) (encode 8 24 (Finite False 15.75)) @?= Nothing+ fpRem RNE 8 24 (encode 8 24 (Finite False 5)) (encode 8 24 (Finite False 2)) @?= one+ fpRem RNE 8 24 (encode 8 24 (Finite False 7)) (encode 8 24 (Finite False 2)) @?= encode 8 24 (Finite True 1)+ , testGroup+ "circuits agree with the reference semantics"+ [ testProperty "small formats" (prop_circuits [(3, 3), (3, 4), (4, 3), (2, 5), (5, 4)])+ , testProperty "Float16" (withMaxSuccess 200 (prop_circuits [(5, 11)]))+ , testProperty "Float32" (withMaxSuccess 40 (prop_circuits [(8, 24)]))+ ]+ , testCase "solving" $ do+ -- x + 1 = x has only infinite and huge solutions in Float16.+ r1 <- solve [App Eq [App FPAdd [rne, x16, one16], x16], App Not [App FPIsInfinite [x16]]]+ r1 @?= "sat"+ r2 <- solve [App Eq [App FPAdd [rne, x16, one16], x16], App FPLt [App FPAbs [x16], big16]]+ r2 @?= "unsat"+ -- NaN is not fp.eq to itself but is = to itself.+ r3 <- solve [App FPIsNaN [x16], App FPEq [x16, x16]]+ r3 @?= "unsat"+ r4 <- solve [App FPIsNaN [x16], App Not [App Eq [x16, x16]]]+ r4 @?= "unsat"+ -- fp.min of zeros of different signs may be either zero.+ let pz = constant (FPConst 5 11 0)+ nz = constant (FPConst 5 11 (2 ^ (15 :: Int)))+ r5 <- solve [App Eq [App FPMin [pz, nz], pz]]+ r6 <- solve [App Eq [App FPMin [pz, nz], nz]]+ r7 <- solve [App Not [App Eq [App FPMin [pz, nz], App FPMin [pz, nz]]]]+ (r5, r6, r7) @?= ("sat", "sat", "unsat")+ ]+ where+ rne = constant (RMConst RNE)+ x16 = constant (Uninterpreted (Symbol "x" [] (FPSort 5 11)))+ one16 = constant (FPConst 5 11 (encode 5 11 (Finite False 1)))+ big16 = constant (FPConst 5 11 (encode 5 11 (Finite False 2048)))++solve :: [Expr] -> IO String+solve as =+ solveAssertions True as >>= \case+ ESat _ -> pure "sat"+ EUnsat _ -> pure "unsat"+ EUnknown why -> pure ("unknown: " <> show why)++-------------------------------------------------------------------------------+-- Against GHC++-- | Patterns of special values, extremes and random bits.+genBits :: Int -> Int -> Gen Integer+genBits = fpLiteral++prop_float :: Property+prop_float = forAll ((,,) <$> elements ops <*> genBits 8 24 <*> genBits 8 24) $ \(name, a, b) ->+ let fa = castWord32ToFloat (fromInteger a)+ fb = castWord32ToFloat (fromInteger b)+ bitsOf :: Float -> Integer+ bitsOf = canonicalize 8 24 . toInteger . castFloatToWord32+ (mine, ghc) = case name of+ "add" -> (fpAdd RNE 8 24 a b, bitsOf (fa + fb))+ "sub" -> (fpSub RNE 8 24 a b, bitsOf (fa - fb))+ "mul" -> (fpMul RNE 8 24 a b, bitsOf (fa * fb))+ "div" -> (fpDiv RNE 8 24 a b, bitsOf (fa / fb))+ _ -> (fpSqrt RNE 8 24 a, bitsOf (sqrt fa))+ in counterexample (show (name, fa, fb, mine, ghc)) (mine === ghc)+ where+ ops = ["add", "sub", "mul", "div", "sqrt"] :: [String]++prop_double :: Property+prop_double = forAll ((,,) <$> elements ops <*> genBits 11 53 <*> genBits 11 53) $ \(name, a, b) ->+ let fa = castWord64ToDouble (fromInteger a)+ fb = castWord64ToDouble (fromInteger b)+ bitsOf :: Double -> Integer+ bitsOf = canonicalize 11 53 . toInteger . castDoubleToWord64+ (mine, ghc) = case name of+ "add" -> (fpAdd RNE 11 53 a b, bitsOf (fa + fb))+ "sub" -> (fpSub RNE 11 53 a b, bitsOf (fa - fb))+ "mul" -> (fpMul RNE 11 53 a b, bitsOf (fa * fb))+ "div" -> (fpDiv RNE 11 53 a b, bitsOf (fa / fb))+ _ -> (fpSqrt RNE 11 53 a, bitsOf (sqrt fa))+ in counterexample (show (name, fa, fb, mine, ghc)) (mine === ghc)+ where+ ops = ["add", "sub", "mul", "div", "sqrt"] :: [String]++-------------------------------------------------------------------------------+-- Circuits++-- | For random operands, the circuit of each operator must give exactly+-- the value of the reference semantics (or, where SMT-LIB leaves the+-- result unspecified, accept it). The operands are variables fixed by+-- equalities, so the circuits are not constant-folded.+prop_circuits :: [(Int, Int)] -> Property+prop_circuits formats = forAll gen $ \(op, fmt, rm, vals) -> monadicIO $ do+ let (eb, sb) = fmt+ fpVar n = constant (Uninterpreted (Symbol n [] (FPSort eb sb)))+ names = ["a", "b", "c"]+ args = [fpVar n | n <- take (length vals) names]+ fixes = [App Eq [a, constant (FPConst eb sb v)] | (a, v) <- zip args vals]+ rmArg = [constant (RMConst rm) | needsRM op]+ term = App op (rmArg <> args)+ concrete = App op (rmArg <> [constant (FPConst eb sb v) | v <- vals])+ expected = either (error . show) id (evalExpr emptyInterpretation concrete)+ specified = not (unspecified op fmt rm vals)+ valueTerm = case expected of+ VFP e s v -> constant (FPConst e s v)+ VBV w v -> constant (BVConst w v)+ VBool b -> constant (BoolConst b)+ other -> error (show other)+ agrees <- run (solve (fixes <> [App Eq [term, valueTerm]]))+ differs <- run (solve (fixes <> [App Not [App Eq [term, valueTerm]]]))+ QC.monitor (counterexample (show (op, fmt, rm, vals, expected, agrees, differs)))+ QC.monitor (label (T.unpack (opName op)))+ QC.assert (if specified then agrees == "sat" && differs == "unsat" else agrees == "sat" || differs == "sat")+ where+ gen = do+ fmt@(eb, sb) <- elements formats+ (op, arity) <- elements operators+ rm <- elements allRoundingModes+ vals <- vectorOf arity (fpLiteral eb sb)+ pure (op, fmt, rm, vals)+ operators =+ [(o, 2) | o <- [FPAdd, FPSub, FPMul, FPDiv, FPRem, FPMin, FPMax, FPLeq, FPLt, FPEq]]+ <> [(FPFma, 3)]+ <> [ (o, 1)+ | o <-+ [ FPSqrt, FPRoundToIntegral, FPAbs, FPNeg, FPIsNormal, FPIsSubnormal, FPIsZero+ , FPIsInfinite, FPIsNaN, FPIsNegative, FPIsPositive+ , ToFP 3 5, ToFP 6 7, FPToUBV 4, FPToSBV 5+ ]+ ]+ needsRM = \case+ o | o `elem` [FPAdd, FPSub, FPMul, FPDiv, FPFma, FPSqrt, FPRoundToIntegral] -> True+ ToFP _ _ -> True+ FPToUBV _ -> True+ FPToSBV _ -> True+ _ -> False+ unspecified op (eb, sb) rm vals = case (op, vals) of+ (FPMin, [x, y]) -> fpMin eb sb x y == Nothing+ (FPMax, [x, y]) -> fpMax eb sb x y == Nothing+ (FPToUBV w, [x]) -> fpToInteger rm eb sb (0, 2 ^ w - 1) x == Nothing+ (FPToSBV w, [x]) -> fpToInteger rm eb sb (negate (2 ^ (w - 1)), 2 ^ (w - 1) - 1) x == Nothing+ _ -> False
+ test/HSMT/IncrementalSpec.hs view
@@ -0,0 +1,229 @@+{-# LANGUAGE RankNTypes #-}++-- | Incremental solving: unsatisfiable cores, assumptions, resource limits+-- and sequences of checks over one session.+module HSMT.IncrementalSpec (tests, testsWith) where++import Control.Monad (forM)+import Data.List (sort)+import qualified Data.Text as T+import GHC.Clock (getMonotonicTime)+import Test.Tasty+import Test.Tasty.HUnit hiding (assert)++import HSMT+import HSMT.SMT.Engine (EngineResult (..))+import HSMT.SMTLib.Run++answer :: Result ctx -> String+answer = \case+ Sat _ -> "sat"+ Unsat _ -> "unsat"+ Unknown why -> "unknown: " <> T.unpack why++-- | Pigeonhole: n + 1 pigeons in n holes, as Boolean constraints.+pigeonhole :: Int -> SMT ctx ()+pigeonhole n = do+ ps <- forM [0 .. n] $ \i -> forM [1 .. n] $ \j -> declare @'BoolS (T.pack ("p" <> show i <> "_" <> show j))+ mapM_ (assert . orB) ps+ sequence_+ [ assert (notB (ps !! i !! j) .|| notB (ps !! k !! j))+ | j <- [0 .. n - 1]+ , i <- [0 .. n]+ , k <- [i + 1 .. n]+ ]++tests :: TestTree+tests = testsWith defaultConfig++-- | The tests with the given configuration (and its backend).+testsWith :: Config -> TestTree+testsWith base =+ testGroup+ "incremental solving"+ [ testGroup+ "unsatisfiable cores"+ [ testCase "a core is unsatisfiable on its own" $ do+ core <- runSMT base $ do+ p <- declare @'BoolS "p"+ q <- declare @'BoolS "q"+ r <- declare @'BoolS "r"+ let as = [p, r .|| q, notB p .|| notB q, r .=> p, notB r]+ mapM_ assert as+ c <- checkSat >>= liftCore+ pure (map (`elem` as) (coreAssertions c), length (coreAssertions c))+ -- Every element is an assertion, and the five assertions are+ -- needed except possibly r => p.+ all id (fst core) @? "core elements are assertions"+ assertBool "core size" (snd core >= 4)+ , testCase "minimal cores drop irrelevant assertions" $ do+ same <- runSMT (base {cfgMinimizeCores = True}) $ do+ x <- declare @'IntS "x"+ y <- declare @'IntS "y"+ z <- declare @'IntS "z"+ let relevant = [x .> 5, x + y .< 3, y .== 0]+ mapM_ assert [z .== 1, x .> 5, y .< 100, x + y .< 3, y .== 0, z .> 0]+ c <- checkSat >>= liftCore+ pure (sort (coreAssertions c) == sort relevant)+ same @?= True+ , testCase "minimal cores in every theory" $ do+ rs <- runSMT (base {cfgMinimizeCores = True}) $ do+ f <- declareFun @'[ 'IntS] @'IntS "f"+ a <- declare @('ArrayS ('BVS 4) 'BoolS) "a"+ b <- declare @('BVS 8) "b"+ s <- declare @'StringS "s"+ x <- declare @'IntS "x"+ p <- declare @'BoolS "p"+ q <- declare @'BoolS "q"+ -- Satisfiable together, and with any one theory group.+ let filler = [x .> 0, p, b `bvULt` bv 200, strLen s .< 10, select a (bv 3)]+ groups =+ [ [f x .== 3, x .== 3, f 3 .> 3]+ , [select a (bv 1) .== select a (bv 2), notB (select a (bv 2)), select a (bv 1)]+ , [b `bvULt` bv 10, b `bvUGt` bv 9]+ , [strLen s .== x, x .== 3, prefixOf "abcd" s]+ , [q, q .=> contains s "z", s .== "abc"]+ ]+ forM groups $ \g -> scoped $ do+ mapM_ assert (filler <> g)+ c <- checkSat >>= liftCore+ pure (sort (coreAssertions c) == sort g)+ rs @?= replicate 5 True+ , testCase "unsatisfiable assertions without core minimization" $ do+ r <- runSMT base $ do+ assert (bool False)+ map show . coreAssertions <$> (checkSat >>= liftCore)+ r @?= ["App (BoolConst False) []"]+ ]+ , testGroup+ "assumptions"+ [ testCase "assumptions hold for one check" $ do+ r <- runSMT base $ do+ x <- declare @'IntS "x"+ assert (x .> 0)+ c <- checkSatAssuming [x .< 0, x .== 7] >>= liftCore+ later <- checkSat+ pure (coreAssertions c == [x .> 0], coreAssumptions c == [x .< 0], answer later)+ r @?= (True, True, "sat")+ , testCase "tracking literals" $ do+ r <- runSMT (base {cfgMinimizeCores = True}) $ do+ x <- declare @'IntS "x"+ ts <- forM [1 .. 4 :: Int] $ \i -> declare @'BoolS (T.pack ("t" <> show i))+ let constraints = [x .> 10, x .< 20, x .== 5, x .> 0]+ sequence_ [assert (t .=> c) | (t, c) <- zip ts constraints]+ c <- checkSatAssuming ts >>= liftCore+ s <- checkSatAssuming [ts !! 0, ts !! 1, ts !! 3]+ pure (map (`elemIndex'` ts) (coreAssumptions c), answer s)+ r @?= ([Just 0, Just 2], "sat")+ , testCase "an assumption that is an assertion" $ do+ r <- runSMT base $ do+ p <- declare @'BoolS "p"+ assert p+ c <- checkSatAssuming [notB p, p] >>= liftCore+ pure (length (coreAssertions c) + length (coreAssumptions c) >= 2)+ r @?= True+ ]+ , testGroup+ "resource limits"+ [ testCase "a timeout answers unknown and the session goes on" $ do+ start <- getMonotonicTime+ (r1, r2) <- runSMT base {cfgTimeout = Just 200} $ do+ p <- declare @'BoolS "p"+ r2 <- scoped (pigeonhole 11 >> checkSat)+ assert p+ r1 <- checkSat+ pure (answer r1, answer r2)+ elapsed <- subtract start <$> getMonotonicTime+ (r1, r2) @?= ("sat", "unknown: timeout")+ assertBool ("took " <> show elapsed <> " s") (elapsed < 3)+ , testCase "a conflict limit answers unknown" $ do+ r <- runSMT base {cfgConflictLimit = Just 5} $ do+ pigeonhole 6+ answer <$> checkSat+ r @?= "unknown: resource limit reached"+ , testCase "limits leave easy checks alone" $ do+ r <- runSMT base {cfgConflictLimit = Just 1000, cfgTimeout = Just 5000} $ do+ pigeonhole 4+ answer <$> checkSat+ r @?= "unsat"+ ]+ , testGroup+ "sessions"+ [ testCase "many checks over one session" $ do+ rs <- runSMT base $ do+ x <- declare @'IntS "x"+ f <- declareFun @'[ 'IntS] @'IntS "f"+ assert (f x .> x)+ vs <- forM [1 .. 40 :: Integer] $ \i -> scoped $ do+ assert (x .== fromInteger i)+ checkSat >>= \case+ Sat m -> pure (eval m (f x) > i)+ _ -> pure False+ last' <- scoped (assert (f x .< x) >> answer <$> checkSat)+ pure (and vs, last')+ rs @?= (True, "unsat")+ , testCase "theories that appear later" $ do+ rs <- runSMT base $ do+ p <- declare @'BoolS "p"+ assert p+ r1 <- checkSat+ x <- declare @'IntS "x"+ assert (p .=> x .> 3)+ r2 <- checkSat+ s <- declare @'StringS "s"+ assert (strLen s .== x)+ assert (x .< 5)+ r3 <-+ checkSat >>= \case+ Sat m -> pure (T.length (eval m s) == 4)+ _ -> pure False+ f <- declareFun @'[ 'StringS] @'BoolS "f"+ assert (f s .&& notB (f (s <+> "")))+ r4 <- checkSat+ pure (answer r1, answer r2, r3, answer r4)+ rs @?= ("sat", "sat", True, "unsat")+ , testCase "longer strings in later checks" $ do+ rs <- runSMT base $ do+ s <- declare @'StringS "s"+ r1 <- scoped (assert (strLen s .== 3) >> answer <$> checkSat)+ r2 <- scoped (assert (strLen s .== 20) >> answer <$> checkSat)+ r3 <- scoped (assert (strLen s .== 2 .&& prefixOf "abc" s) >> answer <$> checkSat)+ pure (r1, r2, r3)+ rs @?= ("sat", "sat", "unsat")+ ]+ , testCase "SMT-LIB: named assertions, assumptions and cores" $ do+ let script =+ T.unlines+ [ "(set-option :smt.core.minimize true)"+ , "(declare-const x Int)"+ , "(declare-const p Bool)"+ , "(assert (! (> x 3) :named a1))"+ , "(assert (! p :named a2))"+ , "(assert (< x 100))"+ , "(check-sat-assuming ((< x 2) (and p (= x 5))))"+ , "(get-unsat-core)"+ , "(check-sat)"+ , "(get-unsat-core)"+ , "(assert (not a2))"+ , "(check-sat)"+ , "(get-unsat-core)"+ ]+ runScriptResponsesWith (cfgBackend base) True script >>= \case+ [ CheckResult (EUnsat _)+ , UnsatCore core1+ , CheckResult (ESat _)+ , CommandError _+ , CheckResult (EUnsat _)+ , UnsatCore core2+ ] -> do+ -- Both are minimal; the engine finds the first.+ assertBool ("core: " <> show core1) $+ core1 `elem` [["a1", "(< x 2)"], ["(< x 2)", "(and p (= x 5))"]]+ core2 @?= ["a2"]+ other -> assertFailure (show other)+ ]+ where+ liftCore r = case r of+ Unsat c -> pure c+ _ -> error ("expected unsat, got " <> answer r)+ elemIndex' t ts = lookup t (zip ts [0 :: Int ..])
+ test/HSMT/LIASpec.hs view
@@ -0,0 +1,159 @@+module HSMT.LIASpec (tests) where++import Control.Monad (forM_)+import qualified Data.Map.Strict as Map+import Data.Maybe (isJust)+import Data.Text (Text)+import Test.QuickCheck+import Test.QuickCheck.Monadic (monadicIO, run)+import qualified Test.QuickCheck.Monadic as QC+import Test.Tasty+import Test.Tasty.HUnit+import Test.Tasty.QuickCheck (testProperty)++import HSMT.Core.Eval+import HSMT.Core.Expr+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Value+import HSMT.SMT.Engine+import qualified HSMT.Theory.Arith.Simplex as Sx++tests :: TestTree+tests =+ testGroup+ "LIA"+ [ testCase "simplex finds a feasible point" $ do+ sx <- Sx.newSimplex+ u <- Sx.newVar sx+ w <- Sx.newVar sx+ s <- Sx.addRow sx [(1, u), (1, w)]+ d <- Sx.addRow sx [(1, u), (-1, w)]+ _ <- Sx.assertLower sx s 10 []+ _ <- Sx.assertUpper sx d 2 []+ _ <- Sx.assertLower sx d 2 []+ r <- Sx.check sx+ isJust r @?= False+ vu <- Sx.value sx u+ vw <- Sx.value sx w+ assertBool "u + w >= 10" (vu + vw >= 10)+ vu - vw @?= 2+ , testCase "simplex detects infeasibility and backtracks" $ do+ sx <- Sx.newSimplex+ u <- Sx.newVar sx+ w <- Sx.newVar sx+ s <- Sx.addRow sx [(1, u), (1, w)]+ _ <- Sx.assertUpper sx u 1 []+ Sx.push sx+ _ <- Sx.assertUpper sx w 1 []+ _ <- Sx.assertLower sx s 3 []+ r1 <- Sx.check sx+ isJust r1 @?= True+ Sx.pop sx 0+ _ <- Sx.assertLower sx s 3 []+ r2 <- Sx.check sx+ isJust r2 @?= False+ , testCase "integrality on unbounded problems" $ do+ -- 3x + 3y = 2 has rational solutions only.+ r1 <- solve [eq (add [mul 3 x, mul 3 y]) (int 2)]+ r1 @?= "unsat"+ r2 <- solve [le (add [int 1, mul 3 x, mul 2 y]) (int 0), lt (int 3) x]+ r2 @?= "sat"+ , testCase "division and remainder by literals" $+ forM_ [(-7, 2), (7, -2), (-7, -2), (7, 2), (0, 5)] $ \(a, b) -> do+ let q = App IntDiv [x, int b]+ r = App IntMod [x, int b]+ (q0, r0) = euclid a b+ res <- solve [eq x (int a), eq q (int q0), eq r (int r0)]+ res @?= "sat"+ res' <- solve [eq x (int a), App Not [eq q (int q0)]]+ res' @?= "unsat"+ , testCase "division by zero is uninterpreted" $ do+ let d t = App IntDiv [t, int 0]+ r1 <- solve [eq (d x) (int 1), eq (d y) (int 2)]+ r1 @?= "sat"+ r2 <- solve [eq x y, eq (d x) (int 1), eq (d y) (int 2)]+ r2 @?= "unsat"+ , testCase "congruence meets arithmetic" $ do+ r1 <- solve [le x y, le y x, App Not [eq (f x) (f y)]]+ r1 @?= "unsat"+ r2 <- solve [eq (add [x, int 1]) y, eq (f (add [y, int (-1)])) (int 3), eq (f x) (int 4)]+ r2 @?= "unsat"+ r3 <- solve [lt x y, eq (f x) (f y)]+ r3 @?= "sat"+ r4 <- solve [le (int 1) x, le x (int 2), distinct [f x, f (int 1), f (int 2)]]+ r4 @?= "unsat"+ , testProperty "agrees with brute force on bounded problems" prop_bruteForce+ ]+ where+ x = var "x"+ y = var "y"+ f t = App (Uninterpreted (Symbol "f" [IntSort] IntSort)) [t]+ euclid a b = let r = a `mod` abs b in ((a - r) `div` b, r)++var :: Text -> Expr+var n = constant (Uninterpreted (Symbol n [] IntSort))++int :: Integer -> Expr+int = constant . IntConst++add :: [Expr] -> Expr+add = App Add++mul :: Integer -> Expr -> Expr+mul k e = App Mul [int k, e]++eq, le, lt :: Expr -> Expr -> Expr+eq a b = App Eq [a, b]+le a b = App Le [a, b]+lt a b = App Lt [a, b]++distinct :: [Expr] -> Expr+distinct = App Distinct++solve :: [Expr] -> IO String+solve as =+ solveAssertions True as >>= \case+ ESat _ -> pure "sat"+ EUnsat _ -> pure "unsat"+ EUnknown why -> pure ("unknown: " <> show why)++-- | Random linear constraints over three variables restricted to [-3, 3],+-- decided by enumeration.+prop_bruteForce :: Property+prop_bruteForce = forAll genProblem $ \cs -> monadicIO $ do+ let names = ["x", "y", "z"]+ bounds = concat [[le (int (-3)) (var n), le (var n) (int 3)] | n <- names]+ problem = bounds <> cs+ models =+ [ Map.fromList [(Symbol n [] IntSort, constInterp (VInt v)) | (n, v) <- zip names vs]+ | vs <- sequence (replicate 3 [-3 .. 3])+ ]+ holds m = all (\c -> evalExpr emptyInterpretation {interpSymbols = m} c == Right (VBool True)) problem+ expected = if any holds models then "sat" else "unsat"+ r <- run (solve problem)+ QC.monitor (cover 20 (expected == "sat") "sat" . cover 20 (expected == "unsat") "unsat")+ QC.monitor (counterexample (show cs <> "\nhsmt: " <> r <> ", expected: " <> expected))+ QC.assert (r == expected)+ where+ genProblem = do+ n <- chooseInt (1, 5)+ vectorOf n clause+ clause = do+ k <- frequency [(3, pure 1), (1, pure 2)]+ ls <- vectorOf k literal+ pure (case ls of [l] -> l; _ -> App Or ls)+ literal = do+ a <- atom+ frequency [(3, pure a), (1, pure (App Not [a]))]+ atom = do+ lhs <- linear+ rhs <- linear+ elements [le lhs rhs, lt lhs rhs, eq lhs rhs]+ linear = do+ terms <- sublistOf ["x", "y", "z"]+ coeffs <- vectorOf (length terms) (elements [-3, -2, -1, 1, 2, 3])+ c <- chooseInteger (-4, 4)+ pure $ case [mul k (var n) | (k, n) <- zip coeffs terms] of+ [] -> int c+ ts -> add (int c : ts)
+ test/HSMT/RecordSpec.hs view
@@ -0,0 +1,104 @@+module HSMT.RecordSpec (tests) where++import Data.Text (Text)+import qualified Data.Text as T+import Test.Tasty+import Test.Tasty.HUnit++import HSMT.SMT.Engine+import HSMT.SMTLib.Run++tests :: TestTree+tests =+ testGroup+ "Records"+ [ testCase "selection and construction" $ do+ let base = [point, "(declare-const p P)", "(declare-const x Int)"]+ expect (base <> ["(assert (not (= (px (mkP x true)) x)))"]) ["unsat"]+ expect (base <> ["(assert (= p (mkP x true)))", "(assert (not (py p)))"]) ["unsat"]+ expect (base <> ["(assert (= (mkP x true) (mkP 3 true)))", "(check-sat)", "(assert (distinct x 3))"]) ["sat", "unsat"]+ , testCase "extensionality" $ do+ let base = [point, "(declare-const p P)", "(declare-const q P)"]+ -- Records with equal fields are equal.+ expect (base <> ["(assert (= (px p) (px q)))", "(assert (= (py p) (py q)))", "(assert (distinct p q))"]) ["unsat"]+ expect (base <> ["(assert (distinct p (mkP (px p) (py p))))"]) ["unsat"]+ expect (base <> ["(assert (= (px p) (px q)))", "(assert (distinct p q))", "(check-sat)", "(assert (py p))", "(assert (py q))"]) ["sat", "unsat"]+ , testCase "finite record sorts" $ do+ let pair = "(declare-datatypes ((B 0)) (((mkB (b1 Bool) (b2 (_ BitVec 1))))))"+ consts n = ["(declare-const x" <> tshow i <> " B)" | i <- [1 .. n]]+ names n = T.unwords ["x" <> tshow i | i <- [1 .. n :: Int]]+ expect (pair : consts 4 <> ["(assert (distinct " <> names 4 <> "))"]) ["sat"]+ expect (pair : consts 5 <> ["(assert (distinct " <> names 5 <> "))"]) ["unsat"]+ -- The empty record has a single value.+ expect+ ["(declare-datatypes ((E 0)) (((mkE))))", "(declare-const e E)", "(declare-const f E)", "(assert (distinct e f))"]+ ["unsat"]+ , testCase "nested records" $ do+ let base =+ [ point+ , "(declare-datatypes ((S 0)) (((mkS (pos P) (tag Int)))))"+ , "(declare-const s S)"+ , "(declare-const t S)"+ ]+ expect (base <> ["(assert (= (pos s) (pos t)))", "(assert (= (tag s) (tag t)))", "(assert (distinct s t))"]) ["unsat"]+ expect (base <> ["(assert (= s t))", "(assert (distinct (px (pos s)) (px (pos t))))"]) ["unsat"]+ expect (base <> ["(assert (= (px (pos s)) (+ (tag s) 1)))", "(assert (> (tag s) (px (pos s))))"]) ["unsat"]+ , testCase "uninterpreted functions over records" $ do+ let base = [point, "(declare-const p P)", "(declare-const q P)", "(declare-fun f (P) Int)", "(declare-fun g (Int) P)"]+ expect (base <> ["(assert (= (px p) (px q)))", "(assert (= (py p) (py q)))", "(assert (distinct (f p) (f q)))"]) ["unsat"]+ expect (base <> ["(assert (distinct (f p) (f q)))", "(assert (= (px p) (px q)))"]) ["sat"]+ expect (base <> ["(assert (= (g 1) (g 2)))", "(assert (distinct (px (g 1)) (px (g 2))))"]) ["unsat"]+ , testCase "arrays of records" $ do+ let base = [point, "(declare-const a (Array Int P))", "(declare-const i Int)", "(declare-const j Int)"]+ expect+ (base <> ["(assert (not (= (px (select (store a i (mkP 5 false)) i)) 5)))"])+ ["unsat"]+ expect+ (base <> ["(assert (distinct (px (select a i)) (px (select a j))))", "(check-sat)", "(assert (= i j))"])+ ["sat", "unsat"]+ , testCase "arrays indexed by records" $ do+ let pair = "(declare-datatypes ((B 0)) (((mkB (b1 Bool) (b2 (_ BitVec 1))))))"+ k v = "((as const (Array B Int)) " <> v <> ")"+ full = foldl (\acc ix -> "(store " <> acc <> " " <> ix <> " 1)") (k "0") ["(mkB " <> b <> " " <> w <> ")" | b <- ["true", "false"], w <- ["#b0", "#b1"]]+ -- Overwriting every index changes the default.+ expect [pair, "(assert (= " <> full <> " " <> k "1" <> "))"] ["sat"]+ expect+ [ pair+ , "(declare-const a (Array B Int))"+ , "(declare-const i B)"+ , "(assert (= (select a i) 5))"+ , "(assert (= (select (store a (mkB true #b0) 2) i) 2))"+ , "(check-sat)"+ , "(assert (not (b1 i)))"+ ]+ ["sat", "unsat"]+ -- An infinite record index sort.+ expect+ [ point+ , "(declare-const a (Array P Int))"+ , "(declare-const p P)"+ , "(declare-const x Int)"+ , "(assert (distinct (select (store a (mkP x true) 1) p) (select a p)))"+ , "(check-sat)"+ , "(assert (distinct (px p) x))"+ ]+ ["sat", "unsat"]+ ]+ where+ point = "(declare-datatypes ((P 0)) (((mkP (px Int) (py Bool)))))"++tshow :: Int -> Text+tshow = T.pack . show++-- | Run a script (with model validation) and compare its answers; a final+-- @check-sat@ is appended.+expect :: [Text] -> [Text] -> Assertion+expect cmds answers =+ runScriptText True (T.unlines (cmds <> ["(check-sat)"])) >>= \case+ Left err -> assertFailure (T.unpack err)+ Right rs -> map answer rs @?= answers+ where+ answer = \case+ ESat _ -> "sat"+ EUnsat _ -> "unsat"+ EUnknown why -> "unknown: " <> why
+ test/HSMT/RegexSpec.hs view
@@ -0,0 +1,177 @@+-- | Regular expressions: derivatives against a naive matcher, automata+-- against derivatives, and the language measures against enumeration.+module HSMT.RegexSpec (tests) where++import qualified Data.IntMap.Strict as IntMap+import qualified Data.IntSet as IntSet+import Data.List (inits, tails)+import Data.Maybe (isJust)+import qualified Data.Text as T+import Test.QuickCheck+import Test.Tasty+import Test.Tasty.HUnit+import Test.Tasty.QuickCheck (testProperty)++import HSMT.Core.Regex++-- | Expressions as written, before normalization.+data Raw+ = Lit String+ | Range Char Char+ | AnyChar+ | Nothing'+ | All+ | Cat Raw Raw+ | Alt Raw Raw+ | And Raw Raw+ | Star Raw+ | Plus Raw+ | Opt Raw+ | Comp Raw+ | Diff Raw Raw+ | Loop Int Int Raw+ deriving (Show)++-- | The characters of the generated expressions; @z@ stands for every+-- other character in enumerations.+alphabet :: String+alphabet = "abcz"++instance Arbitrary Raw where+ arbitrary = sized gen+ where+ gen n+ | n <= 1 =+ frequency+ [ (4, Lit <$> listOf1' 2)+ , (2, Range <$> elements "abc" <*> elements "abc")+ , (1, pure AnyChar)+ , (1, pure Nothing')+ , (1, pure All)+ , (1, pure (Lit ""))+ ]+ | otherwise =+ let sub = gen (n `div` 2)+ in frequency+ [ (2, gen 1)+ , (3, Cat <$> sub <*> sub)+ , (3, Alt <$> sub <*> sub)+ , (2, And <$> sub <*> sub)+ , (2, Star <$> sub)+ , (1, Plus <$> sub)+ , (1, Opt <$> sub)+ , (2, Comp <$> sub)+ , (1, Diff <$> sub <*> sub)+ , (1, Loop <$> choose (0, 2) <*> choose (0, 3) <*> sub)+ ]+ listOf1' k = choose (1, k) >>= \m -> vectorOf m (elements "abc")+ shrink = \case+ Cat a b -> [a, b] <> [Cat a' b | a' <- shrink a] <> [Cat a b' | b' <- shrink b]+ Alt a b -> [a, b] <> [Alt a' b | a' <- shrink a] <> [Alt a b' | b' <- shrink b]+ And a b -> [a, b] <> [And a' b | a' <- shrink a] <> [And a b' | b' <- shrink b]+ Diff a b -> [a, b] <> [Diff a' b | a' <- shrink a] <> [Diff a b' | b' <- shrink b]+ Star a -> a : map Star (shrink a)+ Plus a -> a : map Plus (shrink a)+ Opt a -> a : map Opt (shrink a)+ Comp a -> a : map Comp (shrink a)+ Loop i j a -> a : map (Loop i j) (shrink a)+ _ -> []++build :: Raw -> Regex+build = \case+ Lit s -> literal (T.pack s)+ Range a b -> range (T.singleton a) (T.singleton b)+ AnyChar -> allChar+ Nothing' -> none+ All -> everything+ Cat a b -> cat (build a) (build b)+ Alt a b -> union [build a, build b]+ And a b -> inter [build a, build b]+ Star a -> star (build a)+ Plus a -> plus (build a)+ Opt a -> opt (build a)+ Comp a -> complement (build a)+ Diff a b -> difference (build a) (build b)+ Loop i j a -> loop i j (build a)++-- | Membership by the definition of each operator.+naive :: Raw -> String -> Bool+naive r w = case r of+ Lit s -> w == s+ Range a b -> case w of+ [c] -> a <= c && c <= b+ _ -> False+ AnyChar -> length w == 1+ Nothing' -> False+ All -> True+ Cat a b -> or [naive a x && naive b y | (x, y) <- splits w]+ Alt a b -> naive a w || naive b w+ And a b -> naive a w && naive b w+ Star a -> null w || or [naive a x && naive (Star a) y | (x, y) <- splits w, not (null x)]+ Plus a -> naive (Cat a (Star a)) w+ Opt a -> null w || naive a w+ Comp a -> not (naive a w)+ Diff a b -> naive a w && not (naive b w)+ Loop i j a+ | j < i -> False+ | otherwise -> any (\k -> naive (power' k a) w) [i .. j]+ where+ splits s = zip (inits s) (tails s)+ power' k a = foldr Cat (Lit "") (replicate k a)++strings :: Int -> [String]+strings n = concatMap (\k -> sequence (replicate k alphabet)) [0 .. n]++runDfa :: Dfa -> String -> Bool+runDfa dfa = go 0+ where+ go q = \case+ [] -> IntSet.member q (dfaAccepting dfa)+ (c : cs) -> case [j | (set, j) <- IntMap.findWithDefault [] q (dfaDelta dfa), memberSet (fromEnum c) set] of+ [j] -> go j cs+ _ -> False++tests :: TestTree+tests =+ testGroup+ "regular expressions"+ [ testProperty "derivatives agree with the definitions" $ \raw ->+ forAll (elements (strings 5)) $ \w ->+ counterexample (show (build raw)) $ matches (build raw) (T.pack w) === naive raw w+ , testProperty "automata agree with derivatives" $ \raw ->+ let r = build raw+ in isJust (toDfa r) ==>+ case toDfa r of+ Just dfa -> conjoin [counterexample w (runDfa dfa w === matches r (T.pack w)) | w <- strings 4]+ Nothing -> property False+ , testProperty "shortest and longest members" $ \raw ->+ let r = build raw+ members = [w | w <- strings 6, matches r (T.pack w)]+ in case toDfa r of+ Nothing -> property Discard+ Just dfa ->+ conjoin+ [ case members of+ w : _ -> minLength dfa === Just (length w)+ [] -> property (maybe True (> 6) (minLength dfa))+ , case maxLength dfa of+ Just m ->+ counterexample ("max " <> show m) $+ m <= 6 ==> maximum (map length members) === m+ Nothing -> property True+ ]+ , testProperty "equivalence agrees with enumeration" $ \a b ->+ let (ra, rb) = (build a, build b)+ in case equivalent ra rb of+ Just True -> conjoin [counterexample w (matches ra (T.pack w) === matches rb (T.pack w)) | w <- strings 4]+ _ -> property True+ , testCase "identities" $ do+ star (star (literal "a")) @?= star (literal "a")+ complement (complement (literal "ab")) @?= literal "ab"+ union [allChar, literal "a"] @?= allChar+ equivalent (star (union [literal "a", literal "b"])) (star (cat (star (literal "a")) (star (literal "b")))) @?= Just True+ equivalent (plus (literal "ab")) (cat (literal "ab") (star (literal "ab"))) @?= Just True+ equivalent (star (literal "aa")) (star (literal "a")) @?= Just False+ fmap minLength (toDfa (inter [plus (literal "ab"), power 3 allChar])) @?= Just Nothing+ (toDfa (loop 2 5 (literal "ab")) >>= maxLength) @?= Just 10+ ]
+ test/HSMT/RegressionSpec.hs view
@@ -0,0 +1,93 @@+-- | Replays the SMT-LIB files in @test/regressions@ and the benchmarks in+-- @bench/smtlib@ ("HSMT.Benchmarks").+--+-- Regressions Each file states the+-- expected answers of its @check-sat@ commands in a comment line of the form+-- @; expected: sat unsat ...@; an expected @unknown@ accepts any answer.+--+-- A file containing the line @; allow-unknown@ also accepts @unknown@ from+-- hsmt; it is meant for regressions over theories without a decision+-- procedure yet. Wrong definite answers always fail.+module HSMT.RegressionSpec (tests, testsWith) where++import Data.IORef+import Data.List (isPrefixOf, isSuffixOf, sort)+import qualified Data.Text as T+import qualified Data.Text.IO as T+import System.Directory (doesDirectoryExist, listDirectory)+import System.FilePath ((</>))+import Test.Tasty+import Test.Tasty.HUnit++import HSMT.Backend+import HSMT.Benchmarks+import HSMT.SMT.Engine+import HSMT.SMTLib.Run++regressionDir :: FilePath+regressionDir = "test" </> "regressions"++tests :: IO TestTree+tests = testsWith Native++-- | The files, decided by the given backend. With an external solver,+-- the regressions named @z3-*@ (errors of Z3 found by the differential+-- tests) are skipped.+testsWith :: Backend -> IO TestTree+testsWith backend = do+ exists <- doesDirectoryExist regressionDir+ files <- if exists then sort . filter (".smt2" `isSuffixOf`) <$> listDirectory regressionDir else pure []+ benches <- benchmarkFiles+ let keep f = backend == Native || not ("z3-" `isPrefixOf` f)+ pure $+ testGroup+ "SMT-LIB files"+ [ testGroup "regressions" (map (regression backend) (filter keep files))+ , testGroup "benchmarks" (map (benchmark backend) benches)+ ]++-- | A benchmark must give the annotated answers. Files in+-- 'knownLimitations' may answer @unknown@, within a time limit.+benchmark :: Backend -> FilePath -> TestTree+benchmark backend file = testCase file $ do+ txt <- T.readFile (benchmarkDir </> file)+ out <- newIORef []+ let limited = file `elem` map fst knownLimitations+ opts = defaultCheckOptions {coValidate = True, coTimeout = if limited then Just 2 else Nothing}+ runScriptWithBackend backend opts (\r -> modifyIORef' out (r :)) txt+ responses <- reverse <$> readIORef out+ case [e | CommandError e <- responses] of+ e : _ -> assertFailure ("script error: " <> T.unpack e)+ [] -> pure ()+ let answers = [answerText r | CheckResult r <- responses]+ expected = expectedStatuses txt+ length answers @?= length expected+ sequence_+ [ assertBool ("check-sat #" <> show i <> ": expected " <> T.unpack e <> ", got " <> T.unpack a) $+ a == e || (limited && a == "unknown")+ | (i, e, a) <- zip3 [1 :: Int ..] expected answers+ ]++regression :: Backend -> FilePath -> TestTree+regression backend file = testCase file $ do+ txt <- T.readFile (regressionDir </> file)+ expected <- case [T.words rest | l <- T.lines txt, Just rest <- [T.stripPrefix "; expected:" l]] of+ [ws] -> pure ws+ _ -> assertFailure "missing or duplicated '; expected:' line"+ let allowUnknown = "; allow-unknown" `elem` map T.strip (T.lines txt)+ responses <- runScriptResponsesWith backend True txt+ case [e | CommandError e <- responses] of+ err : _ -> assertFailure ("script error: " <> T.unpack err)+ [] -> do+ let results = [r | CheckResult r <- responses]+ length results @?= length expected+ sequence_+ [ assertBool ("check-sat #" <> show i <> ": expected " <> T.unpack e <> ", got " <> T.unpack (answer r)) $+ e == "unknown" || e == answer r || (allowUnknown && answer r == "unknown")+ | (i, e, r) <- zip3 [1 :: Int ..] expected results+ ]+ where+ answer = \case+ ESat _ -> "sat"+ EUnsat _ -> "unsat"+ EUnknown _ -> "unknown"
+ test/HSMT/SATSpec.hs view
@@ -0,0 +1,167 @@+module HSMT.SATSpec (tests) where++import Control.Monad+import Data.IORef+import Data.List (nub)+import Test.QuickCheck.Monadic (assert, monadicIO, run)+import Test.Tasty+import Test.Tasty.HUnit hiding (assert)+import Test.Tasty.QuickCheck++import HSMT.SAT.Dimacs+import HSMT.SAT.Solver+import HSMT.SAT.Types++-- | A small random CNF in DIMACS numbering.+data SmallCnf = SmallCnf Int [[Int]]+ deriving (Show)++instance Arbitrary SmallCnf where+ arbitrary = do+ n <- chooseInt (1, 8)+ m <- chooseInt (0, 35)+ cs <- replicateM m $ do+ k <- chooseInt (1, 4)+ replicateM k $ do+ v <- chooseInt (1, n)+ s <- arbitrary+ pure (if s then v else negate v)+ pure (SmallCnf n cs)+ shrink (SmallCnf n cs) = [SmallCnf n cs' | cs' <- shrinkList (shrinkList (const [])) cs]++assignments :: Int -> [[Bool]]+assignments n = replicateM n [False, True]++satisfiesClause :: [Bool] -> [Int] -> Bool+satisfiesClause asg = any (\l -> (asg !! (abs l - 1)) == (l > 0))++bruteForce :: Int -> [[Int]] -> Maybe [Bool]+bruteForce n cs = case filter (\a -> all (satisfiesClause a) cs) (assignments n) of+ (a : _) -> Just a+ [] -> Nothing++loadSolver :: Int -> [[Int]] -> IO Solver+loadSolver n cs = do+ s <- newSolver+ _ <- loadCnf s (Cnf n cs)+ pure s++prop_agreesWithBruteForce :: SmallCnf -> Property+prop_agreesWithBruteForce (SmallCnf n cs) = monadicIO $ do+ s <- run (loadSolver n cs)+ r <- run (solve s)+ model <- run (getModel s)+ case bruteForce n cs of+ Nothing -> assert (r == Unsat)+ Just _ -> do+ assert (r == Sat)+ assert (all (satisfiesClause (take n model)) cs)++prop_assumptions :: SmallCnf -> Property+prop_assumptions (SmallCnf n cs) = forAll (assumptionsFor n) $ \as -> monadicIO $ do+ s <- run (loadSolver n cs)+ r <- run (solveWith s defaultSolveOptions (map toLit as))+ let withUnits = cs ++ [[a] | a <- as]+ case bruteForce n withUnits of+ Just _ -> do+ assert (r == Sat)+ model <- run (getModel s)+ assert (all (satisfiesClause (take n model)) withUnits)+ Nothing -> do+ assert (r == Unsat)+ failed <- run (failedAssumptions s)+ let failedInts = map fromLit failed+ -- The failed assumptions are assumptions, and are enough for unsat.+ assert (all (`elem` as) failedInts)+ assert (bruteForce n (cs ++ [[a] | a <- failedInts]) == Nothing)+ -- The solver stays usable after an Unsat under assumptions.+ r' <- run (solve s)+ assert (r' == if bruteForce n cs == Nothing then Unsat else Sat)+ where+ assumptionsFor k = do+ m <- chooseInt (0, k)+ nub <$> replicateM m (do v <- chooseInt (1, k); b <- arbitrary; pure (if b then v else negate v))++toLit :: Int -> Lit+toLit l = mkLit (abs l - 1) (l < 0)++fromLit :: Lit -> Int+fromLit l = if litSign l then negate (litVar l + 1) else litVar l + 1++-- | Pigeonhole principle: n+1 pigeons in n holes is unsatisfiable.+pigeonhole :: Int -> Cnf+pigeonhole n =+ let var p h = p * n + h + 1+ atLeastOne = [[var p h | h <- [0 .. n - 1]] | p <- [0 .. n]]+ atMostOne =+ [[negate (var p h), negate (var q h)] | h <- [0 .. n - 1], p <- [0 .. n], q <- [p + 1 .. n]]+ in Cnf ((n + 1) * n) (atLeastOne ++ atMostOne)++-- | A toy theory: at most one variable of a given set is true. It either+-- only reports conflicts or also propagates through lemmas.+amoTheory :: Solver -> [Var] -> Bool -> IO TheoryHooks+amoTheory s vars propagating = do+ st <- newIORef [[]]+ let check = do+ trues <- concat <$> readIORef st+ case trues of+ (a : b : _) -> pure (TheoryConflict [a, b])+ [t] | propagating -> do+ lemmas <- fmap concat . forM vars $ \v -> do+ val <- litValueNow s (posLit v)+ pure [[negLit v, litNeg t] | v /= litVar t, val == LUndef]+ pure (if null lemmas then TheoryOk else TheoryLemmas (map removable lemmas))+ _ -> pure TheoryOk+ pure+ TheoryHooks+ { thNewLevel = modifyIORef' st ([] :)+ , thBacktrack = \lvl -> modifyIORef' st (\xs -> drop (length xs - (lvl + 1)) xs)+ , thAssert = \l -> when (not (litSign l) && litVar l `elem` vars) $+ modifyIORef' st (\case (x : xs) -> (l : x) : xs; [] -> [[l]])+ , thPropagate = check+ , thFinalCheck = check+ }++prop_theory :: Bool -> SmallCnf -> Property+prop_theory propagating (SmallCnf n cs) = forAll (sublistOf [1 .. n]) $ \amo -> monadicIO $ do+ s <- run (loadSolver n cs)+ run (amoTheory s (map (subtract 1) amo) propagating >>= setTheory s)+ r <- run (solve s)+ let amoClauses = [[negate a, negate b] | a <- amo, b <- amo, a < b]+ case bruteForce n (cs ++ amoClauses) of+ Nothing -> assert (r == Unsat)+ Just _ -> do+ assert (r == Sat)+ model <- run (getModel s)+ assert (all (satisfiesClause (take n model)) (cs ++ amoClauses))++tests :: TestTree+tests =+ testGroup+ "SAT"+ [ testProperty "agrees with brute force" (withMaxSuccess 3000 prop_agreesWithBruteForce)+ , testProperty "assumptions and failed assumptions" (withMaxSuccess 2000 prop_assumptions)+ , testProperty "theory conflicts" (withMaxSuccess 1500 (prop_theory False))+ , testProperty "theory propagation lemmas" (withMaxSuccess 1500 (prop_theory True))+ , testCase "pigeonhole 7 is unsat" $ do+ s <- newSolver+ ok <- loadCnf s (pigeonhole 7)+ r <- if ok then solve s else pure Unsat+ r @?= Unsat+ , testCase "conflict limit gives Unknown" $ do+ s <- newSolver+ _ <- loadCnf s (pigeonhole 9)+ r <- solveWith s defaultSolveOptions {optConflictLimit = Just 10} []+ r @?= Unknown+ , testCase "incremental clause addition" $ do+ s <- loadSolver 3 [[1, 2, 3]]+ (@?= Sat) =<< solve s+ forM_ [[-1], [-2]] (addClause s . map toLit)+ (@?= Sat) =<< solve s+ (@?= True) =<< modelValue s 2+ _ <- addClause s [toLit (-3)]+ (@?= Unsat) =<< solve s+ , testCase "DIMACS parsing" $+ parseDimacs "c comment\np cnf 3 2\n1 -2 0\n2 3\n0\n"+ @?= Right (Cnf 3 [[1, -2], [2, 3]])+ ]
+ test/HSMT/SMTLibSpec.hs view
@@ -0,0 +1,189 @@+module HSMT.SMTLibSpec (tests) where++import Data.Bits (complement, rotateL, rotateR, xor, (.&.), (.|.))+import qualified Data.Text as T+import Data.Word (Word8)+import Test.QuickCheck hiding ((.&.))+import Test.Tasty+import Test.Tasty.HUnit+import Test.Tasty.QuickCheck (testProperty)++import qualified Data.Map.Strict as Map++import HSMT.Core.Eval+import HSMT.Core.Expr+import HSMT.Core.Op+import HSMT.Core.Sort+import HSMT.Core.Value+import HSMT.Gen.Expr+import HSMT.SMTLib.Parser+import HSMT.SMT.Engine (EngineResult (..))+import HSMT.SMTLib.Printer+import HSMT.SMTLib.Run+import HSMT.SMTLib.Syntax++tests :: TestTree+tests =+ testGroup+ "SMT-LIB"+ [ testCase "string escapes" $ do+ renderString "a\"b" @?= "\"a\"\"b\""+ renderString "\\" @?= "\"\\u{5c}\""+ renderString "é" @?= "\"\\u{e9}\""+ , testCase "symbol quoting" $ do+ renderSymbol "x!0" @?= "x!0"+ renderSymbol "a b" @?= "|a b|"+ renderSymbol "1x" @?= "|1x|"+ , testCase "negative literals and degenerate connectives" $ do+ renderExpr (constant (IntConst (-3))) @?= "(- 3)"+ renderExpr (App And []) @?= "true"+ renderExpr (App Or [constant (BoolConst True)]) @?= "true"+ , testCase "parse errors are reported" $ do+ assertLeft (parseScript "(assert x)")+ assertLeft (parseScript "(declare-const x Int) (assert x)")+ assertLeft (parseScript "(assert (and true)")+ , testCase "define-fun macros are expanded" $+ case parseScript "(define-fun f ((x Int)) Bool (> x 0)) (assert (f 3))" of+ Right [DefineFun {}, Assert e] -> evalExpr emptyInterpretation e @?= Right (VBool True)+ other -> assertFailure (show other)+ , testCase "string literal escapes are resolved" $+ case parseScript "(assert (= \"a\"\"\\u{5c}\\u00e9\" \"\"))" of+ Right [Assert (App Eq [App (StrConst s) [], _])] -> s @?= "a\"\\é"+ other -> assertFailure (show other)+ , testCase "let, define-const and define-sort" $+ case parseScript+ ( T.unlines+ [ "(define-sort Byte () (_ BitVec 8))"+ , "(define-const k Byte #x0f)"+ , "(declare-const x Int)"+ , "(assert (let ((x 2) (y x)) (let ((x (+ x 1))) (and (= x 3) (= y x) (= k (bvand k #xff))))))"+ ]+ ) of+ Right [DefineFun {}, DeclareFun _, Assert e] ->+ -- The inner y is the declared x, not a let-bound one.+ let x3 = Interpretation (Map.singleton (Symbol "x" [] IntSort) (constInterp (VInt 3))) z z Map.empty+ z = constInterp (VInt 0)+ in evalExpr x3 e @?= Right (VBool True)+ other -> assertFailure (show other)+ , testCase "declarations are scoped by push and pop" $ do+ assertRight (parseScript "(push 1) (declare-const x Int) (pop 1) (declare-const x Bool) (assert x)")+ assertLeft (parseScript "(push 1) (declare-const y Int) (pop 1) (assert (> y 0))")+ assertLeft (parseScript "(push 1) (pop 2)")+ assertRight (parseScript "(declare-const y Int) (reset) (declare-const y Bool)")+ , testProperty "derived bit-vector operators" prop_bvDerived+ , testCase "script responses" $ do+ rs <-+ runScriptResponses True $+ T.unlines+ [ "(set-option :print-success true)"+ , "(declare-fun f (Int) Int)"+ , "(declare-const x Int)"+ , "(assert (and (= (f x) 5) (= x 2)))"+ , "(get-model)"+ , "(check-sat)"+ , "(get-value ((f x) (+ x 1)))"+ , "(assert (> y 0))"+ , "(get-info :reason-unknown)"+ , "(get-info :error-behavior)"+ , "(get-info :no-such-key)"+ , "(get-assertions)"+ , "(echo \"ok\")"+ , "(exit)"+ , "(check-sat)"+ ]+ map renderResponse rs+ @?= [ "success"+ , "success"+ , "success"+ , "success"+ , "(error \"no model available\")"+ , "sat"+ , "(((f x) 5)\n ((+ x 1) 3))"+ , "(error \"unknown symbol: y in (assert (> y 0))\")"+ , "(error \"the last check did not answer unknown\")"+ , "(:error-behavior continued-execution)"+ , "unsupported"+ , "((and (= (f x) 5) (= x 2)))"+ , "\"ok\""+ , "success"+ ]+ , testCase "get-model answers a model that checks" $ do+ let decls =+ [ "(declare-sort U 0)"+ , "(declare-fun g (U) U)"+ , "(declare-const a U)"+ , "(declare-const s String)"+ , "(declare-const arr (Array Int Int))"+ ]+ constraints =+ [ "(assert (distinct a (g a) (g (g a))))"+ , "(assert (= (str.len s) (select arr 4)))"+ , "(assert (> (select arr 4) 2))"+ ]+ model <-+ runScriptResponses True (T.unlines (decls <> constraints <> ["(check-sat)", "(get-model)"])) >>= \case+ [CheckResult _, m@(Model _ _)] -> pure (renderResponse m)+ other -> assertFailure (show other)+ -- The model, read as definitions, satisfies the constraints.+ let defs = T.unlines (drop 1 (init (T.lines model)))+ check = T.unlines ["(declare-sort U 0)", defs] <> T.unlines constraints <> "(check-sat)"+ runScriptText True check >>= \case+ Right [r] -> show r `seq` assertBool (T.unpack check) (isSat r)+ other -> assertFailure (T.unpack check <> show other)+ , testProperty "print/parse round trip" prop_roundTrip+ ]+ where+ assertLeft = either (const (pure ())) (assertFailure . ("expected an error, got " <>) . show)+ assertRight = either (assertFailure . T.unpack) (const (pure ()))+ isSat = \case+ ESat _ -> True+ _ -> False++-- | The operators the parser defines through others agree with+-- "Data.Bits".+prop_bvDerived :: Word8 -> Word8 -> Int -> Property+prop_bvDerived a b k0 =+ conjoin+ [ check ("((_ rotate_left " <> show k <> ") " <> lit a <> ")") (rotateL a k)+ , check ("((_ rotate_right " <> show k <> ") " <> lit a <> ")") (rotateR a k)+ , check ("(bvnand " <> lit a <> " " <> lit b <> ")") (complement (a .&. b))+ , check ("(bvnor " <> lit a <> " " <> lit b <> ")") (complement (a .|. b))+ , check ("(bvxnor " <> lit a <> " " <> lit b <> ")") (complement (a `xor` b))+ , value ("(bvcomp " <> lit a <> " " <> lit b <> ")") === Right (VBV 1 (if a == b then 1 else 0))+ , value ("((_ repeat 2) " <> lit a <> ")") === Right (VBV 16 (toInteger a * 257))+ ]+ where+ k = k0 `mod` 20+ lit x = "(_ bv" <> show x <> " 8)"+ check t r = counterexample t (value t === Right (VBV 8 (toInteger r)))+ value t = case parseScript (T.pack ("(define-const v (_ BitVec " <> width t <> ") " <> t <> ")")) of+ Right [DefineFun _ _ e] -> either (Left . show) Right (evalExpr emptyInterpretation e)+ other -> Left (show other)+ width t+ | "(bvcomp" `isPrefix` t = "1"+ | "((_ repeat" `isPrefix` t = "16"+ | otherwise = "8"+ isPrefix p t = take (length p) t == p++-- | Printing a problem and parsing it back gives the same assertions, up to+-- the expansions the printer performs.+prop_roundTrip :: Property+prop_roundTrip =+ forAllShrink (genProblem allTheoriesConfig) shrinkProblem $ \as ->+ let txt = renderScript (problemScript as)+ in counterexample (show txt) $ case parseScript txt of+ Left err -> counterexample (show err) False+ Right cmds -> [e | Assert e <- cmds] === map normalize as++-- | The printer expands record updates and degenerate connectives, and the+-- parser reads the negation of a numeral as a negative literal.+normalize :: Expr -> Expr+normalize (App Neg [App (IntConst n) []]) | n >= 0 = constant (IntConst (negate n))+normalize (App op args) = case (op, map normalize args) of+ (And, []) -> constant (BoolConst True)+ (And, [a]) -> a+ (Or, []) -> constant (BoolConst False)+ (Or, [a]) -> a+ (RecordSet f, [r, v]) | RecordSort fs <- sortOfExpr r ->+ App (RecordMk (map fst fs)) [if g == f then v else App (RecordGet g) [r] | (g, _) <- fs]+ (_, args') -> App op args'
+ test/HSMT/StringSpec.hs view
@@ -0,0 +1,95 @@+module HSMT.StringSpec (tests) where++import Data.Text (Text)+import qualified Data.Text as T+import Test.Tasty+import Test.Tasty.HUnit++import HSMT.SMT.Engine+import HSMT.SMTLib.Run++tests :: TestTree+tests =+ testGroup+ "Strings"+ [ testCase "concatenation and length" $ do+ expect (base <> ["(assert (= (str.++ x \"b\") (str.++ \"a\" y)))", "(assert (> (str.len x) 2))"]) ["sat"]+ expect (base <> ["(assert (= (str.++ x y) \"abc\"))", "(assert (= (str.len x) (str.len y)))"]) ["unsat"]+ -- Lengths alone refute it, for strings of any length.+ expect (base <> ["(assert (= (str.++ x x) (str.++ y \"a\" y)))"]) ["unsat"]+ expect (base <> ["(assert (= (str.len (str.++ x y)) 20))"]) ["sat"]+ , testCase "substrings and characters" $ do+ expect (base <> ["(assert (= (str.substr x 1 2) \"bc\"))", "(assert (= (str.at x 0) \"a\"))", "(assert (= (str.len x) 3))"]) ["sat"]+ expect (base <> ["(assert (= x \"abc\"))", "(assert (not (= (str.substr x 1 5) \"bc\")))"]) ["unsat"]+ expect (base <> ["(assert (= x \"abc\"))", "(assert (not (= (str.at x 3) \"\")))"]) ["unsat"]+ expect (base <> ["(assert (not (= (str.substr x (- 1) 2) \"\")))"]) ["unsat"]+ , testCase "search" $ do+ expect (base <> ["(assert (str.contains x \"ab\"))", "(assert (str.prefixof \"b\" x))", "(assert (str.suffixof \"a\" x))"]) ["sat"]+ expect (base <> ["(assert (str.contains x \"ab\"))", "(assert (< (str.len x) 2))"]) ["unsat"]+ expect (base <> ["(assert (= (str.indexof x \"a\" 0) 2))", "(assert (= (str.at x 1) \"a\"))"]) ["unsat"]+ expect (base <> ["(assert (= (str.indexof \"aba\" x 1) 2))"]) ["sat"]+ expect (base <> ["(assert (= (str.replace x \"ab\" \"c\") \"xcy\"))", "(assert (= (str.substr x 1 2) \"aa\"))"]) ["unsat"]+ , testCase "conversions" $ do+ expect (base <> ["(assert (= (str.to_int x) 123))", "(assert (= (str.len x) 5))"]) ["sat"]+ expect (base <> ["(assert (= (str.from_int n) \"012\"))"]) ["unsat"]+ expect (base <> ["(assert (= (str.from_int n) x))", "(assert (str.prefixof \"4\" x))", "(assert (< n 50))", "(assert (> n 40))"]) ["sat"]+ expect (base <> ["(assert (= (str.to_int x) (- 2)))"]) ["unsat"]+ , testCase "lexicographic order" $ do+ expect (base <> ["(assert (str.< x y))", "(assert (str.< y \"b\"))", "(assert (str.prefixof \"a\" x))"]) ["sat"]+ expect (base <> ["(assert (str.< x y))", "(assert (str.< y x))"]) ["unsat"]+ expect (base <> ["(assert (str.<= x \"\"))", "(assert (not (= x \"\")))"]) ["unsat"]+ , testCase "uninterpreted functions over strings" $ do+ let funs = base <> ["(declare-fun f (String) Int)"]+ expect (funs <> ["(assert (= x (str.++ \"a\" y)))", "(assert (= y \"b\"))", "(assert (distinct (f x) (f \"ab\")))"]) ["unsat"]+ expect (funs <> ["(assert (distinct (f x) (f y)))", "(assert (= (str.len x) (str.len y)))"]) ["sat"]+ , testCase "regular expressions" $ do+ let digits = "(re.+ (re.range \"0\" \"9\"))"+ expect (base <> ["(assert (str.in_re x (re.++ (str.to_re \"id\") " <> digits <> ")))", "(assert (> (str.len x) 4))"]) ["sat"]+ -- (ab)* has only even lengths.+ expect (base <> ["(assert (str.in_re x (re.* (str.to_re \"ab\"))))", "(assert (= (str.len x) 7))"]) ["unsat"]+ expect (base <> ["(assert (str.in_re x (re.* (str.to_re \"ab\"))))", "(assert (str.contains x \"bb\"))", "(assert (< (str.len x) 20))"]) ["unsat"]+ -- Without the length limit the refutation needs strings longer than+ -- the bound: the occurrence of bb may lie past it.+ r0 <- run (base <> ["(assert (str.in_re x (re.* (str.to_re \"ab\"))))", "(assert (str.contains x \"bb\"))"])+ r0 @?= ["unknown: string length bound reached"]+ -- Complement and intersection.+ expect (base <> ["(assert (str.in_re x (re.inter (re.comp (re.++ re.all (str.to_re \"a\") re.all)) ((_ re.^ 3) re.allchar))))", "(assert (str.prefixof \"b\" x))"]) ["sat"]+ expect (base <> ["(assert (str.in_re x (re.diff (re.* (re.range \"a\" \"b\")) (re.* (str.to_re \"a\")))))", "(assert (not (str.contains x \"b\")))", "(assert (<= (str.len x) 8))"]) ["unsat"]+ -- Membership is exact for strings in the bound, also when negated.+ expect (base <> ["(assert (not (str.in_re x ((_ re.loop 1 3) (str.to_re \"a\")))))", "(assert (str.in_re x (re.+ (str.to_re \"a\"))))", "(assert (< (str.len x) 4))"]) ["unsat"]+ -- Relations between the languages hold for any length: the last+ -- character cannot be both a and b.+ expect (base <> ["(assert (str.in_re x (re.++ re.all (str.to_re \"a\"))))", "(assert (str.in_re x (re.++ re.all (str.to_re \"b\"))))"]) ["unsat"]+ expect (base <> ["(assert (str.in_re x (re.* (str.to_re \"ab\"))))", "(assert (not (str.in_re x (re.* (re.range \"a\" \"b\")))))"]) ["unsat"]+ -- The shortest member is longer than the bound.+ expect (base <> ["(assert (str.in_re x ((_ re.^ 40) (str.to_re \"a\"))))", "(assert (str.in_re x (re.* (str.to_re \"b\"))))"]) ["unsat"]+ -- Ground regular expressions are evaluated, including equalities.+ expect ["(assert (= (re.* (re.* (str.to_re \"a\"))) (re.* (str.to_re \"a\"))))"] ["sat"]+ expect ["(assert (str.in_re \"aab\" (re.++ (re.* (str.to_re \"a\")) (str.to_re \"c\"))))"] ["unsat"]+ -- Regular expressions that depend on variables are not supported.+ r <- run (base <> ["(assert (str.in_re x (re.* (str.to_re y))))"])+ r @?= ["unknown: regular expressions must be ground (str.to_re of string literals)"]+ , testCase "beyond the length bound" $ do+ -- x ++ "a" = "b" ++ x has no solution of any length; bounded+ -- reasoning cannot refute it.+ r <- run (base <> ["(assert (= (str.++ x \"a\") (str.++ \"b\" x)))"])+ r @?= ["unknown: string length bound reached"]+ ]+ where+ base = ["(declare-const x String)", "(declare-const y String)", "(declare-const n Int)"]++-- | Run a script (with model validation) and compare its answers; a final+-- @check-sat@ is appended.+expect :: [Text] -> [Text] -> Assertion+expect cmds answers = run cmds >>= (@?= answers)++run :: [Text] -> IO [Text]+run cmds =+ runScriptText True (T.unlines (cmds <> ["(check-sat)"])) >>= \case+ Left err -> assertFailure (T.unpack err) >> pure []+ Right rs -> pure (map answer rs)+ where+ answer = \case+ ESat _ -> "sat"+ EUnsat _ -> "unsat"+ EUnknown why -> "unknown: " <> why
+ test/HSMT/TutorialSpec.hs view
@@ -0,0 +1,167 @@+{-# LANGUAGE OverloadedLabels #-}++-- | The examples of "HSMT.Tutorial", with the answers it states.+module HSMT.TutorialSpec (tests) where++import Data.Char (isAsciiLower, isAsciiUpper, isDigit)+import Data.Text (Text)+import qualified Data.Text as T+import System.Directory (findExecutable)+import System.Environment (lookupEnv)+import Test.Tasty+import Test.Tasty.HUnit hiding (assert)++import HSMT++example :: IO (Maybe (Integer, Integer))+example = runSMT defaultConfig $ do+ x <- declare @IntS "x"+ y <- declare @IntS "y"+ assert (x + y .== 10)+ assert (x - y .== 4)+ checkSat >>= \case+ Sat m -> pure (Just (eval m x, eval m y))+ _ -> pure Nothing++multipleOfSix :: IO Bool+multipleOfSix = runSMT defaultConfig $ do+ n <- declare @IntS "n"+ assert (n .> 7 .&& n .< 9)+ assert (n `imod` 2 .== 0 .&& n `imod` 3 .== 0)+ checkSat >>= \case+ Unsat _ -> pure False+ _ -> pure True++powerOfTwo :: IO (Maybe (BitVector 16))+powerOfTwo = runSMT defaultConfig $ do+ x <- declare @(BVS 16) "x"+ assert (bvAnd x (x - 1) .== 0)+ assert (bvUGt x 1000)+ assert (bvULt x 2000)+ checkSat >>= \case+ Sat m -> pure (Just (eval m x))+ _ -> pure Nothing++swapTwice :: IO Bool+swapTwice = runSMT defaultConfig $ do+ a <- declare @(ArrayS IntS IntS) "a"+ i <- declare @IntS "i"+ j <- declare @IntS "j"+ let swap b = store (store b i (select b j)) j (select b i)+ assert (swap (swap a) ./= a)+ checkSat >>= \case+ Unsat _ -> pure True+ _ -> pure False++greeting :: IO (Maybe Text)+greeting = runSMT defaultConfig $ do+ name <- declare @StringS "name"+ let s = "hello, " <+> name+ assert (strLen s .== 10)+ assert (suffixOf "!" name .&& contains name "b")+ checkSat >>= \case+ Sat m -> pure (Just (eval m s))+ _ -> pure Nothing++identifier :: IO (Maybe Text)+identifier = runSMT defaultConfig $ do+ s <- declare @StringS "s"+ let letter = reUnion [reRange 'a' 'z', reRange 'A' 'Z']+ ident = reConcat [letter, reStar (reUnion [letter, reRange '0' '9'])]+ assert (inRe s (reInter [ident, reLoop 3 5 reAllChar]))+ assert (notB (inRe s (reUnion ["else", "then"])))+ assert (contains s "9")+ checkSat >>= \case+ Sat m -> pure (Just (eval m s))+ _ -> pure Nothing++congruence :: IO Bool+congruence = runSMT defaultConfig $ do+ f <- declareFun @'[UninterpS "U"] @(UninterpS "U") "f"+ a <- declare @(UninterpS "U") "a"+ assert (f (f (f a)) .== a)+ assert (f (f (f (f (f a)))) .== a)+ assert (f a ./= a)+ checkSat >>= \case+ Unsat _ -> pure True+ _ -> pure False++type Point = RecordS '[ '("x", IntS), '("y", IntS)]++reflection :: IO (Maybe (Integer, Integer))+reflection = runSMT defaultConfig $ do+ p <- declare @Point "p"+ let q = record (#x := p ! #y :& #y := p ! #x :& FNil)+ assert (q .== setField #x 3 p)+ assert (p ! #x .> 0)+ checkSat >>= \case+ Sat m -> pure (Just (field #x (eval m p), field #y (eval m p)))+ _ -> pure Nothing++notReflexive :: IO (Maybe Bool)+notReflexive = runSMT defaultConfig $ do+ x <- declare @Float32S "x"+ assert (notB (fpEq x x))+ checkSat >>= \case+ Sat m -> pure (Just (isNaN (toFloat (eval m x))))+ _ -> pure Nothing++conflicting :: IO [Int]+conflicting = runSMT defaultConfig {cfgMinimizeCores = True} $ do+ x <- declare @IntS "x"+ labels <- mapM (\i -> declare @BoolS ("c" <> T.pack (show i))) [0 .. 3 :: Int]+ let constraints = [x .> 10, x .< 20, x .== 5, x .> 0]+ sequence_ [assert (l .=> c) | (l, c) <- zip labels constraints]+ checkSatAssuming labels >>= \case+ Unsat core -> pure [i | (i, l) <- zip [0 ..] labels, l `elem` coreAssumptions core]+ _ -> pure []++viaZ3 :: IO (Maybe (Integer, Integer))+viaZ3 = runSMT defaultConfig {cfgBackend = External z3Backend} $ do+ x <- declare @IntS "x"+ y <- declare @IntS "y"+ assert (x * y .== 12 .&& x .> y .&& y .> 1)+ checkSat >>= \case+ Sat m -> pure (Just (eval m x, eval m y))+ _ -> pure Nothing++-- | Whether Z3 can be found as 'z3Backend' finds it.+haveZ3 :: IO Bool+haveZ3 =+ lookupEnv "HSMT_Z3" >>= \case+ Just p | not (null p) -> pure True+ _ -> (/= Nothing) <$> findExecutable "z3"++isAsciiLetter :: Char -> Bool+isAsciiLetter c = isAsciiLower c || isAsciiUpper c++tests :: TestTree+tests =+ testGroup+ "tutorial"+ [ testCase "getting started" $ example >>= (@?= Just (7, 3))+ , testCase "integers" $ multipleOfSix >>= (@?= False)+ , testCase "bit-vectors" $ powerOfTwo >>= (@?= Just (BitVector 1024))+ , testCase "arrays" $ swapTwice >>= (@?= True)+ , testCase "strings" $+ greeting >>= \case+ Just s -> do+ T.length s @?= 10+ assertBool (show s) ("hello, " `T.isPrefixOf` s && "!" `T.isSuffixOf` s && T.isInfixOf "b" (T.drop 7 s))+ Nothing -> assertFailure "no model"+ , testCase "regular expressions" $+ identifier >>= \case+ Just s -> assertBool (show s) $+ T.length s >= 3 && T.length s <= 5 && T.any (== '9') s+ && isAsciiLetter (T.head s) && T.all (\c -> isAsciiLetter c || isDigit c) s+ Nothing -> assertFailure "no model"+ , testCase "uninterpreted functions" $ congruence >>= (@?= True)+ , testCase "records" $ reflection >>= (@?= Just (3, 3))+ , testCase "floating point" $ notReflexive >>= (@?= Just True)+ , testCase "unsatisfiable cores" $ conflicting >>= (@?= [0, 2])+ , testCase "external solvers (skipped without z3)" $ do+ z3 <- haveZ3+ if z3+ then viaZ3 >>= \r -> assertBool (show r) (r `elem` [Just (6, 2), Just (4, 3)])+ else pure ()+ ]
+ test/Main.hs view
@@ -0,0 +1,60 @@+module Main (main) where++import System.Directory (findExecutable)+import System.Environment (lookupEnv)+import Test.Tasty++import HSMT (Backend (..), Config (..), defaultConfig, z3Backend)++import qualified HSMT.APISpec+import qualified HSMT.ArraySpec+import qualified HSMT.EUFSpec+import qualified HSMT.BVSpec+import qualified HSMT.EvalSpec+import qualified HSMT.FloatSpec+import qualified HSMT.IncrementalSpec+import qualified HSMT.LIASpec+import qualified HSMT.RecordSpec+import qualified HSMT.RegexSpec+import qualified HSMT.RegressionSpec+import qualified HSMT.SATSpec+import qualified HSMT.SMTLibSpec+import qualified HSMT.StringSpec+import qualified HSMT.TutorialSpec++main :: IO ()+main = do+ regressions <- HSMT.RegressionSpec.tests+ z3 <-+ lookupEnv "HSMT_Z3" >>= \case+ Just p | not (null p) -> pure (Just p)+ _ -> findExecutable "z3"+ external <- case z3 of+ Nothing -> pure []+ Just _ -> do+ let cfg = defaultConfig {cfgBackend = External z3Backend}+ files <- HSMT.RegressionSpec.testsWith (cfgBackend cfg)+ pure+ [ testGroup+ "external backend (z3)"+ [HSMT.APISpec.testsWith cfg, HSMT.IncrementalSpec.testsWith cfg, files]+ ]+ defaultMain $+ testGroup "hsmt" $+ [ HSMT.SATSpec.tests+ , HSMT.EvalSpec.tests+ , HSMT.APISpec.tests+ , HSMT.EUFSpec.tests+ , HSMT.LIASpec.tests+ , HSMT.BVSpec.tests+ , HSMT.ArraySpec.tests+ , HSMT.RecordSpec.tests+ , HSMT.StringSpec.tests+ , HSMT.RegexSpec.tests+ , HSMT.FloatSpec.tests+ , HSMT.SMTLibSpec.tests+ , HSMT.IncrementalSpec.tests+ , HSMT.TutorialSpec.tests+ , regressions+ ]+ <> external
+ test/regressions/euf-pigeonhole-bv1.smt2 view
@@ -0,0 +1,13 @@+; Three distinct values do not fit in a 1-bit domain; f is injective on them.+; expected: unsat sat+(set-logic QF_UFBV)+(declare-fun f ((_ BitVec 1)) (_ BitVec 1))+(declare-const a (_ BitVec 1))+(declare-const b (_ BitVec 1))+(push 1)+(assert (distinct (f a) (f b) #b0))+(assert (not (= (f a) #b1)))+(check-sat)+(pop 1)+(assert (distinct a b))+(check-sat)
+ test/regressions/incremental-constant-bool-record.smt2 view
@@ -0,0 +1,14 @@+; Incremental session: a Boolean term with a constant literal, registered in a later check, must reach congruence closure.+; expected: sat unsat+(set-logic ALL)+(declare-sort U 0)+(declare-datatypes ((|Record{u:U,p:Bool}| 0)) (((|mk-Record{u:U,p:Bool}| (|Record{u:U,p:Bool}.u| U) (|Record{u:U,p:Bool}.p| Bool)))))+(declare-datatypes ((|Record{c:Bool,d:Bool}| 0)) (((|mk-Record{c:Bool,d:Bool}| (|Record{c:Bool,d:Bool}.c| Bool) (|Record{c:Bool,d:Bool}.d| Bool)))))+(declare-fun a1 () U)+(declare-fun b0 () |Record{u:U,p:Bool}|)+(declare-fun e0 () |Record{c:Bool,d:Bool}|)+(assert (= (|mk-Record{u:U,p:Bool}| a1 false) b0))+(check-sat)+(assert (= (|mk-Record{c:Bool,d:Bool}| (|Record{c:Bool,d:Bool}.c| e0) (not true)) e0))+(assert (|Record{c:Bool,d:Bool}.d| e0))+(check-sat)
+ test/regressions/incremental-constant-bool-store-bv.smt2 view
@@ -0,0 +1,9 @@+; Incremental session: a Boolean term with a constant literal, registered in a later check, must reach congruence closure.+; expected: sat unsat+(set-logic ALL)+(declare-fun b0 () (_ BitVec 4))+(declare-fun e0 () (Array (_ BitVec 4) Bool))+(assert (= e0 ((as const (Array (_ BitVec 4) Bool)) false)))+(check-sat)+(assert (= (store ((as const (Array (_ BitVec 4) Bool)) false) b0 (bvsge b0 b0)) e0))+(check-sat)
+ test/regressions/incremental-constant-bool-store-uf.smt2 view
@@ -0,0 +1,13 @@+; Incremental session: a Boolean term with a constant literal, registered in a later check, must reach congruence closure.+; expected: sat unsat+(set-logic ALL)+(declare-sort U 0)+(declare-fun a1 () U)+(declare-fun a2 () U)+(declare-fun b1 () (Array U U))+(declare-fun c1 () (Array U Bool))+(declare-fun p0 () Bool)+(assert (= b1 ((as const (Array U U)) a2)))+(check-sat)+(assert (= (store c1 a1 (xor p0 p0)) (store c1 a1 (not false))))+(check-sat)
+ test/regressions/z3-finite-index-array-eq.smt2 view
@@ -0,0 +1,18 @@+; Found by the differential suite: Z3 4.16.0 answers sat to these queries,+; although the arrays differ at some index (#b00 in the first two, #b10 in+; the third). With sat.smt=true it answers the first two correctly but not+; the third. Kept to pin down the reference semantics of extensional array+; equality over finite index sorts.+; allow-unknown+; expected: unsat unsat unsat+(set-logic ALL)+(push 1)+(assert (= (store ((as const (Array (_ BitVec 2) Bool)) false) (_ bv2 2) true) (store ((as const (Array (_ BitVec 2) Bool)) true) (_ bv1 2) false)))+(check-sat)+(pop 1)+(push 1)+(assert (not (distinct (store ((as const (Array (_ BitVec 2) Bool)) false) (_ bv2 2) true) ((as const (Array (_ BitVec 2) Bool)) true) (store ((as const (Array (_ BitVec 2) Bool)) true) (_ bv1 2) false))))+(check-sat)+(pop 1)+(assert (= (store (store ((as const (Array (_ BitVec 2) Bool)) false) (_ bv0 2) true) (_ bv1 2) true) ((as const (Array (_ BitVec 2) Bool)) true)))+(check-sat)
+ test/regressions/z3-finite-record-index-array-eq.smt2 view
@@ -0,0 +1,12 @@+; Found by the differential suite: Z3 4.16.0 answers sat to the second+; query, although the index sort has four values and only two are written,+; so the array cannot equal the constant 2 (same error as in+; z3-finite-index-array-eq.smt2, with a record index).+; expected: sat unsat+(set-logic ALL)+(declare-datatypes ((B 0)) (((mkB (c Bool) (d (_ BitVec 1))))))+(declare-fun a0 () Int)+(declare-fun d1 () B)+(check-sat)+(assert (= ((as const (Array B Int)) 2) (store (store ((as const (Array B Int)) (- 1)) (mkB false (_ bv0 1)) a0) d1 a0)))+(check-sat)