hsmt-0.1.0.0: src/HSMT/SMT/Engine.hs
-- | 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]
_ -> []