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:
build-depends: hsmt
To install the command-line tool:
cabal install hsmt
Quick start
{-# 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:
runSMT starts a solver instance with a Config.
defaultConfig is a good starting point.
declare introduces a constant of a sort. You choose the sort with a
type application (@IntS, @BoolS, @(BVS 8), ...).
assert adds a Boolean expression to the assertions.
checkSat returns one of three results:
Sat with a model
Unsat with an unsatisfiable core
Unknown with the reason the solver gave up
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:
{-# LANGUAGE DataKinds, LambdaCase, OverloadedLabels, OverloadedStrings, TypeApplications #-}
import Data.Text (Text)
import HSMT
Booleans
-- 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:
-- 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
-- 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
-- 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
-- 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
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
-- 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:
-- 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:
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:
(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.