hsmt-0.1.0.0: src/HSMT/Theory/EUF.hs
-- | 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)