packages feed

hsmt-0.1.0.0: src/HSMT/SAT/Solver.hs

{-# LANGUAGE BangPatterns #-}

-- | A CDCL SAT solver with support for theory solvers (DPLL(T)).
--
-- Features: two watched literals, first-UIP clause learning with local
-- clause minimization, VSIDS branching with phase saving, Luby restarts,
-- LBD-based deletion of learnt clauses, incremental solving under
-- assumptions with failed-assumption extraction, and clause addition from
-- theories during search.
module HSMT.SAT.Solver
  ( Solver
  , newSolver
  , newVar
  , setPhase
  , numVars
  , addClause
  , solve
  , solveWith
  , SolveOptions (..)
  , defaultSolveOptions
  , modelValue
  , getModel
  , litValueNow
  , failedAssumptions
  , deliveredLits
  , setTheory
  , isOkay
  , decisionLevel
  , Stats (..)
  , getStats
  ) where

import Control.Monad
import Data.Bits (shiftR, xor, (.&.), (.|.))
import Data.IORef
import Data.Int (Int8)
import qualified Data.IntSet as IntSet
import Data.List (nub, sortOn)
import qualified Data.Vector as V
import GHC.Clock (getMonotonicTime)
import qualified Data.Vector.Unboxed.Mutable as MU

import HSMT.SAT.Types
import HSMT.Util.GrowVec

-------------------------------------------------------------------------------
-- Clauses

-- | A clause is a mutable vector of integers with a two-slot header:
-- slot 0 holds flags, slot 1 the LBD, and literals start at slot 2.
-- The first two literals are the watched ones.
data Clause = Clause
  { clId :: !Int
  , clData :: !(MU.IOVector Int)
  }

instance Eq Clause where
  a == b = clId a == clId b

flagLearnt, flagDeleted :: Int
flagLearnt = 1
flagDeleted = 2

clauseSize :: Clause -> Int
clauseSize c = MU.length (clData c) - 2
{-# INLINE clauseSize #-}

clauseLit :: Clause -> Int -> IO Int
clauseLit c i = MU.unsafeRead (clData c) (i + 2)
{-# INLINE clauseLit #-}

clauseLits :: Clause -> IO [Int]
clauseLits c = mapM (clauseLit c) [0 .. clauseSize c - 1]

isDeleted :: Clause -> IO Bool
isDeleted c = do
  f <- MU.unsafeRead (clData c) 0
  pure (f .&. flagDeleted /= 0)
{-# INLINE isDeleted #-}

isNoClause :: Clause -> Bool
isNoClause c = clId c < 0
{-# INLINE isNoClause #-}

-------------------------------------------------------------------------------
-- Solver state

-- | Search statistics, cumulative over the life of a solver.
data Stats = Stats
  { statConflicts :: !Int
    -- ^ Conflicts encountered.
  , statDecisions :: !Int
    -- ^ Branching decisions (assumptions not included).
  , statPropagations :: !Int
    -- ^ Literals propagated.
  , statRestarts :: !Int
    -- ^ Restarts performed.
  , statLearnts :: !Int
    -- ^ Learnt clauses currently in the database.
  }
  deriving (Eq, Show)

-- | Mutable state of a CDCL solver instance.
data Solver = Solver
  { sOk :: !(IORef Bool)
  , sNumVars :: !(IORef Int)
  , sAssigns :: !(UVec Int8)
  , sLevel :: !(UVec Int)
  , sReason :: !(BVec Clause)
  , sPolarity :: !(UVec Bool)
  , sActivity :: !(UVec Double)
  , sSeen :: !(UVec Bool)
  , sWatches :: !(BVec (BVec Clause))
  , sTrail :: !(UVec Int)
  , sTrailLim :: !(UVec Int)
  , sQHead :: !(IORef Int)
  , sTheoryHead :: !(IORef Int)
  , sClauses :: !(BVec Clause)
  , sLearnts :: !(BVec Clause)
  , sNextId :: !(IORef Int)
  , sHeap :: !(UVec Int)
  , sHeapIndex :: !(UVec Int)
  , sVarInc :: !(IORef Double)
  , sTheory :: !(IORef (Maybe TheoryHooks))
  , sLemmaQueue :: !(IORef [Lemma])
    -- ^ Permanent theory lemmas not added yet because an earlier lemma of
    -- the same batch was conflicting.
  , sModel :: !(UVec Int8)
  , sFailed :: !(IORef [Lit])
  , sMaxLearnts :: !(IORef Double)
  , sNoClause :: !Clause
  , sCounters :: !(MU.IOVector Int)
    -- ^ Conflicts, decisions, propagations and restarts.
  }

-- | Create a solver with no variables and no clauses.
newSolver :: IO Solver
newSolver = do
  noData <- MU.replicate 2 0
  Solver
    <$> newIORef True
    <*> newIORef 0
    <*> newUVec 64
    <*> newUVec 64
    <*> newBVec 64
    <*> newUVec 64
    <*> newUVec 64
    <*> newUVec 64
    <*> newBVec 128
    <*> newUVec 64
    <*> newUVec 64
    <*> newIORef 0
    <*> newIORef 0
    <*> newBVec 64
    <*> newBVec 64
    <*> newIORef 0
    <*> newUVec 64
    <*> newUVec 64
    <*> newIORef 1
    <*> newIORef Nothing
    <*> newIORef []
    <*> newUVec 64
    <*> newIORef []
    <*> newIORef 2000
    <*> pure (Clause (-1) noData)
    <*> MU.replicate 4 0

-- | Install theory hooks. Must be called before solving.
setTheory :: Solver -> TheoryHooks -> IO ()
setTheory s th = writeIORef (sTheory s) (Just th)

-- | 'False' once the clause set is known to be unsatisfiable at decision
-- level 0 (independently of assumptions).
isOkay :: Solver -> IO Bool
isOkay = readIORef . sOk

-- | Number of variables created so far.
numVars :: Solver -> IO Int
numVars = readIORef . sNumVars

-- | Snapshot of the solver statistics.
getStats :: Solver -> IO Stats
getStats s =
  Stats
    <$> MU.read (sCounters s) cConflicts
    <*> MU.read (sCounters s) cDecisions
    <*> MU.read (sCounters s) cPropagations
    <*> MU.read (sCounters s) cRestarts
    <*> bSize (sLearnts s)

cConflicts, cDecisions, cPropagations, cRestarts :: Int
cConflicts = 0
cDecisions = 1
cPropagations = 2
cRestarts = 3

bumpStat :: Solver -> Int -> IO ()
bumpStat s c = MU.unsafeModify (sCounters s) (+ 1) c
{-# INLINE bumpStat #-}

-- | Create a fresh variable. Safe to call during search (from theory hooks).
newVar :: Solver -> IO Var
newVar s = do
  v <- readIORef (sNumVars s)
  writeIORef (sNumVars s) (v + 1)
  uPush (sAssigns s) 0
  uPush (sLevel s) 0
  bPush (sReason s) (sNoClause s)
  uPush (sPolarity s) True
  uPush (sActivity s) 0
  uPush (sSeen s) False
  uPush (sModel s) 0
  uPush (sHeapIndex s) (-1)
  newBVec 4 >>= bPush (sWatches s)
  newBVec 4 >>= bPush (sWatches s)
  heapInsert s v
  pure v

-- | Set the value the variable is tried with first when it is decided.
-- Phase saving overrides it once the variable has been assigned.
setPhase :: Solver -> Var -> Bool -> IO ()
setPhase s v b = uWrite (sPolarity s) v (not b)

-------------------------------------------------------------------------------
-- Assignment

-- | The current decision level (0 outside of search).
decisionLevel :: Solver -> IO Int
decisionLevel s = uSize (sTrailLim s)
{-# INLINE decisionLevel #-}

-- | Value of a literal as 1 (true), -1 (false) or 0 (unassigned).
litVal :: Solver -> Int -> IO Int8
litVal s l = do
  a <- uRead (sAssigns s) (l `shiftR` 1)
  pure (if odd l then negate a else a)
{-# INLINE litVal #-}

-- | Current value of a literal (during search or right after adding
-- clauses).
litValueNow :: Solver -> Lit -> IO LBool
litValueNow s (Lit l) = toLBool <$> litVal s l

toLBool :: Int8 -> LBool
toLBool 1 = LTrue
toLBool 0 = LUndef
toLBool _ = LFalse

enqueue :: Solver -> Int -> Clause -> IO ()
enqueue s l reason = do
  let v = l `shiftR` 1
  uWrite (sAssigns s) v (if odd l then -1 else 1)
  dl <- decisionLevel s
  uWrite (sLevel s) v dl
  bWrite (sReason s) v reason
  uPush (sTrail s) l
{-# INLINE enqueue #-}

newDecisionLevel :: Solver -> IO ()
newDecisionLevel s = do
  n <- uSize (sTrail s)
  uPush (sTrailLim s) n
  withTheory s $ \th -> thNewLevel th

withTheory :: Solver -> (TheoryHooks -> IO ()) -> IO ()
withTheory s k = readIORef (sTheory s) >>= mapM_ k
{-# INLINE withTheory #-}

-- | Undo all assignments above the given level.
cancelUntil :: Solver -> Int -> IO ()
cancelUntil s lvl = do
  dl <- decisionLevel s
  when (dl > lvl) $ do
    lim <- uRead (sTrailLim s) lvl
    n <- uSize (sTrail s)
    forM_ [n - 1, n - 2 .. lim] $ \i -> do
      l <- uRead (sTrail s) i
      let v = l `shiftR` 1
      uWrite (sAssigns s) v 0
      bWrite (sReason s) v (sNoClause s)
      uWrite (sPolarity s) v (odd l)
      heapInsert s v
    uShrink (sTrail s) lim
    writeIORef (sQHead s) lim
    modifyIORef' (sTheoryHead s) (min lim)
    uShrink (sTrailLim s) lvl
    withTheory s $ \th -> thBacktrack th lvl

-------------------------------------------------------------------------------
-- Clause database

mkClause :: Solver -> Bool -> [Int] -> IO Clause
mkClause s learnt lits = do
  i <- readIORef (sNextId s)
  writeIORef (sNextId s) (i + 1)
  d <- MU.new (length lits + 2)
  MU.write d 0 (if learnt then flagLearnt else 0)
  MU.write d 1 0
  zipWithM_ (\k l -> MU.write d (k + 2) l) [0 ..] lits
  pure (Clause i d)

attach :: Solver -> Clause -> IO ()
attach s c = do
  l0 <- clauseLit c 0
  l1 <- clauseLit c 1
  bRead (sWatches s) l0 >>= (`bPush` c)
  bRead (sWatches s) l1 >>= (`bPush` c)

-- | Add a problem clause. Must be called outside of search. Returns 'False'
-- if the clause set became trivially unsatisfiable.
addClause :: Solver -> [Lit] -> IO Bool
addClause s lits0 = do
  ok <- readIORef (sOk s)
  if not ok
    then pure False
    else do
      cancelUntil s 0
      let lits = nub (map unLit lits0)
      if any (\l -> (l `xor` 1) `elem` lits) lits
        then pure True
        else do
          vals <- mapM (litVal s) lits
          if 1 `elem` vals
            then pure True
            else case [l | (l, v) <- zip lits vals, v == 0] of
              [] -> writeIORef (sOk s) False >> pure False
              [l] -> do
                enqueue s l (sNoClause s)
                propagate s >>= \case
                  Nothing -> pure True
                  Just _ -> writeIORef (sOk s) False >> pure False
              ls -> do
                c <- mkClause s False ls
                attach s c
                bPush (sClauses s) c
                pure True

-------------------------------------------------------------------------------
-- Propagation

-- | Unit propagation over watched literals. Returns a conflicting clause.
propagate :: Solver -> IO (Maybe Clause)
propagate s = loop
  where
    loop = do
      qh <- readIORef (sQHead s)
      n <- uSize (sTrail s)
      if qh >= n
        then pure Nothing
        else do
          writeIORef (sQHead s) (qh + 1)
          p <- uRead (sTrail s) qh
          bumpStat s cPropagations
          let falseLit = p `xor` 1
          ws <- bRead (sWatches s) falseLit
          r <- propagateWatches s falseLit ws
          case r of
            Nothing -> loop
            Just c -> do
              uSize (sTrail s) >>= writeIORef (sQHead s)
              pure (Just c)

propagateWatches :: Solver -> Int -> BVec Clause -> IO (Maybe Clause)
propagateWatches s falseLit ws = do
  n <- bSize ws
  let go !i !j
        | i >= n = bShrink ws j >> pure Nothing
        | otherwise = do
            c <- bRead ws i
            del <- isDeleted c
            if del
              then go (i + 1) j
              else do
                let d = clData c
                l0 <- MU.unsafeRead d 2
                when (l0 == falseLit) $ do
                  l1 <- MU.unsafeRead d 3
                  MU.unsafeWrite d 2 l1
                  MU.unsafeWrite d 3 l0
                first <- MU.unsafeRead d 2
                v0 <- litVal s first
                if v0 == 1
                  then bWrite ws j c >> go (i + 1) (j + 1)
                  else do
                    k <- findWatch d 4 (MU.length d)
                    if k >= 0
                      then do
                        lk <- MU.unsafeRead d k
                        MU.unsafeWrite d 3 lk
                        MU.unsafeWrite d k falseLit
                        bRead (sWatches s) lk >>= (`bPush` c)
                        go (i + 1) j
                      else do
                        bWrite ws j c
                        if v0 == -1
                          then do
                            -- Conflict: keep the remaining watchers.
                            forM_ [i + 1 .. n - 1] $ \t ->
                              bRead ws t >>= bWrite ws (j + 1 + t - (i + 1))
                            bShrink ws (j + 1 + n - (i + 1))
                            pure (Just c)
                          else do
                            enqueue s first c
                            go (i + 1) (j + 1)
      findWatch d !k len
        | k >= len = pure (-1)
        | otherwise = do
            l <- MU.unsafeRead d k
            v <- litVal s l
            if v /= -1 then pure k else findWatch d (k + 1) len
  go 0 0

-------------------------------------------------------------------------------
-- Conflict analysis

-- | First-UIP analysis. Returns the learnt clause (asserting literal first),
-- the backjump level and the clause's LBD.
analyze :: Solver -> Clause -> IO ([Int], Int, Int)
analyze s confl = do
  dl <- decisionLevel s
  outRef <- newIORef []
  idxStart <- subtract 1 <$> uSize (sTrail s)
  let loop c pathC p idx = do
        lits <- clauseLits c
        let lits' = if p < 0 then lits else drop 1 lits
        pathC' <-
          foldM
            ( \pc q -> do
                let v = q `shiftR` 1
                seen <- uRead (sSeen s) v
                lvl <- uRead (sLevel s) v
                if not seen && lvl > 0
                  then do
                    bumpVar s v
                    uWrite (sSeen s) v True
                    if lvl >= dl
                      then pure (pc + 1)
                      else modifyIORef' outRef (q :) >> pure pc
                  else pure pc
            )
            pathC
            lits'
        idx' <- nextSeen idx
        p' <- uRead (sTrail s) idx'
        let v' = p' `shiftR` 1
        c' <- bRead (sReason s) v'
        uWrite (sSeen s) v' False
        if pathC' - 1 > 0
          then loop c' (pathC' - 1) p' (idx' - 1)
          else pure p'
      nextSeen i = do
        l <- uRead (sTrail s) i
        seen <- uRead (sSeen s) (l `shiftR` 1)
        if seen then pure i else nextSeen (i - 1)
  uip <- loop confl (0 :: Int) (-1) idxStart
  out <- readIORef outRef
  -- Local minimization: drop literals implied by other literals of the
  -- clause (or by level-0 facts).
  kept <- filterM (fmap not . redundant) out
  forM_ out $ \q -> uWrite (sSeen s) (q `shiftR` 1) False
  lvls <- mapM (\q -> uRead (sLevel s) (q `shiftR` 1)) kept
  let learnt = case sortOn (negate . fst) (zip lvls kept) of
        [] -> [uip `xor` 1]
        ((_, q) : rest) -> (uip `xor` 1) : q : map snd rest
      bt = if null lvls then 0 else maximum lvls
      lbd = IntSet.size (IntSet.fromList (dl : lvls))
  pure (learnt, bt, lbd)
  where
    redundant q = do
      r <- bRead (sReason s) (q `shiftR` 1)
      if isNoClause r
        then pure False
        else do
          lits <- drop 1 <$> clauseLits r
          andM
            [ do
                seen <- uRead (sSeen s) (l `shiftR` 1)
                lvl <- uRead (sLevel s) (l `shiftR` 1)
                pure (seen || lvl == 0)
            | l <- lits
            ]
    andM [] = pure True
    andM (m : ms) = m >>= \b -> if b then andM ms else pure False

-- | Compute a subset of the assumptions responsible for the falsification of
-- the assumption @p@ (which is currently false). Decisions found on the trail
-- are assumptions, since this runs during the assumption phase.
analyzeFinal :: Solver -> Int -> IO [Lit]
analyzeFinal s p = do
  dl <- decisionLevel s
  if dl == 0
    then pure [Lit p]
    else do
      uWrite (sSeen s) (p `shiftR` 1) True
      lim <- uRead (sTrailLim s) 0
      n <- uSize (sTrail s)
      core <-
        foldM
          ( \acc i -> do
              l <- uRead (sTrail s) i
              let v = l `shiftR` 1
              seen <- uRead (sSeen s) v
              if not seen
                then pure acc
                else do
                  uWrite (sSeen s) v False
                  r <- bRead (sReason s) v
                  if isNoClause r
                    then pure (Lit l : acc)
                    else do
                      lits <- drop 1 <$> clauseLits r
                      forM_ lits $ \q -> do
                        lvl <- uRead (sLevel s) (q `shiftR` 1)
                        when (lvl > 0) $ uWrite (sSeen s) (q `shiftR` 1) True
                      pure acc
          )
          []
          [n - 1, n - 2 .. lim]
      uWrite (sSeen s) (p `shiftR` 1) False
      pure (nub (Lit p : core))

-- | Learn a clause from a conflict and backjump.
learnFromConflict :: Solver -> Clause -> IO ()
learnFromConflict s confl = do
  bumpStat s cConflicts
  (learnt, bt, lbd) <- analyze s confl
  cancelUntil s bt
  case learnt of
    [l] -> enqueue s l (sNoClause s)
    l : _ -> do
      c <- mkClause s True learnt
      MU.write (clData c) 1 lbd
      attach s c
      bPush (sLearnts s) c
      enqueue s l c
    [] -> error "learnFromConflict: empty learnt clause"
  varDecay s

-------------------------------------------------------------------------------
-- Theory lemmas

data LemmaOutcome = LemmaOk | LemmaConflict Clause | LemmaUnsat

-- | Integrate a clause produced during search. Permanent clauses join the
-- problem clauses; the others are subject to learnt clause deletion.
addLemma :: Solver -> Bool -> [Lit] -> IO LemmaOutcome
addLemma s isPermanent lits0 = do
  let lits1 = nub (map unLit lits0)
  if any (\l -> (l `xor` 1) `elem` lits1) lits1
    then pure LemmaOk
    else do
      info <- forM lits1 $ \l -> do
        v <- litVal s l
        lvl <- uRead (sLevel s) (l `shiftR` 1)
        pure (l, v, lvl)
      if any (\(_, v, lvl) -> v == 1 && lvl == 0) info
        then pure LemmaOk
        else do
          let lits = [(l, v, lvl) | (l, v, lvl) <- info, not (v == -1 && lvl == 0)]
              key (_, v, lvl)
                | v == 1 = (0 :: Int, negate lvl)
                | v == 0 = (1, 0)
                | otherwise = (2, negate lvl)
              sorted = sortOn key lits
          case sorted of
            [] -> writeIORef (sOk s) False >> pure LemmaUnsat
            [(l, _, _)] -> do
              cancelUntil s 0
              enqueue s l (sNoClause s)
              pure LemmaOk
            (l0, v0, lvl0) : (_, v1, _) : _ -> do
              c <- mkClause s (not isPermanent) [l | (l, _, _) <- sorted]
              MU.write (clData c) 1 (length sorted)
              attach s c
              bPush (if isPermanent then sClauses s else sLearnts s) c
              if v0 == -1
                then do
                  cancelUntil s lvl0
                  pure (LemmaConflict c)
                else do
                  when (v0 == 0 && v1 == -1) $ enqueue s l0 c
                  pure LemmaOk

data TheoryOutcome = TOk | TAdded | TConflict Clause | TUnsat

-- | Hand pending literals to the theory and run one of its checks.
runTheory :: Solver -> (TheoryHooks -> IO TheoryResult) -> IO TheoryOutcome
runTheory s check =
  readIORef (sTheory s) >>= \case
    Nothing -> pure TOk
    Just th -> do
      h <- readIORef (sTheoryHead s)
      n <- uSize (sTrail s)
      forM_ [h .. n - 1] $ \i -> uRead (sTrail s) i >>= thAssert th . Lit
      writeIORef (sTheoryHead s) n
      -- Lemmas left over from an earlier batch come first.
      queued <- readIORef (sLemmaQueue s)
      writeIORef (sLemmaQueue s) []
      if not (null queued)
        then addAll queued
        else
          check th >>= \case
            TheoryOk -> pure TOk
            TheoryConflict ls -> outcome <$> addLemma s False (map litNeg ls)
            TheoryLemmas [] -> pure TOk
            TheoryLemmas cls -> addAll cls
  where
    outcome = \case
      LemmaOk -> TAdded
      LemmaConflict c -> TConflict c
      LemmaUnsat -> TUnsat
    addAll [] = pure TAdded
    addAll (Lemma isPermanent c : cs) =
      addLemma s isPermanent c >>= \case
        LemmaOk -> addAll cs
        LemmaConflict cl -> do
          -- Permanent lemmas may never be produced again, so the remaining
          -- ones are added after the conflict is resolved; removable ones
          -- can be recomputed by the theory and are dropped.
          modifyIORef' (sLemmaQueue s) (filter lemmaPermanent cs <>)
          pure (TConflict cl)
        LemmaUnsat -> pure TUnsat

-------------------------------------------------------------------------------
-- VSIDS

bumpVar :: Solver -> Int -> IO ()
bumpVar s v = do
  inc <- readIORef (sVarInc s)
  a <- (+ inc) <$> uRead (sActivity s) v
  uWrite (sActivity s) v a
  when (a > 1e100) $ do
    n <- readIORef (sNumVars s)
    forM_ [0 .. n - 1] $ \u -> uModify (sActivity s) u (* 1e-100)
    writeIORef (sVarInc s) (inc * 1e-100)
  idx <- uRead (sHeapIndex s) v
  when (idx >= 0) $ percolateUp s idx

varDecay :: Solver -> IO ()
varDecay s = modifyIORef' (sVarInc s) (/ 0.95)

heapInsert :: Solver -> Int -> IO ()
heapInsert s v = do
  idx <- uRead (sHeapIndex s) v
  when (idx < 0) $ do
    n <- uSize (sHeap s)
    uPush (sHeap s) v
    uWrite (sHeapIndex s) v n
    percolateUp s n

percolateUp :: Solver -> Int -> IO ()
percolateUp s i0 = do
  v <- uRead (sHeap s) i0
  av <- uRead (sActivity s) v
  let go i
        | i == 0 = place i
        | otherwise = do
            let p = (i - 1) `div` 2
            pv <- uRead (sHeap s) p
            aParent <- uRead (sActivity s) pv
            if av > aParent
              then do
                uWrite (sHeap s) i pv
                uWrite (sHeapIndex s) pv i
                go p
              else place i
      place i = uWrite (sHeap s) i v >> uWrite (sHeapIndex s) v i
  go i0

percolateDown :: Solver -> Int -> IO ()
percolateDown s i0 = do
  n <- uSize (sHeap s)
  v <- uRead (sHeap s) i0
  av <- uRead (sActivity s) v
  let go i = do
        let l = 2 * i + 1
            r = l + 1
        if l >= n
          then place i
          else do
            lv <- uRead (sHeap s) l
            al <- uRead (sActivity s) lv
            (c, cv, ac) <-
              if r < n
                then do
                  rv <- uRead (sHeap s) r
                  ar <- uRead (sActivity s) rv
                  pure (if ar > al then (r, rv, ar) else (l, lv, al))
                else pure (l, lv, al)
            if ac > av
              then do
                uWrite (sHeap s) i cv
                uWrite (sHeapIndex s) cv i
                go c
              else place i
      place i = uWrite (sHeap s) i v >> uWrite (sHeapIndex s) v i
  go i0

heapPop :: Solver -> IO (Maybe Int)
heapPop s = do
  n <- uSize (sHeap s)
  if n == 0
    then pure Nothing
    else do
      top <- uRead (sHeap s) 0
      lastV <- uPop (sHeap s)
      uWrite (sHeapIndex s) top (-1)
      when (n > 1) $ do
        uWrite (sHeap s) 0 lastV
        uWrite (sHeapIndex s) lastV 0
        percolateDown s 0
      pure (Just top)

pickBranchLit :: Solver -> IO (Maybe Int)
pickBranchLit s =
  heapPop s >>= \case
    Nothing -> pure Nothing
    Just v -> do
      a <- uRead (sAssigns s) v
      if a /= 0
        then pickBranchLit s
        else do
          neg <- uRead (sPolarity s) v
          pure (Just (2 * v + fromEnum neg))

-------------------------------------------------------------------------------
-- Learnt clause deletion

reduceDB :: Solver -> IO ()
reduceDB s = do
  ls <- bToList (sLearnts s)
  scored <- forM ls $ \c -> do
    lbd <- MU.read (clData c) 1
    pure (lbd, c)
  let sorted = sortOn (\(lbd, c) -> (negate lbd, negate (clauseSize c))) scored
      half = length sorted `div` 2
  bClear (sLearnts s)
  forM_ (zip [0 :: Int ..] sorted) $ \(i, (lbd, c)) -> do
    locked <- isLocked c
    if i < half && lbd > 2 && not locked
      then MU.modify (clData c) (.|. flagDeleted) 0
      else bPush (sLearnts s) c
  modifyIORef' (sMaxLearnts s) (* 1.1)
  where
    isLocked c = do
      l0 <- clauseLit c 0
      r <- bRead (sReason s) (l0 `shiftR` 1)
      v <- litVal s l0
      pure (r == c && v == 1)

-------------------------------------------------------------------------------
-- Search

-- | Resource limits for 'solveWith'.
data SolveOptions = SolveOptions
  { optConflictLimit :: Maybe Int
    -- ^ Give up with 'Unknown' after this many conflicts.
  , optDeadline :: Maybe Double
    -- ^ Give up with 'Unknown' once the monotonic clock
    -- ('GHC.Clock.getMonotonicTime') passes this time, in seconds. The
    -- clock is read at every conflict and every final theory check.
  }

-- | No conflict limit and no deadline.
defaultSolveOptions :: SolveOptions
defaultSolveOptions = SolveOptions Nothing Nothing

data SearchResult = SRSat | SRUnsat | SRRestart | SRBudget

search :: Solver -> V.Vector Lit -> Int -> Int -> Maybe Double -> IO SearchResult
search s assumps restartAfter globalLimit deadline = go 0
  where
    go :: Int -> IO SearchResult
    go !nConfl =
      propagate s >>= \case
        Just c -> onConflict nConfl c
        Nothing ->
          runTheory s thPropagate >>= \case
            TConflict c -> onConflict nConfl c
            TUnsat -> pure SRUnsat
            TAdded -> go nConfl
            TOk -> decide nConfl

    onConflict nConfl c = do
      dl <- decisionLevel s
      if dl == 0
        then writeIORef (sOk s) False >> pure SRUnsat
        else do
          learnFromConflict s c
          total <- MU.read (sCounters s) cConflicts
          late <- pastDeadline
          if total >= globalLimit || late
            then pure SRBudget
            else
              if nConfl + 1 >= restartAfter
                then pure SRRestart
                else go (nConfl + 1)

    decide nConfl = do
      nl <- bSize (sLearnts s)
      nt <- uSize (sTrail s)
      maxL <- readIORef (sMaxLearnts s)
      when (fromIntegral (nl - nt) >= maxL) $ reduceDB s
      dl <- decisionLevel s
      if dl < V.length assumps
        then do
          let Lit p = assumps V.! dl
          litVal s p >>= \case
            1 -> newDecisionLevel s >> go nConfl
            -1 -> do
              analyzeFinal s p >>= writeIORef (sFailed s)
              pure SRUnsat
            _ -> do
              newDecisionLevel s
              enqueue s p (sNoClause s)
              go nConfl
        else
          pickBranchLit s >>= \case
            Just l -> do
              bumpStat s cDecisions
              newDecisionLevel s
              enqueue s l (sNoClause s)
              go nConfl
            Nothing ->
              pastDeadline >>= \case
                True -> pure SRBudget
                False -> finalCheck nConfl

    finalCheck nConfl =
      runTheory s thFinalCheck >>= \case
        -- The theory may have created new variables (for instance to
        -- branch on): the assignment is complete only when they are
        -- assigned too.
        TOk ->
          pickBranchLit s >>= \case
            Nothing -> pure SRSat
            Just l -> do
              bumpStat s cDecisions
              newDecisionLevel s
              enqueue s l (sNoClause s)
              go nConfl
        TConflict c -> onConflict nConfl c
        TUnsat -> pure SRUnsat
        TAdded -> go nConfl

    pastDeadline = case deadline of
      Nothing -> pure False
      Just d -> (> d) <$> getMonotonicTime

-- | The Luby sequence scaled by @y@.
luby :: Double -> Int -> Double
luby y x0 =
  let (size0, sq0) = grow 1 0
      grow size sq
        | size < x0 + 1 = grow (2 * size + 1) (sq + 1)
        | otherwise = (size, sq)
      shrink size sq x
        | size - 1 /= x = let size' = (size - 1) `div` 2 in shrink size' (sq - 1) (x `mod` size')
        | otherwise = sq
   in y ^^ (shrink size0 sq0 x0 :: Int)

-- | Solve the current clause set.
solve :: Solver -> IO SatResult
solve s = solveWith s defaultSolveOptions []

-- | Solve under assumptions. On 'Unsat', 'failedAssumptions' returns a subset
-- of the assumptions that is sufficient for unsatisfiability (empty when the
-- clause set itself is unsatisfiable).
solveWith :: Solver -> SolveOptions -> [Lit] -> IO SatResult
solveWith s opts assumptions = do
  writeIORef (sFailed s) []
  ok <- readIORef (sOk s)
  if not ok
    then pure Unsat
    else do
      cancelUntil s 0
      start <- MU.read (sCounters s) cConflicts
      let limit = maybe maxBound (+ start) (optConflictLimit opts)
          assumps = V.fromList assumptions
          loop i = do
            let restartAfter = round (luby 2 i * 100) :: Int
            r <- search s assumps restartAfter limit (optDeadline opts)
            case r of
              SRRestart -> do
                bumpStat s cRestarts
                cancelUntil s 0
                loop (i + 1)
              SRSat -> do
                n <- readIORef (sNumVars s)
                forM_ [0 .. n - 1] $ \v -> uRead (sAssigns s) v >>= uWrite (sModel s) v
                cancelUntil s 0
                pure Sat
              SRUnsat -> cancelUntil s 0 >> pure Unsat
              SRBudget -> cancelUntil s 0 >> pure Unknown
      loop 0

-- | Value of a variable in the last model. Variables left unassigned
-- (possible only when created after solving) are reported as 'False'.
modelValue :: Solver -> Var -> IO Bool
modelValue s v = (== 1) <$> uRead (sModel s) v

-- | The values of all variables in the last model, indexed by variable.
getModel :: Solver -> IO [Bool]
getModel s = do
  n <- readIORef (sNumVars s)
  mapM (modelValue s) [0 .. n - 1]

-- | After an 'Unsat' answer of 'solveWith', a subset of the assumptions
-- sufficient for unsatisfiability (see 'solveWith').
failedAssumptions :: Solver -> IO [Lit]
failedAssumptions = readIORef . sFailed

-- | Literals already handed to the theory hooks, in assignment order. Call
-- it outside of search: hooks installed later can be brought up to date
-- with these literals (the others reach them through 'thAssert').
deliveredLits :: Solver -> IO [Lit]
deliveredLits s = do
  n <- readIORef (sTheoryHead s)
  mapM (fmap Lit . uRead (sTrail s)) [0 .. n - 1]