packages feed

rest-rewrite 0.4.5 → 0.5.0

raw patch · 38 files changed

+1373/−747 lines, 38 filesdep +tastydep +tasty-hunitdep +tasty-quickcheckdep ~QuickCheckPVP ok

version bump matches the API change (PVP)

Dependencies added: tasty, tasty-hunit, tasty-quickcheck

Dependency ranges changed: QuickCheck

API changes (from Hackage documentation)

Files

+ changelog.md view
@@ -0,0 +1,15 @@+# Changes++## Next++## 0.5.0 (2026-12-01)++- Use tasty for the testsuite ([#51](https://github.com/zgrannan/rest/pull/51))+- Optimized equality of expressions ([#51](https://github.com/zgrannan/rest/pull/51))+- Optimize isFullyExplored ([#50](https://github.com/zgrannan/rest/pull/50))+- Emit bindings to reduce formula size ([#48](https://github.com/zgrannan/rest/pull/48))+- `refine` emits constant declarations for undeclared symbols ([#48](https://github.com/zgrannan/rest/pull/48))+- `sendCommands` does not flush the input to the SMT solver anymore ([#48](https://github.com/zgrannan/rest/pull/48))+- `sendCommandsNow` does flush the input to the SMT solver ([#48](https://github.com/zgrannan/rest/pull/48))+- The `ConstraintsADT` has been removed ([#48](https://github.com/zgrannan/rest/pull/48))+
rest-rewrite.cabal view
@@ -1,15 +1,27 @@+cabal-version:      2.2 name:               rest-rewrite build-type:         Simple-version:            0.4.5-cabal-version:      2.0+version:            0.5.0 category:           Rewriting maintainer:         Zack Grannan <zgrannan@cs.ubc.ca> author:             Zack Grannan <zgrannan@cs.ubc.ca>-license:            BSD3-description:        REST is a Rewriting library with online termination checking. For more details see the paper at https://arxiv.org/abs/2202.05872.+license:            BSD-3-Clause+description:+    This package provides functions to determine if a sequence of terms has a+    well-quasi ordering that makes it non-increasing. This is useful for+    automatic theorem provers that need to decide when to stop exploring a+    particular path in a proof.+    .+    Also contains auxiliary functions to visualize trees of rewrites with the+    `dot` tool of the `graphviz` package.+    .+    See `README.md` for more details.+ synopsis:           Rewriting library with online termination checking license-file:       LICENSE +extra-doc-files: changelog.md+ extra-source-files:   graphs/.DONOTDELETE @@ -17,7 +29,19 @@   type:     git   location: https://github.com/zgrannan/rest +flag devel+  default:     False+  manual:      True+  description: Enable more warnings and fail compilation when warnings occur.+               Turn this flag on in CI.++common common-ghc-options+  ghc-options:        -W -fwarn-missing-signatures -Wno-x-partial -Wno-incomplete-record-selectors+  if flag(devel)+    ghc-options:      -Wall -Werror -Wno-x-partial -Wno-incomplete-record-selectors+ library+  import:           common-ghc-options   default-language:  Haskell2010   exposed-modules:     Language.REST@@ -50,12 +74,11 @@     Language.REST.SMT     Language.REST.Types     Language.REST.WQOConstraints-    Language.REST.WQOConstraints.ADT-    Language.REST.WQOConstraints.Lazy+    Language.REST.WQOConstraints.SMT     Language.REST.WQOConstraints.Strict   hs-source-dirs: src   build-depends:  base                 >= 4.7 && < 5-                , containers           >= 0.6.2 && < 0.8+                , containers           >= 0.6.2 && < 0.9                 , hashable             >= 1.3.0 && < 1.6                 , process              >= 1.6.9 && < 1.7                 , parsec               >= 3.1.14 && < 3.2@@ -64,6 +87,7 @@                 , text                 >= 1.2.4 && < 2.2  library testlib+  import:           common-ghc-options   default-language:  Haskell2010   build-depends:  base >= 4.7                 , containers@@ -76,7 +100,7 @@                 , monad-loops >= 0.4.3 && < 0.5                 , unordered-containers >= 0.2.11                 , text-                , time >= 1.9.3 && < 1.15+                , time >= 1.9.3 && < 1.16   exposed-modules:       Arith       DSL@@ -89,6 +113,7 @@   hs-source-dirs: testlib  Test-Suite test-rest+  import:           common-ghc-options   default-language:  Haskell2010   type: exitcode-stdio-1.0   main-is: Test.hs@@ -96,25 +121,31 @@   build-depends:  base                 , hashable                 , containers-                , QuickCheck >= 2.14.2 && < 2.15+                , QuickCheck >= 2.14.2                 , mtl                 , unordered-containers                 , text                 , rest-rewrite+                , tasty+                , tasty-hunit+                , tasty-quickcheck                 , testlib   other-modules:     ExploredTerms     KBO-    LazyOC+    LPOEquiv     MultisetOrder     OpOrdering     QuickCheckTests     RPO+    RPOEquiv     SMT+    SMTExprInstances     StrictOC     WQO  Test-Suite rest+  import:           common-ghc-options   default-language:  Haskell2010   type: exitcode-stdio-1.0   main-is: Main.hs
src/Language/REST.hs view
@@ -2,16 +2,22 @@  module Language.REST where -import Language.REST.OCAlgebra (OCAlgebra)-import Language.REST.OCToAbstract-import Language.REST.WQOConstraints.ADT (ConstraintsADT, adtOC)-import Language.REST.RPO+import Data.Text (Text)+import Language.REST.OCAlgebra (OCAlgebra(..))+import Language.REST.RPO (rpoSMT)+import Language.REST.LPO (lpoSMT, lpoStrictSMT) import Language.REST.RuntimeTerm-import Language.REST.Op-import System.IO (Handle)+import Language.REST.SMT  --- | 'adtRPO' Is an ordering constraint algebra derived from the recursive--- path ordering; it is a useful general-purpose OCA.-adtRPO :: (Handle, Handle) -> OCAlgebra (ConstraintsADT Op) RuntimeTerm IO-adtRPO z3 = lift (adtOC z3) rpo+-- | An ordering constraint algebra derived from the recursive path ordering.+rpoOCA :: SolverHandle -> Text -> IO (OCAlgebra (SMTExpr Bool) RuntimeTerm IO)+rpoOCA z3 prefix = smtOCA z3 prefix rpoSMT++-- | An ordering constraint algebra derived from the lexicographic path ordering.+lpoOCA :: SolverHandle -> Text -> IO (OCAlgebra (SMTExpr Bool) RuntimeTerm IO)+lpoOCA z3 prefix = smtOCA z3 prefix lpoSMT++-- | A strict version of 'lpoOCA'.+lpoStrictOCA :: SolverHandle -> Text -> IO (OCAlgebra (SMTExpr Bool) RuntimeTerm IO)+lpoStrictOCA z3 prefix = smtOCA z3 prefix lpoStrictSMT
src/Language/REST/Core.hs view
@@ -10,8 +10,8 @@ -- | @orient impl ts@ generates the constraints on an ordering defined by the --   OCA `impl`, that ensures each term in the path `ts` is smaller than or --   equal to the previous one.-orient :: OCAlgebra oc RuntimeTerm m -> [RuntimeTerm] -> oc+orient :: Monad m => OCAlgebra oc RuntimeTerm m -> [RuntimeTerm] -> m oc orient impl ts0 = go (top impl) (zip ts0 (tail ts0))    where-    go oc []            = oc-    go oc ((t0, t1):ts) = go (refine impl oc t0 t1) ts+    go oc []            = pure oc+    go oc ((t0, t1):ts) = refine impl oc t0 t1 >>= \c -> go c ts
src/Language/REST/ExploredTerms.hs view
@@ -15,6 +15,7 @@    , ExploreStrategy(..)    )  where +import Control.Monad (filterM) import qualified Data.HashMap.Strict as M import qualified Data.HashSet as S import Data.Hashable@@ -44,7 +45,7 @@     -- | @'exRefine' c t u@ strengthens constraints @c@ to permit the rewrite step     --   from @t@ to @u@. This is used to determine if considering term @u@ by rewriting     --   from @t@ would permit more rewrite applications.-  , exRefine        :: c -> term -> term -> c+  , exRefine        :: c -> term -> term -> m c   }  -- | A mapping of terms, to the rewritten terms that need to be fully explored@@ -72,44 +73,47 @@ -- | @isFullyExplored t c M = not explorable(t, c)@ where @explorable@ is -- defined as in the REST paper. Also incorporates an optimization described -- here: https://github.com/zgrannan/rest/issues/9-isFullyExplored :: forall term c m . (Monad m, Eq term, Hashable term, Hashable c, Eq c, Show c) =>+isFullyExplored :: forall term c m . (Monad m, Eq term, Hashable term) =>   term -> c -> ExploredTerms term c m -> m Bool-isFullyExplored t0 oc0 et@(ET _ (EF{subsumes,exRefine}) _) = result where+isFullyExplored t0 oc0 et@(ET _ (EF{union,subsumes,exRefine}) _) = result where -  result = go S.empty [(t0, oc0)]+  result = go M.empty [(t0, oc0)]    -- Arg 1: Steps that have already been seen   -- Arg 2: Steps to consider-  go :: S.HashSet (term, c) -> [(term, c)] -> m Bool+  go :: M.HashMap term c -> [(term, c)] -> m Bool    -- Completed worklist, this term is fully explored at these constraints   go _ []       = return True    -- Term `h` has been seen before at constraints `oc`-  go seen ((h, oc'):rest) | Just (oc, trms) <- lookup h et-                = do-                    exploringPathWouldNotPermitDifferentSteps <- oc `subsumes` oc'-                    if exploringPathWouldNotPermitDifferentSteps-                      then go seen' rest-                      else-                        let-                          -- Exploring `h` at these constraints-                          -- would allow exploration of each t in trms,-                          -- at the constraints generated by the step from h to t-                          trms' = S.map (\t -> (t, exRefine oc' h t)) trms-                          ts    = S.union trms' (S.fromList rest) `S.difference` seen'-                        in-                          go seen' (S.toList ts)-                  where-                    seen' = S.insert (h, oc') seen+  go seen ((h, oc'):rest) | Just (oc, trms) <- lookup h et = do+      exploringPathWouldNotPermitDifferentSteps <- oc `subsumes` oc'+      let seen' = M.insertWith union h oc' seen+      if exploringPathWouldNotPermitDifferentSteps then+        go seen' rest+      else do+        -- Exploring `h` at these constraints would allow exploration of+        -- each t in trms, at the constraints generated by the step from+        -- h to t+        trms' <- mapM (\t -> (,) t <$> exRefine oc' h t) $ S.toList trms+        ts <- filterM (fmap not . subsumedBySeen seen') $ trms' ++ rest+        go seen' ts+    where +      subsumedBySeen :: M.HashMap term c -> (term, c) -> m Bool+      subsumedBySeen seen' (t, oc'') =+        case M.lookup t seen' of+          Nothing -> return False+          Just seenOC -> seenOC `subsumes` oc''+   -- There exists a reachable term that has never previously been seen; not fully explored   go _ _         = return False  -- | @'shouldExplore' t c et@ determines if rewrites originating from term @t@ at --   constraints @c@ should be considered, given the already explored terms of @et@ --   and the associated 'ExploreStrategy'-shouldExplore :: forall term c m . (Monad m, Eq term, Hashable term, Eq c, Show c, Hashable c) =>+shouldExplore :: forall term c m . (Monad m, Eq term, Hashable term) =>   term -> c -> ExploredTerms term c m -> m Bool shouldExplore t oc et@(ET _ EF{subsumes} strategy) =   case strategy of
src/Language/REST/Internal/ListT.hs view
@@ -23,7 +23,6 @@       map f xs  instance (Monad m) => Monad (ListT m) where-  return x         = ListT (return [x])   (ListT mxs) >>= f = ListT $ do     xs <- mxs     res <- mapM (runListT . f) xs
src/Language/REST/Internal/MultisetOrder.hs view
@@ -6,7 +6,7 @@ -- | This module defines a constraint generator for a multiset --   quasi-ordering. For more details, please see the definition --   of @mul@ in section 4.2.1 of the paper.-module Language.REST.Internal.MultisetOrder (multisetOrder) where+module Language.REST.Internal.MultisetOrder (multisetOrder, removeEQs, possibilities, Replace(..)) where  import GHC.Generics import qualified Data.List as L
src/Language/REST/Internal/WQO.hs view
@@ -50,7 +50,7 @@   show QEQ = "≈"  instance {-# OVERLAPPING #-} ToSMTVar a Int => ToSMT (WQO a) Bool where-  toSMT (WQO ecs po) = And $ ecsSMT ++ posSMT where+  toSMT (WQO ecs po) = smtAnd $ ecsSMT ++ posSMT where      toSMT' :: a -> SMTExpr Int     toSMT' = toSMT@@ -59,7 +59,7 @@       ec <- S.toList ecs       let ecl = EC.toList ec       guard $ length ecl >= 2-      return $ Equal (map toSMT' ecl)+      return $ smtEqual (map toSMT' ecl)      posSMT = do       (ec, vs) <- PO.toDescsList po@@ -188,13 +188,9 @@       ec' <- L.find (ec `EC.isSubsetOf`) (S.toList ecs')       mkEcsMap (M.insert ec ec' buf) rest   gt ecsMap (ec, descs) =-    let-      Just ec' = M.lookup ec ecsMap-    in-      descs `S.isSubsetOf` PO.descendents ec' po'---+    case M.lookup ec ecsMap of+      Just ec' -> descs `S.isSubsetOf` PO.descendents ec' po'+      _ -> error "notStrongerThan: missing equivalence class"  mergeAll :: forall a. (Show a, Ord a, Eq a, Hashable a) => [WQO a] -> Maybe (WQO a) mergeAll []            = Just empty@@ -312,24 +308,27 @@                 f'       = EC.singleton f                 g'       = EC.singleton g                 ecs'     = S.insert f' $ S.insert g' ecs-                Just po' = PO.insert po f' g'-            in-                WQO ecs' po'+             in+                case PO.insert po f' g' of+                  Nothing  -> error "insert: failed to insert into partial order"+                  Just po' -> WQO ecs' po'         (Just ec, Nothing)   ->             let                 g'       = EC.singleton g                 ecs'     = S.insert g' ecs-                Just po' = PO.insert po ec g'-            in-                WQO ecs' po'+             in+                case PO.insert po ec g' of+                  Nothing  -> error "insert: failed to insert into partial order"+                  Just po' -> WQO ecs' po'          (Nothing, Just ec) ->             let                 f'       = EC.singleton f                 ecs'     = S.insert f' ecs-                Just po' = PO.insert po f' ec-            in-                WQO ecs' po'+             in+                case PO.insert po f' ec of+                  Nothing  -> error "insert: failed to insert into partial order"+                  Just po' -> WQO ecs' po'         (Just ec1, Just ec2) ->             WQO ecs (PO.insertUnsafe po ec1 ec2) 
src/Language/REST/KBO.hs view
@@ -1,8 +1,8 @@ {-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE NamedFieldPuns #-}  module Language.REST.KBO (kbo, kboGTE) where +import           Data.Text (Text) import           Language.REST.OCAlgebra import           Language.REST.Op import           Language.REST.RuntimeTerm as RT@@ -10,6 +10,7 @@ import           Language.REST.Internal.Util  import qualified Data.Map as M+import GHC.Stack (HasCallStack)  termOps :: RuntimeTerm -> [Op] termOps (App f xs) = f:concatMap termOps xs@@ -21,7 +22,7 @@   go m (App f [targ]) = go (M.insert f 1 m) targ   go m (App f ts)  = foldl go (M.insert f 0 m) ts -  toExpr m = And $ map toConstraint (M.toList m)+  toExpr m = smtAnd $ map toConstraint (M.toList m)   toConstraint (sym, n) = toSMT sym `smtGTE` Const n  @@ -29,22 +30,12 @@ -- on the weights of function symbols such that @t@ is greater than @u@ -- in the KBO ordering. kboGTE :: RuntimeTerm -> RuntimeTerm -> SMTExpr Bool-kboGTE t u = arityConstraints t `smtAnd` arityConstraints u `smtAnd` (size tOps `smtGTE` size uOps)+kboGTE t u = smtAnd [arityConstraints t, arityConstraints u, size tOps `smtGTE` size uOps]   where     (tOps, uOps) = removeEqBy (==) (termOps t) (termOps u)     size ops     = smtAdd (map toSMT ops)   -- | OCA for a quasi-order extension to the Knuth-Bendix ordering-kbo :: SolverHandle -> OCAlgebra (SMTExpr Bool) RuntimeTerm IO-kbo solver = OCAlgebra-  {  isSat           = checkSat' solver-  ,  refine-  ,  top             = smtTrue-  ,  union-  ,  notStrongerThan-  }-  where-    union  e1 e2          = Or [e1, e2]-    refine e t u          = e `smtAnd` kboGTE t u-    notStrongerThan e1 e2 = checkSat' solver (Implies e2 e1)+kbo :: HasCallStack => SolverHandle -> Text -> IO (OCAlgebra (SMTExpr Bool) RuntimeTerm IO)+kbo solver prefix = smtOCA solver prefix kboGTE
src/Language/REST/LPO.hs view
@@ -2,11 +2,12 @@  {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# OPTIONS_GHC -Wno-unused-matches #-}    -module Language.REST.LPO (lpo, lpoStrict) where+module Language.REST.LPO (lpo, lpoStrict, lpoSMT, lpoStrictSMT, lpoSMTRel, lpoStrictSMTRel) where  import Prelude hiding (EQ, GT, lex) @@ -18,6 +19,7 @@ import           Language.REST.WQOConstraints as OC import           Language.REST.Types import           Language.REST.RuntimeTerm+import           Language.REST.SMT  lex   :: (Eq a, Ord b, Hashable b)@@ -90,3 +92,57 @@ --   the Lexicographic path ordering. lpoStrict :: (Show (oc Op), Eq (oc Op), Hashable (oc Op)) => ConstraintGen oc Op RuntimeTerm Identity lpoStrict oc r cs t u = return $ lpo' True oc r cs t u++-- | Direct SMT translation of the LPO constraint generator, without going+--   through 'WQOConstraints'.+lpoSMT' :: Bool -> Relation -> SMTExpr Bool -> RuntimeTerm -> RuntimeTerm -> SMTExpr Bool+lpoSMT' strict r e t@(App f ts) u@(App g us)+  | not strict && r == EQ && length ts /= length us = smtFalse+  | not strict && r == EQ =+      let cs'  = smtAnd [e, eqPrec f g]+          subs = zipWith (lpoSMT' strict EQ cs') ts us+      in smtAnd (cs' : subs)+  | strict && r == EQ = if t == u then e else smtFalse+  | otherwise = smtAnd [e, smtOr [case1, case2, case3]]+  where+    case1 = smtOr [ lpoSMT' strict GTE e ti u | ti <- ts ]+    case2 = if f == g then smtFalse else smtAnd [tDominatesUs, gtPrec f g]+    case3 = if strict && f /= g+      then smtFalse+      else smtAnd+                ([ tDominatesUs+                 , lexSMT (r == GT) e ts us+                 ] ++ [ eqPrec f g | f /= g ])++    tDominatesUs = smtAnd [ lpoSMT' strict GT e t uj | uj <- us ]++    eqPrec :: Op -> Op -> SMTExpr Bool+    eqPrec a b = smtEqual [toSMT a, toSMT b]++    gtPrec :: Op -> Op -> SMTExpr Bool+    gtPrec a b = Greater (toSMT a) (toSMT b)++    lexSMT :: Bool -> SMTExpr Bool -> [RuntimeTerm] -> [RuntimeTerm] -> SMTExpr Bool+    lexSMT isGT acc [] (_:_) = smtFalse+    lexSMT _   acc (_:_) [] = acc+    lexSMT isGT acc []    [] = if isGT then smtFalse else acc+    lexSMT isGT acc (x:xs) (y:ys)+      | x == y = lexSMT isGT acc xs ys+      | otherwise = smtOr+                       [ lpoSMT' strict GT acc x y+                       , lexSMT isGT (lpoSMT' strict EQ acc x y) xs ys+                       ]++-- | The GTE instance of 'lpoSMT'' for the non-strict ordering.+lpoSMTRel :: Relation -> RuntimeTerm -> RuntimeTerm -> SMTExpr Bool+lpoSMTRel r = lpoSMT' False r smtTrue++lpoSMT :: RuntimeTerm -> RuntimeTerm -> SMTExpr Bool+lpoSMT = lpoSMTRel GTE++-- | The GTE instance of 'lpoSMT'' for the strict ordering.+lpoStrictSMTRel :: Relation -> RuntimeTerm -> RuntimeTerm -> SMTExpr Bool+lpoStrictSMTRel r = lpoSMT' True r smtTrue++lpoStrictSMT :: RuntimeTerm -> RuntimeTerm -> SMTExpr Bool+lpoStrictSMT = lpoStrictSMTRel GTE
src/Language/REST/OCAlgebra.hs view
@@ -2,19 +2,32 @@ {-# LANGUAGE ScopedTypeVariables #-} module Language.REST.OCAlgebra where --- | The "Ordering Constraint Algebra", as described in section 4.2 of the paper.---  @OCAlgebra c a m@ is an OCA with language of constraints @c@, applied to terms---  of type @a@. @m@ is the computation context for @isSat@.+-- | Ordering Constraint Algebra: Operations to determine if there is a+--   well-quasi ordering that makes a sequence of terms non-increasing.+--+-- @c@ is a type representing ordering constraints.+--+-- @a@ is the type of the terms in a sequence.+--+-- @m@ is a monad that allows to perform computations, such as checking the+-- satisfiability of constraints.+-- data OCAlgebra c a m = OCAlgebra-  { isSat  :: c -> m Bool       -- ^ Checks if the constraints are satisfiable-  , refine :: c -> a -> a -> c  -- ^ @refine c t u@ strengthens @c@ to permit @t >= u@-  , top    :: c                 -- ^ Initial constraints for use in REST--  , union  :: c -> c -> c       -- ^ Computes the union of constraints; used in 'ExploredTerms' as an optimization-                                --   A safe default implementation is @union c1 c2 = c2@--  , notStrongerThan :: c -> c -> m Bool -- ^ @c1 `notStrongerThan c2@ if @c1@ permits all orderings allowed by @c2@-                                        -- A safe default implementation is @notStrongerThan _ _ = return false@+  { -- | Checks if the constraints are satisfiable+    isSat  :: c -> m Bool+    -- | @refine c t u@ strengthens @c@ to permit @t >= u@+    --+    -- Refine might emit bindings (e.g. constant definitions) to be used in+    -- the satisfiability checks, in order to reduce the size of the+    -- constraints (see https://github.com/zgrannan/rest/issues/16).+  , refine :: c -> a -> a -> m c+    -- | Allows any non-increasing ordering.+  , top :: c+    -- | @union c0 c1@ allows any of the orderings permitted by @c0@ or @c1@.+  , union  :: c -> c -> c+    -- | @c1 `notStrongerThan` c2 == True@ if @c1@ permits all orderings allowed+    -- by @c2@.+  , notStrongerThan :: c -> c -> m Bool   }  -- | @fuelOC n@ is an OCA that permits @n@ rewrite steps@@ -22,7 +35,7 @@ fuelOC initFuel = OCAlgebra isSat' refine' initFuel union' notStrongerThan'   where     isSat'  c             = return $ c >= 0-    refine' c _ _         = c - 1+    refine' c _ _         = return $ c - 1     union'                = max     notStrongerThan' c c' = return $ c >= c' @@ -34,13 +47,14 @@   -> OCAlgebra c b m contramap f oca = oca{refine = refine'}   where-    refine' :: c -> b -> b -> c+    refine' :: c -> b -> b -> m c     refine' c t1 t2 = refine oca c (f t1) (f t2)  -- | @bimapConstraints to from oca@ yields an oca using @d@ to track constraints; @to@ and @from@ should --   define an isomorphism between c and d bimapConstraints :: forall c d a m .-     (c -> d)+     Functor m+  => (c -> d)   -> (d -> c)   -> OCAlgebra c a m   -> OCAlgebra d a m@@ -49,8 +63,8 @@     isSat' :: d -> m Bool     isSat' c = isSat oca (from c) -    refine' :: d -> a -> a -> d-    refine' c t1 t2 = to $ refine oca (from c) t1 t2+    refine' :: d -> a -> a -> m d+    refine' c t1 t2 = to <$> refine oca (from c) t1 t2      union' :: d -> d -> d     union' c1 c2 = to $ union oca (from c1) (from c2)
src/Language/REST/OCToAbstract.hs view
@@ -17,7 +17,7 @@ -- | @lift@ takes a representation of constraints on a WQO over @base@, --   alongside a function used to generate constraints to permit a relation on terms @lifted@, --   and returns the corresponding Ordering Constraints Algebra-lift :: forall impl base lifted m . (ToSMTVar base Int, Ord base, Eq base, Hashable base, Show lifted, Show base, Show (impl base)) =>+lift :: forall impl base lifted m . (Applicative m, ToSMTVar base Int, Ord base, Eq base, Hashable base, Show lifted, Show base, Show (impl base)) =>      OC.WQOConstraints impl m   -> OC.ConstraintGen impl base lifted Identity   -> OCAlgebra (impl base) lifted m@@ -36,10 +36,10 @@     top' :: impl base     top' = OC.noConstraints oc -    refine' :: impl base -> lifted -> lifted -> impl base+    refine' :: impl base -> lifted -> lifted -> m (impl base)     refine' c t u =       let         pair   = runIdentity $ cgen oc GTE top' t u         result = OC.intersect oc c pair       in-        result+        pure result
src/Language/REST/RPO.hs view
@@ -7,7 +7,7 @@  -- | This module contains the implementation of the Recursive Path Quasi-Ordering, --   defined in section 4.2.1 of the REST paper-module Language.REST.RPO (rpo, rpoGTE, synGTE) where+module Language.REST.RPO (rpo, rpoGTE, synGTE, rpoSMT, rpoSMTRel) where  import Prelude hiding (EQ, GT) @@ -16,6 +16,8 @@ import GHC.Generics import Data.Hashable import qualified Data.HashMap.Strict as M+import qualified Data.HashSet as HS+import qualified Data.List as L  import qualified Language.REST.Internal.MultiSet as MS import           Language.REST.Op@@ -26,6 +28,7 @@ import qualified Language.REST.RuntimeTerm as RT import           Language.REST.Internal.MultisetOrder import           Language.REST.Internal.Util+import           Language.REST.SMT  instance Show RuntimeTerm where   show (App op trms) =@@ -154,3 +157,49 @@ synGTM ordering xs ys = case removeEqBy (synEQ ordering) (MS.toList xs) (MS.toList ys) of   ([] , [] ) -> False   (xs', ys') -> all (\y -> any (\x -> rpoT ordering x y) xs') ys'++-- | Direct SMT translation of the RPO constraint generator, without going+--   through 'WQOConstraints'. @rpoSMTRel r t u@ is the SMT constraint on the+--   weights of function symbols such that @t@ is related to @u@ by @r@ in the+--   recursive path ordering.+rpoSMTRel :: Relation -> RT.RuntimeTerm -> RT.RuntimeTerm -> SMTExpr Bool+rpoSMTRel r t u = rpoSMT' r smtTrue (rpoTerm t) (rpoTerm u)++-- | The GTE instance of 'rpoSMTRel'.+rpoSMT :: RT.RuntimeTerm -> RT.RuntimeTerm -> SMTExpr Bool+rpoSMT = rpoSMTRel GTE++rpoSMT' :: Relation -> SMTExpr Bool -> RuntimeTerm -> RuntimeTerm -> SMTExpr Bool+rpoSMT' r e t u+  | t == u                              = if r == GT then smtFalse else e+  | t `isSubtermOf` u                   = smtFalse+  | u `isSubtermOf` t                   = if r == EQ then smtFalse else e+  | App f ts <- t, App g us <- u, f == g = rpoMulSMT r e ts us+  | App f ts <- t, App g us <- u         =+      let eqPrec = smtEqual [toSMT f, toSMT g]+          gtPrec = Greater (toSMT f) (toSMT g)+          body+            | r == EQ   = rpoMulSMT r eqPrec ts us+            | otherwise = smtOr+                             [ rpoMulSMT GT gtPrec (MS.singleton t) us+                             , rpoMulSMT r  eqPrec ts us+                             , rpoMulSMT GTE smtTrue ts (MS.singleton u)+                             ]+      in smtAnd [e, body]++rpoMulSMT :: Relation -> SMTExpr Bool -> MultiSet RuntimeTerm -> MultiSet RuntimeTerm -> SMTExpr Bool+rpoMulSMT r e ts0 us0 = uncurry go (removeEQs ts0 us0)+  where+    go ts us+      | MS.null ts && MS.null us       = if r == GT then smtFalse else e+      | not (MS.null ts) && MS.null us = if r == EQ then smtFalse else e+      | MS.null ts && not (MS.null us) = smtFalse+      | otherwise = smtOr [ posConstraints pos1 | pos1 <- HS.toList (possibilities r (MS.toList ts) (MS.toList us)) ]++    posConstraints pos1 = L.foldl' apply e (HS.toList pos1)+      where+        apply acc (ReplaceOne t u) = rpoSMT' EQ acc t u+        apply acc (Replace t ts')  =+          if HS.null ts'+            then acc+            else smtAnd $ acc : map (rpoSMT' GT smtTrue t) (HS.toList ts')
src/Language/REST/Rest.hs view
@@ -145,7 +145,7 @@         accepted userRWs = M.fromList <$> runListT (do           t' <- liftSet $ S.map fst userRWs           guard $ L.notElem t' tsTerms-          let ord = refine ocImpl lastOrdering ptTerm t'+          ord <- ListT $ fmap (:[]) (refine ocImpl lastOrdering ptTerm t')           ok <- lift $ isSat ocImpl ord           guard ok           return (t', ord))@@ -188,7 +188,7 @@             evalPaths = runListT $ do               (t', r) <- ListT $ return (S.toList evalRWs)               guard $ L.notElem t' tsTerms-              let ord = refine ocImpl lastOrdering ptTerm t'+              ord <- ListT $ fmap (:[]) (refine ocImpl lastOrdering ptTerm t')               lift (shouldExplore t' ord et) >>= guard               return (ts ++ [Step pt r ord True], PathTerm t' S.empty) 
src/Language/REST/RuntimeTerm.hs view
@@ -1,20 +1,26 @@ {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE OverloadedStrings #-}  module Language.REST.RuntimeTerm   ( RuntimeTerm(..)   , ToRuntimeTerm(..)   , subTerms   , contains+  , smtOCA   ) where  import           Data.Hashable+import           Data.Text (Text) import           GHC.Generics (Generic) import           Text.Printf import qualified Data.List as L +import           Language.REST.OCAlgebra import           Language.REST.Op+import           Language.REST.SMT+import GHC.Stack (HasCallStack)  -- | Ground terms data RuntimeTerm = App Op [RuntimeTerm] deriving (Eq, Ord, Generic, Hashable)@@ -56,3 +62,21 @@ contains :: RuntimeTerm -> RuntimeTerm -> Bool contains t1 t2 | t1 == t2 = True contains (App _ ts) t     = any (contains t) ts++-- | Builds an ordering constraint algebra from a @step@ that translates+-- an ordering constraint to an 'SMTExpr'.+smtOCA+  :: HasCallStack+  => SolverHandle+  -> Text+  -> (RuntimeTerm -> RuntimeTerm -> SMTExpr Bool)+  -> IO (OCAlgebra (SMTExpr Bool) RuntimeTerm IO)+smtOCA z3 prefix step = do+    is <- newInternState prefix z3+    return $ OCAlgebra+      { isSat           = checkSat z3+      , refine          = \e t u -> internSMTExpr is $ smtAnd [e , step t u]+      , top             = smtTrue+      , union           = \e1 e2 -> smtOr [e1, e2]+      , notStrongerThan = \e1 e2 -> checkSat z3 (smtImplies e2 e1)+      }
src/Language/REST/SMT.hs view
@@ -1,11 +1,10 @@ {-# LANGUAGE AllowAmbiguousTypes #-}-{-# LANGUAGE DeriveAnyClass #-}-{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE InstanceSigs #-}+{-# LANGUAGE MagicHash #-}  {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-}@@ -19,35 +18,48 @@     checkSat   , checkSat'   , getModel+  , InternHandle+  , internSMTExpr+  , newInternState   , parseModel   , killZ3+  , sendCommands+  , sendCommandsNow   , spawnZ3   , smtAdd   , smtAnd+  , smtEqual+  , smtImplies+  , smtOr   , smtFalse   , smtGTE   , smtTrue   , withZ3   , SolverHandle-  , SMTExpr(..)+  , SMTExpr(Const, Greater)   , SMTVar(..)   , ToSMT(..)   , ToSMTVar(..)   , Z3Model ) where +import Control.Exception (bracket_)+import Control.Monad (unless) import Control.Monad.IO.Class import Data.Hashable+import Data.IORef import qualified Data.Map as M import qualified Data.List as L import qualified Data.Set as S import qualified Data.Text as T+import GHC.Base ((<#), dataToTag#) import System.Process import Text.Parsec (endBy) import Text.Parsec.Prim import Text.ParserCombinators.Parsec.Char-import GHC.Generics (Generic) import GHC.IO.Handle+import GHC.Stack (HasCallStack)+import Unsafe.Coerce (unsafeCoerce)  -- | A model returned by Z3 corresponding to a satisfiable --   set of constraints. Untyped.@@ -100,53 +112,64 @@     Const   :: Int            -> SMTExpr Int  -data UntypedExpr =-    UAnd [UntypedExpr]-  | UAdd [UntypedExpr]-  | UOr  [UntypedExpr]-  | UEqual  [UntypedExpr]-  | UGreater UntypedExpr UntypedExpr-  | UGTE UntypedExpr UntypedExpr-  | UImplies UntypedExpr UntypedExpr-  | UVar T.Text-  | UConst Int-  deriving (Show, Eq, Ord, Hashable, Generic)--toUntyped :: SMTExpr a -> UntypedExpr-toUntyped (And xs) = UAnd (map toUntyped xs)-toUntyped (Add xs) = UAdd (map toUntyped xs)-toUntyped (Or xs)  = UOr (map toUntyped xs)-toUntyped (Equal xs) = UEqual (map toUntyped xs)-toUntyped (Greater t u) = UGreater (toUntyped t) (toUntyped u)-toUntyped (GTE t u) = UGTE (toUntyped t) (toUntyped u)-toUntyped (Implies t u) = UImplies (toUntyped t) (toUntyped u)-toUntyped (Var (SMTVar text)) = UVar text-toUntyped (Const i) = UConst i--instance (Eq (SMTExpr a)) where-  t == u = toUntyped t == toUntyped u+instance Eq (SMTExpr a) where+  And xs == And ys = xs == ys+  Add xs == Add ys = xs == ys+  Or xs == Or ys   = xs == ys+  Equal xs == Equal ys = xs == unsafeCoerce ys+  Greater t1 u1 == Greater t2 u2 = t1 == t2 && u1 == u2+  GTE t1 u1 == GTE t2 u2 = t1 == t2 && u1 == u2+  Implies t1 u1 == Implies t2 u2 = t1 == t2 && u1 == u2+  Var (SMTVar v1) == Var (SMTVar v2) = v1 == v2+  Const c1 == Const c2 = c1 == c2+  _ == _ = False -instance (Ord (SMTExpr a)) where-  t <= u = toUntyped t <= toUntyped u+instance Ord (SMTExpr a) where+  And xs `compare` And ys = xs `compare` ys+  Add xs `compare` Add ys = xs `compare` ys+  Or xs `compare` Or ys   = xs `compare` ys+  Equal xs `compare` Equal ys = xs `compare` unsafeCoerce ys+  Greater t1 u1 `compare` Greater t2 u2 = (t1, u1) `compare` (t2, u2)+  GTE t1 u1 `compare` GTE t2 u2 = (t1, u1) `compare` (t2, u2)+  Implies t1 u1 `compare` Implies t2 u2 = (t1, u1) `compare` (t2, u2)+  Var (SMTVar v1) `compare` Var (SMTVar v2) = v1 `compare` v2+  Const c1 `compare` Const c2 = c1 `compare` c2+  a `compare` b =+    case dataToTag# a <# dataToTag# b of+      0# -> GT+      _ -> LT  instance Hashable (SMTExpr a) where-  hashWithSalt salt e = hashWithSalt salt (toUntyped e)+  hashWithSalt salt (And xs) = hashWithSalt salt (0 :: Int, xs)+  hashWithSalt salt (Add xs) = hashWithSalt salt (1 :: Int, xs)+  hashWithSalt salt (Or xs) = hashWithSalt salt (2 :: Int, xs)+  hashWithSalt salt (Equal xs) = hashWithSalt salt (3 ::Int, xs)+  hashWithSalt salt (Greater t u) = hashWithSalt salt (4 :: Int, t, u)+  hashWithSalt salt (GTE t u) = hashWithSalt salt (5 :: Int, t, u)+  hashWithSalt salt (Implies t u) = hashWithSalt salt (6 :: Int, t, u)+  hashWithSalt salt (Var (SMTVar v)) = hashWithSalt salt (7 :: Int, v)+  hashWithSalt salt (Const c) = hashWithSalt salt (8 :: Int, c)  instance Show (SMTExpr a) where   show = T.unpack . toFormula   toFormula :: SMTExpr a -> T.Text-toFormula = go False where-  go :: Bool -> SMTExpr a -> T.Text+toFormula = go 10 where+  go :: Int -> SMTExpr a -> T.Text   go _ (And [])         = "⊤"-  go p (And ts)         = eparens p $ T.intercalate " ∧ " $ map (go (not p)) ts-  go p (Add ts)         = eparens p $ T.intercalate " + " $ map (go (not p)) ts-  go p (GTE t u)        = eparens p $ T.intercalate " ≥ " $ map (go True) [t, u]-  go p (Greater t u)    = eparens p $ T.intercalate " > " $ map (go True) [t, u]+  go p (And ts)         = eparens (p <= 5) $ T.intercalate " ∧ " $ map (go 5) ts+  go p (Add ts)         = eparens (p <= 3) $ T.intercalate " + " $ map (go 3) ts+  go p (GTE t u)        = eparens (p <= 4) $ T.intercalate " ≥ " $ map (go 4) [t, u]+  go p (Greater t u)    = eparens (p <= 4) $ T.intercalate " > " $ map (go 4) [t, u]   go _ (Var (SMTVar v)) = v   go _ (Const c)        = T.pack (show c)-  go _ _e               = undefined+  go _ (Or [])          = "⊥"+  go p (Or ts)          = eparens (p <= 6) $ T.intercalate " ∨ " $ map (go 6) ts+  go p (Equal ts)+    | length ts < 2 = "⊤"+    | otherwise     = eparens (p <= 4) $ T.intercalate " = " $ map (go 4) ts+  go p (Implies t u)    = eparens (p <= 6) $ T.intercalate " ⇒ " $ map (go 6) [t, u]    eparens True t = T.concat ["(", t, ")"]   eparens False t = t@@ -162,7 +185,13 @@ vars (Implies e1 e2) = S.union (vars e1) (vars e2) vars (Const _)       = S.empty -data SMTCommand = SMTAssert (SMTExpr Bool) | DeclareVar T.Text | CheckSat | Push | Pop+data SMTCommand+    = SMTAssert (SMTExpr Bool)+    | DeclareVar T.Text+    | CheckSat+    | Push+    | Pop+    | DefineConst T.Text (SMTExpr Bool)  smtFalse :: SMTExpr Bool smtFalse = Or []@@ -176,13 +205,52 @@ smtAdd [] = Const 0 smtAdd ts = Add ts --- | `smtAnd t u` returns an smt expression representing \( t \land u \).-smtAnd :: SMTExpr Bool -> SMTExpr Bool -> SMTExpr Bool-smtAnd (And xs) (And ys) = And $ L.nub (xs ++ ys)-smtAnd (And xs) e        = And $ L.nub (xs ++ [e])-smtAnd e        (And ys) = And $ L.nub (e:ys)-smtAnd t        u        = And [t, u]+smtOr :: [SMTExpr Bool] -> SMTExpr Bool+smtOr xs0 =+    let xs1 = filter (not . isSmtFalse) $ concatMap flattenOr xs0+     in if any isSmtTrue xs1 then+          smtTrue+        else+          case L.nub xs1 of+            []  -> smtFalse+            [x] -> x+            xs2 -> Or xs2+  where+    flattenOr (Or xs) = xs+    flattenOr x      = [x] +isSmtFalse :: SMTExpr Bool -> Bool+isSmtFalse (Or []) = True+isSmtFalse _       = False++smtImplies :: SMTExpr Bool -> SMTExpr Bool -> SMTExpr Bool+smtImplies = Implies++smtEqual :: [SMTExpr a] -> SMTExpr Bool+smtEqual xs = case L.nub xs of+  []  -> smtTrue+  [_] -> smtTrue+  xs' -> Equal xs'++-- | `smtAnd ts` returns an smt expression representing \( t0 \land ... \land tn \).+smtAnd :: [SMTExpr Bool] -> SMTExpr Bool+smtAnd xs0 =+    let xs1 = filter (not . isSmtTrue) $ concatMap flattenAnd xs0+     in if any isSmtFalse xs1 then+          smtFalse+        else+          case L.nub xs1 of+            []  -> smtTrue+            [x] -> x+            xs2 -> And xs2+  where+    flattenAnd (And ys) = ys+    flattenAnd y       = [y]++isSmtTrue :: SMTExpr Bool -> Bool+isSmtTrue (And []) = True+isSmtTrue _        = False+ -- | `smtGTE t u` returns an SMT expression \( t \geqslant u \). If @t == u@, returns 'smtTrue'. smtGTE :: SMTExpr Int -> SMTExpr Int -> SMTExpr Bool smtGTE t u | t == u    = smtTrue@@ -211,10 +279,7 @@ commandString CheckSat = "(check-sat)" commandString Push     = "(push)" commandString Pop      = "(pop)"--askCmds :: SMTExpr Bool -> [SMTCommand]-askCmds expr = varDecls ++ [SMTAssert expr, CheckSat] where-  varDecls = map DeclareVar $ S.toList (vars expr)+commandString (DefineConst n e) = T.concat ["(define-fun ", n, " () Bool ", exprString e, ")"]  -- | The handle (stdIn, stdOut) used for interacting with Z3 type SolverHandle = (Handle, Handle)@@ -245,35 +310,43 @@   hPutStr stdIn "(get-model)\n"   hFlush stdIn --- | @checkSat' handles expr@ checks satisfiability of @expr@ in an instantiated SMT solver.---   This is wrapped in a @push@ / @pop@, so it does not change the SMT environment-checkSat' :: (Handle,  Handle) -> SMTExpr Bool -> IO Bool-checkSat' (stdIn, stdOut) expr = do-  sendCommands $ Push:askCmds expr-  result <- hGetLine stdOut-  sat <- case result of-    "sat"   -> do-      -- getModel stdIn-      -- model <- readModel stdOut-      -- putStrLn model-      return True-    "unsat" -> return False-    other   -> error other-  sendCommands [Pop]-  return sat+sendCommands :: (Handle, Handle) -> [SMTCommand] -> IO ()+sendCommands (stdIn, _) cmds = do+  hPutStr stdIn $ T.unpack (T.intercalate "\n" (map commandString cmds)) ++ "\n"++sendCommandsNow :: (Handle, Handle) -> [SMTCommand] -> IO ()+sendCommandsNow hs@(stdIn, _) cmds = do+  sendCommands hs cmds+  hFlush stdIn++-- | Like 'checkSat', but emits to the SMT solver any constant declarations+-- necessary to check the expression.+checkSat' :: HasCallStack => (Handle,  Handle) -> SMTExpr Bool -> IO Bool+checkSat' hs@(_, stdOut) expr = do+  bracket_ (sendCommandsNow hs [Push]) (sendCommands hs [Pop]) $ do+    sendCommandsNow hs $ Push : askCmds expr+    result <- hGetLine stdOut+    case result of+      "sat"   -> return True+      "unsat" -> return False+      other   -> error other   where-    sendCommands cmds = do-      hPutStr stdIn $ T.unpack (T.intercalate "\n" (map commandString cmds)) ++ "\n"-      hFlush stdIn+    askCmds :: SMTExpr Bool -> [SMTCommand]+    askCmds e =+      map DeclareVar (S.toList $ vars e) ++ [SMTAssert expr, CheckSat] --- | @checkSat expr@ launches Z3, to checks satisfiability of @expr@, terminating Z3---   afterwards. Just a utility wrapper for `checkSat'`-checkSat :: SMTExpr Bool -> IO Bool-checkSat expr = do-  z3     <- spawnZ3-  result <- checkSat' z3 expr-  killZ3 z3-  return result+-- | @checkSat handles expr@ checks satisfiability of @expr@ in an instantiated SMT solver.+--   This is wrapped in a @push@ / @pop@, so it does not change the SMT environment+checkSat :: HasCallStack => (Handle,  Handle) -> SMTExpr Bool -> IO Bool+checkSat hs@(_, stdOut) expr = do+  bracket_+    (sendCommandsNow hs [Push, SMTAssert expr, CheckSat])+    (sendCommands hs [Pop]) $ do+      result <- hGetLine stdOut+      case result of+        "sat"   -> return True+        "unsat" -> return False+        other   -> error $ "checkSat: solver said: " ++ other  -- | This class allows elements of type @a@ to be used as SMT /vaiables/ of type @b@. --   For example, the instance @ToSMTVar Op Int@ allows 'RuntimeTerm' operators to be@@ -292,3 +365,83 @@ instance {-# OVERLAPPABLE #-} (ToSMTVar a b) => ToSMT a b where   toSMT :: a -> SMTExpr b   toSMT op = Var $ toSMTVar op+++-- Interning ordering constraints+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+--+-- Ordering constraints can grow large with the repeated applications of the+-- 'refine' function. The size of the expressions grows linearly with the length+-- of a rewrite path.+--+-- For this reason the implementation interns ordering constraints by declaring+-- a binding for the result of each call to 'refine'. This binding is sent to+-- the SMT solver.+--+-- Later calls to refine that take the result as input receive the+-- bound variable instead.+--+-- Defining the binding requires declaring in advance all the variables+-- that the expression uses, which it is done during the 'refine' call as well.+--+-- The implementation keeps a list of bindings that have been defined+-- and variables that have been declared, so duplicate declarations are+-- avoided.+--+-- An alternative that was considered before https://github.com/zgrannan/rest/pull/48+-- was to reduce the expressions by simplifications, but this replicates+-- manipulations that the SMT solver already does, there is no guarantee+-- that the expressions admit being simplified enough to bound the size,+-- and different OCAlgebras would likely have to deal with the same problem.+--+++-- | A handle for interning SMT expressions. This is used to avoid sending the same+--  SMT expression to the solver multiple times, which can be inefficient.+data InternHandle = InternHandle+  { -- | Prefix to use for then names of interned expressions+    ihPrefix :: T.Text+    -- | Handle to the SMT solver to which the interned expressions are sent+  , ihSolver :: SolverHandle+    -- | State used to intern the SMT expressions produced by 'refine'+  , ihState  :: IORef InternState+  }++-- | State used to intern the SMT expressions produced by 'refine'.+data InternState = InternState+  { -- | The next integer to use for naming an interned expression+    isNext    :: Int+    -- | A map from SMT expressions to the names of their interned versions+  , isBinds :: M.Map (SMTExpr Bool) T.Text+    -- | The set of names of interned expressions+  , isBindNames :: S.Set T.Text+    -- | The set of variables of sort Int that have been declared in the SMT solver+  , isIntVars :: S.Set T.Text+  }++-- | Creates a new 'BindHandle' with the given prefix and SMT solver handle.+newInternState :: T.Text -> SolverHandle -> IO InternHandle+newInternState prefix sh = do+    InternHandle prefix sh+      <$> newIORef (InternState 0 M.empty S.empty S.empty)++-- | Interns the given SMT expression, returning a variable that represents it.+internSMTExpr :: InternHandle -> SMTExpr Bool -> IO (SMTExpr Bool)+internSMTExpr ih e = do+  st <- readIORef (ihState ih)+  case M.lookup e (isBinds st) of+    Just v  -> return $ Var $ SMTVar v+    Nothing -> do+      let newInts = vars e `S.difference` isBindNames st `S.difference` isIntVars st+      unless (S.null newInts) $+        sendCommands (ihSolver ih) (map DeclareVar (S.toList newInts))+      let n = isNext st+          v = ihPrefix ih <> T.pack (show n)+      writeIORef (ihState ih) st+        { isNext    = n + 1+        , isBinds = M.insert e v (isBinds st)+        , isBindNames = S.insert v (isBindNames st)+        , isIntVars = S.union (isIntVars st) newInts+        }+      sendCommands (ihSolver ih) [DefineConst v e]+      return $ Var $ SMTVar v
src/Language/REST/WQOConstraints.hs view
@@ -37,7 +37,7 @@ data WQOConstraints impl m = OC   {     -- | @addConstraint wqo c@ adds constraints to @c@ to also permit the WQO @w@.-    addConstraint       :: forall a. (Eq a, Ord a, Hashable a) => WQO a -> impl a -> impl a+    addConstraint       :: forall a. (ToSMTVar a Int, Eq a, Ord a, Hashable a) => WQO a -> impl a -> impl a      -- | @intersect c1 c2@ returns constraints to permit only WQOs permitted by both @c1@ and     --   @c2@. Therefore the resulting constraints are stronger (less likely to be@@ -70,7 +70,7 @@ isUnsatisfiable OC{isSatisfiable} c = not <$> isSatisfiable c  -- | Returns the constraints that permit a given WQO-singleton :: (Eq a, Ord a, Hashable a) => WQOConstraints oc m -> WQO a -> oc a+singleton :: (ToSMTVar a Int, Eq a, Ord a, Hashable a) => WQOConstraints oc m -> WQO a -> oc a singleton OC{addConstraint, noConstraints} c = addConstraint c noConstraints  -- | Given a list of constraints @ocs@, returns constraints that permit only the WQOs@@ -88,7 +88,7 @@ -- | @intersectRelation oc impl (f, g, r)@ strengthens constraints represented by @impl@ --   to also ensure that @f@ and @g@ are related via relation @r@ in permitted WQOs. intersectRelation ::-  (Ord a, Eq a, Ord a, Hashable a, Show a) =>+  (ToSMTVar a Int, Ord a, Eq a, Hashable a, Show a) =>   WQOConstraints oc m -> oc a -> (a, a, Relation) -> oc a intersectRelation oc impl (f, g, r) =   case nc r of
− src/Language/REST/WQOConstraints/ADT.hs
@@ -1,227 +0,0 @@-{-# LANGUAGE DeriveGeneric #-}-{-# LANGUAGE DeriveAnyClass #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE CPP #-}--#define OPTIMIZE_WQO--module Language.REST.WQOConstraints.ADT-  (  ConstraintsADT(..)-  , addConstraint-  , adtOC-  , intersect-  , union-  )-where--import GHC.Generics (Generic)--import Data.Hashable-import Control.Monad.State.Lazy-import qualified Data.Set as S-import qualified Data.Maybe as Mb-import qualified Data.Map.Strict as M-import qualified Language.REST.Internal.WQO as WQO-import qualified Language.REST.WQOConstraints as OC-import Language.REST.SMT-import Language.REST.Op-import System.IO (Handle)-import Text.Printf--type WQO = WQO.WQO---- | Represents constraints over a WQO on @a@-data ConstraintsADT a =- -- | @Sat wqo@ represents satisfiable constraints: those that permit each relation in @wqo@.-    Sat (WQO a)-  | Unsat-    -- | @Union c1 c2@ permits orderings of P1 and orderings of P2-  | Union (ConstraintsADT a) (ConstraintsADT a)-    -- | @Intersect c1 c2@ permits orderings iff permitted by P1 and permitted by P2-  | Intersect (ConstraintsADT a) (ConstraintsADT a)-  deriving (Eq, Ord, Generic, Hashable)--instance {-# OVERLAPPING #-} (ToSMTVar a Int) => ToSMT (ConstraintsADT a) Bool where-  toSMT (Sat w)           = toSMT w-  toSMT Unsat             = smtFalse-  toSMT (Union w1 w2)     = Or  [toSMT w1, toSMT w2]-  toSMT (Intersect w1 w2) = And [toSMT w1, toSMT w2]--{-# SPECIALIZE cost :: ConstraintsADT Op -> Int #-}-cost :: (Ord a, Eq a, Hashable a) => ConstraintsADT a -> Int-cost (Union lhs rhs)     = min (cost lhs) (cost rhs)-cost (Intersect lhs rhs) = cost lhs + cost rhs-cost (Sat wqo)           = S.size $ WQO.elems wqo-cost Unsat               = 100---- | @intersect c1 c2@ permits orderings iff permitted by P1 and permitted by P2-intersect :: (Eq a, Ord a, Hashable a) => ConstraintsADT a -> ConstraintsADT a -> ConstraintsADT a--#ifdef OPTIMIZE_WQO--- Optimization-intersect (Sat t) (Sat u) =-  maybe Unsat Sat (WQO.merge t u)-#endif--intersect (Sat w) v            | w == WQO.empty = v-intersect v            (Sat w) | w == WQO.empty = v-intersect _ Unsat     = Unsat-intersect Unsat _     = Unsat-intersect t1 t2 | t1 == t2 = t1-intersect t1 (Union t2 t3) | t1 == t2 || t1 == t3 = t1-#ifdef OPTIMIZE_WQO-intersect (Sat w1) (Intersect (Sat w2) t2) =-  case WQO.merge w1 w2 of-    Just w' -> Sat w' `intersect` t2-    Nothing -> Unsat-intersect (Sat w1) (Intersect t2 (Sat w2)) =-  case WQO.merge w1 w2 of-    Just w' -> Sat w' `intersect` t2-    Nothing -> Unsat-intersect (Intersect t1 (Sat w1)) (Sat w2) =-  case WQO.merge w1 w2 of-    Just w' -> t1 `intersect` Sat w'-    Nothing -> Unsat-intersect (Intersect (Sat w1) t1) (Sat w2) =-  case WQO.merge w1 w2 of-    Just w' -> t1 `intersect` Sat w'-    Nothing -> Unsat-#endif-intersect t1 t2            = Intersect t1 t2---- | @union c1 c2@ permits orderings of P1 and orderings of P2-union :: Eq a => ConstraintsADT a -> ConstraintsADT a -> ConstraintsADT a-union (Sat w) _            | w == WQO.empty = Sat w-union _            (Sat w) | w == WQO.empty = Sat w-union (Intersect a b)  c | a == c || b == c = c-union a (Intersect b c)  | a == b || a == c = a-union a (Union b c)      | a == b           = union a c-union Unsat s     = s-union s Unsat     = s-union c1 c2 | c1 == c2 = c1-union c1 c2            = Union c1 c2---- | @addConstraint o c@ strengthes @c@ to also contain every relation in @o@-addConstraint- :: (Ord a, Hashable a) => WQO a -> ConstraintsADT a -> ConstraintsADT a-addConstraint o = intersect (Sat o)--notStrongerThan-  :: (Eq a, ToSMTVar a Int)-  => ConstraintsADT a-  -> ConstraintsADT a-  -> SMTExpr Bool-notStrongerThan t1 t2 | t1 == t2            = smtTrue-notStrongerThan t1 _  | t1 == noConstraints = smtTrue-notStrongerThan t1 t2            = Implies (toSMT t2) (toSMT t1)--noConstraints :: ConstraintsADT a-noConstraints = Sat WQO.empty--unsatisfiable :: ConstraintsADT a-unsatisfiable = Unsat--{-# SPECIALIZE getConstraints :: ConstraintsADT Op -> [WQO Op] #-}-getConstraints :: forall a. (Show a, Ord a, Hashable a) => ConstraintsADT a -> [WQO a]-getConstraints adt = -- trace' ("Get constraints, size : " ++ (show $ dnfSize adt)) $-  evalState (getConstraints' adt) (GCState M.empty M.empty)--data GCState a = GCState {-    cs :: M.Map (ConstraintsADT a) (GCResult a)-  , ms :: M.Map (WQO a, WQO a) (Maybe (WQO a))-}--type GCResult a = [WQO a]--type GCMonad a = State (GCState a) (GCResult a)--cached :: (Ord a) => ConstraintsADT a -> GCMonad a -> GCMonad a-cached key thunk = do-  cache <- gets cs-  case M.lookup key cache of-    Just result -> trace'' "ADT Cache hit" $ return result-    Nothing     -> trace'' "ADT Cache miss" $ do-      result <- trace'' "Do thunk" thunk-      trace'' "Done" $ modify (\st -> st{cs = M.insert key result (cs st)})-      return result- where-   trace'' _  x = x-   -- trace' = trace--cached' :: (Hashable a, Show a, Ord a) => (WQO a, WQO a) -> Maybe (WQO a) -> State (GCState a) (Maybe (WQO a))-cached' (lhs, rhs) thunk = do-  cache <- gets ms-  case M.lookup (lhs, rhs) cache of-    Just result -> trace'' "WQO Cache hit" $ return result-    Nothing     -> trace'' ("WQO Cache miss" ++ show (lhs, rhs)) $ do-      trace'' "Done" $ modify (\st -> st{ms = M.insert (rhs, lhs) thunk $ M.insert (lhs, rhs) thunk (ms st)})-      return thunk- where-   trace'' _  x = x-   -- trace' = trace--getConstraints' :: forall a. (Show a, Ord a, Hashable a) => ConstraintsADT a -> State (GCState a) [WQO a]-getConstraints' (Sat w)         = return [w]-getConstraints' Unsat           = return []-getConstraints' c@(Union lhs rhs) =-  cached c $ do-    c1' <- cached c1 $ getConstraints' c1-    c2' <- cached c2 $ getConstraints' c2-    return $ c1' ++ c2'-  where-      (c1, c2) =-        if cost lhs < cost rhs-        then (lhs, rhs)-        else (rhs, lhs)-getConstraints' c@(Intersect lhs rhs) = cached c $ do-  c1' <- cached c1 $ getConstraints' c1-  if null c1'-    then return []-    else cached c2 (getConstraints' c2) >>= go c1'-  where-      go :: [WQO a] -> [WQO a] -> State (GCState a) [WQO a]-      go c1' c2' = flatten <$>-        sequence (do-          wqo1 <- c1'-          wqo2 <- c2'-          return (cached' (wqo1, wqo2) $ WQO.merge wqo1 wqo2))-      flatten = Mb.catMaybes-      (c1, c2) =-        if cost lhs > cost rhs-        then (lhs, rhs)-        else (rhs, lhs)--permits-  :: (Ord a, Hashable a, Show a)-  => ConstraintsADT a-  -> WQO.WQO a-  -> Bool-permits adt wqo = any (`WQO.notStrongerThan` wqo) (getConstraints adt)--isSatisfiable :: (ToSMTVar a Int, Show a, Eq a, Ord a, Hashable a) => ConstraintsADT a -> SMTExpr Bool-isSatisfiable = toSMT--instance (Eq a, Hashable a,  Show a) => Show (ConstraintsADT a) where-  show (Sat w)         = show w-  show Unsat           = "⊥"-  show (Union w t )    = printf "(%s ∨\n %s)" (show w) (show t)-  show (Intersect w t) = printf "(%s ∧ %s)" (show w) (show t)---- | See 'ConstraintsADT'-adtOC :: (Handle, Handle) -> OC.WQOConstraints ConstraintsADT IO-adtOC z3 = OC.liftC (checkSat' z3) adtOC'--adtOC' :: OC.WQOConstraints ConstraintsADT SMTExpr-adtOC' = OC.OC-  addConstraint-  intersect-  isSatisfiable-  notStrongerThan-  noConstraints-  permits-  union-  unsatisfiable-  undefined-
− src/Language/REST/WQOConstraints/Lazy.hs
@@ -1,120 +0,0 @@-{-# LANGUAGE DeriveGeneric #-}-{-# LANGUAGE DeriveAnyClass #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE ScopedTypeVariables #-}---- | This module defines "Lazy" constraints on a WQO; the intention is that---   computations on this type do only the necessary amount of work to determine---   satisfiability (deferring further computations in a thunk).-module Language.REST.WQOConstraints.Lazy (-      lazyOC-    , addConstraint-    , isSatisfiable-    , noConstraints-    , LazyOC-    ) where--import Text.Printf-import GHC.Generics (Generic)-import Data.Hashable--import qualified Language.REST.Internal.WQO as WQO-import qualified Language.REST.WQOConstraints as OC-import qualified Language.REST.WQOConstraints.ADT as ADT--type WQO = WQO.WQO---- Partially lazy ordering constraints:--- thunks computation after showing satisfiability--type Thunk a = ADT.ConstraintsADT a---- | Implementation of "Lazy" ordering constraints.-data LazyOC a =-    Unsat-    -- @Sat wqo thunk@ represent satisfiable constraints; @wqo@ is a candidate.-    -- @Thunk@ represents the other satisfiable constraints, if any.-  | Sat (WQO a) (Thunk a)-  deriving (Eq, Ord, Generic, Hashable)--getOrdering :: LazyOC a -> Maybe (WQO a)-getOrdering (Sat wqo _) = Just wqo-getOrdering _           = Nothing--eval :: (Eq a, Ord a, Hashable a) => ADT.ConstraintsADT a -> LazyOC a-eval (ADT.Sat w)   = Sat w ADT.Unsat-eval ADT.Unsat     = Unsat-eval (ADT.Union lhs rhs) =-  case eval lhs of-    Sat w t1' -> Sat w (ADT.union t1' rhs)-    Unsat     -> eval rhs--eval (ADT.Intersect t1 t2)       =-  case (eval t1, eval t2) of-    (Sat c1 t1', Sat c2 t2') ->-      let-        rest =-          ADT.intersect (ADT.Sat c1) t2' `ADT.union`-          ADT.intersect (ADT.Sat c2) t1' `ADT.union`-          ADT.intersect t1' t2'-      in-        case WQO.merge c1 c2 of-          Just c' -> Sat c' rest-          Nothing -> eval rest-    _ -> Unsat---toADT :: Eq a => LazyOC a -> ADT.ConstraintsADT a-toADT Unsat     = ADT.Unsat-toADT (Sat w r) = ADT.union (ADT.Sat w) r--instance (Show a, Eq a, Ord a, Hashable a) => Show (LazyOC a) where-  show Unsat     = "⊥"-  show (Sat s r) = printf "%s ∨ lazy(%s)" (show s) (show r)---- | Returns a new instance of 'LazyOC' permitting all WQOs-noConstraints :: LazyOC a-noConstraints = Sat WQO.empty ADT.Unsat--unsatisfiable :: LazyOC a-unsatisfiable = Unsat--union :: Eq a => LazyOC a -> LazyOC a -> LazyOC a-union Unsat s                 = s-union s Unsat                 = s-union (Sat s _)    _          | s == WQO.empty = noConstraints-union _           (Sat s _)   | s == WQO.empty = noConstraints-union (Sat s1 r1) (Sat s2 r2) = Sat s1 (ADT.union (ADT.Sat s2) (ADT.union r1 r2))--intersect :: (Ord a, Hashable a) => LazyOC a -> LazyOC a -> LazyOC a-intersect t1 t2 = eval $ ADT.intersect (toADT t1) (toADT t2)---- | Returns @true@ if any orderings are permitted-isSatisfiable :: LazyOC a -> Bool-isSatisfiable (Sat _ _) = True-isSatisfiable Unsat     = False--notStrongerThan :: (Monad m, Eq a) => LazyOC a -> LazyOC a -> m Bool-notStrongerThan _     Unsat = return True-notStrongerThan t1    t2    = return $ t1 == t2---- | @addConstraint o c@ strengthes @c@ to also contain every relation in @o@-addConstraint :: (Ord a, Hashable a) => WQO a -> LazyOC a -> LazyOC a-addConstraint o c = eval $ ADT.addConstraint o (toADT c)--permits :: (Ord a, Hashable a) => LazyOC a -> WQO.WQO a -> Bool-permits Unsat _            = False-permits (Sat s1 thunk) wqo = s1 `WQO.notStrongerThan` wqo || permits (eval thunk) wqo---- | See 'LazyOC'-lazyOC :: Monad m => OC.WQOConstraints LazyOC m-lazyOC = OC.OC-  addConstraint-  intersect-  (return . isSatisfiable)-  notStrongerThan-  noConstraints-  permits-  union-  unsatisfiable-  getOrdering
+ src/Language/REST/WQOConstraints/SMT.hs view
@@ -0,0 +1,61 @@+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE ScopedTypeVariables #-}++module Language.REST.WQOConstraints.SMT+  ( SMTConstraint(..)+  , smtOC+  ) where++import Data.Hashable+import Language.REST.SMT+import qualified Language.REST.Internal.WQO as WQO+import qualified Language.REST.WQOConstraints as OC++-- | An ordering constraint represented directly as an SMT expression. The type+--   parameter is only used so this type can serve as the @oc@ of 'OC.WQOConstraints'.+newtype SMTConstraint a = SMTConstraint { unSMTConstraint :: SMTExpr Bool }+  deriving (Eq, Ord, Show)++instance Hashable (SMTConstraint a) where+  hashWithSalt salt (SMTConstraint e) = hashWithSalt salt e++instance ToSMT (SMTConstraint a) Bool where+  toSMT = unSMTConstraint++-- | An SMT-expression-based implementation of ordering constraints.+smtOC :: SolverHandle -> OC.WQOConstraints SMTConstraint IO+smtOC z3 = OC.OC+  addConstraint+  intersect+  (checkSat' z3 . unSMTConstraint)+  (notStrongerThan z3)+  noConstraints+  permits+  union+  unsatisfiable+  getOrdering++addConstraint :: (ToSMTVar a Int, Eq a, Ord a, Hashable a) => WQO.WQO a -> SMTConstraint a -> SMTConstraint a+addConstraint wqo c = SMTConstraint (smtAnd [unSMTConstraint c, toSMT wqo])++intersect :: SMTConstraint a -> SMTConstraint a -> SMTConstraint a+intersect (SMTConstraint e1) (SMTConstraint e2) = SMTConstraint (smtAnd [e1, e2])++union :: SMTConstraint a -> SMTConstraint a -> SMTConstraint a+union (SMTConstraint e1) (SMTConstraint e2) = SMTConstraint (smtOr [e1, e2])++noConstraints :: SMTConstraint a+noConstraints = SMTConstraint smtTrue++unsatisfiable :: SMTConstraint a+unsatisfiable = SMTConstraint smtFalse++notStrongerThan :: SolverHandle -> SMTConstraint a -> SMTConstraint a -> IO Bool+notStrongerThan z3 t1 t2 = checkSat' z3 (smtImplies (unSMTConstraint t2) (unSMTConstraint t1))++permits :: SMTConstraint a -> WQO.WQO a -> Bool+permits _ _ = error "unreachable: SMTConstraint has no WQO extraction"++getOrdering :: SMTConstraint a -> Maybe (WQO.WQO a)+getOrdering _ = Nothing
test/BagExample.hs view
@@ -23,7 +23,7 @@ import Language.REST.WQOConstraints.Strict as SC import Language.REST.Internal.WorkStrategy import Language.REST.Types-import Language.REST.SMT hiding (GTE)+import Language.REST.SMT  import qualified Data.List as L import qualified Data.HashSet as S
test/ExploredTerms.hs view
@@ -10,6 +10,9 @@  import Language.REST.ExploredTerms as ET +import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool)+ type Constraints = Int  -- 2nd argument is cost to explore@@ -19,7 +22,7 @@ exploreFuncs :: ExploreFuncs Term Constraints Identity exploreFuncs = EF undefined subsume refine where   subsume c0 c1               = return $ c0 >= c1-  refine  c  _  (Term _ dest) = c - dest+  refine  c  _  (Term _ dest) = return $ c - dest  t0 :: Term t0 = Term "t0" 5@@ -36,10 +39,9 @@ et :: ExploredTerms Term Constraints Identity et = ET.insert t1 15 (S.fromList [t0]) $ ET.insert t0 14 (S.fromList [t2]) et0 -tests :: [(String, Bool)]-tests =+tests :: TestTree+tests = testGroup "ExploredTerms"   [ -- Described in https://github.com/zgrannan/rest/issues/9-    ("Explore-opt", not $ runIdentity $ shouldExplore t1 17 et)--  , ("Explore", runIdentity $ shouldExplore t1 21 et)+    testCase "Explore-opt" $ assertBool "Explore-opt" $ not $ runIdentity $ shouldExplore t1 17 et+  , testCase "Explore" $ assertBool "Explore" $ runIdentity $ shouldExplore t1 21 et   ]
test/KBO.hs view
@@ -2,20 +2,21 @@  module KBO where -import Language.REST.OCAlgebra import Language.REST.KBO import Language.REST.SMT import Language.REST.RuntimeTerm import Nat () -- IsString RuntimeTerm -tests :: SolverHandle -> [(String, IO Bool)]-tests solver = testList where--  gte :: RuntimeTerm ->  RuntimeTerm -> IO Bool-  gte t u = isSat (kbo solver) (kboGTE t u)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool) -  testList =-    [ ("Comm"  , gte "f(a, b)" "f(b, a)")-    , ("Assoc" , gte "f(a, f(b, c))"  "f((a b), c)")-    , ("Dist"  , not <$> gte "f(a, g(b, c))" "g(f(a, b), f(a, c))")-    ]+tests :: TestTree+tests = testGroup "KBO"+  [ testCase "Comm"  $ gte "f(a, b)" "f(b, a)" >>= assertBool "Comm"+  , testCase "Assoc" $ gte "f(a, f(b, c))"  "f((a b), c)" >>= assertBool "Assoc"+  , testCase "Dist"  $ gte "f(a, g(b, c))" "g(f(a, b), f(a, c))" >>= assertBool "Dist" . not+  ]+  where+    gte :: RuntimeTerm ->  RuntimeTerm -> IO Bool+    gte t u = withZ3 $ \hs ->+      checkSat' hs (kboGTE t u)
+ test/LPOEquiv.hs view
@@ -0,0 +1,68 @@+{-# LANGUAGE OverloadedStrings #-}++-- | Checks that the direct SMT translations of LPO ('lpoSMTRel' and+--   'lpoStrictSMTRel') are logically equivalent to the SMT translations obtained+--   by running the polymorphic 'lpo'/'lpoStrict' generators with 'SMTConstraint'.+module LPOEquiv where++import Prelude hiding (GT, EQ)++import Control.Monad.Identity (runIdentity)++import Language.REST.SMT+import Language.REST.Types (Relation(..))+import Language.REST.RuntimeTerm+import Language.REST.LPO (lpoSMTRel, lpoStrictSMTRel, lpo, lpoStrict)+import Language.REST.WQOConstraints as OC+import Language.REST.WQOConstraints.SMT (smtOC)+import Nat () -- IsString RuntimeTerm++import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool)++tests :: SolverHandle -> TestTree+tests z3 =+  testGroup "LPOEquiv"+    [ testCase label $ equiv z3 (step strict r t u) (ref z3 strict r t u) >>= assertBool label+    | (label, strict, r, t, u) <- cases+    ]+  where+    step :: Bool -> Relation -> RuntimeTerm -> RuntimeTerm -> SMTExpr Bool+    step True  = lpoStrictSMTRel+    step False = lpoSMTRel++    cases :: [(String, Bool, Relation, RuntimeTerm, RuntimeTerm)]+    cases =+      [ ("gte-same"        , False, GTE, "f(a)"      , "f(a)")+      , ("gte-lex"         , False, GTE, "f(a, b)"   , "f(b, a)")+      , ("lex-skip-apply"  , False, GTE, "f(a, b)"   , "f(a, c)")+      , ("gte-diff-head"   , False, GTE, "f(a)"      , "g(a)")+      , ("eq-diff-arity"   , False, EQ , "f(a)"      , "g(a, b)")+      , ("eq-same-arity"   , False, EQ , "f(a)"      , "g(b)")+      , ("gt-same"         , False, GT , "f(a)"      , "f(a)")+      , ("strict-gte"      , True , GTE, "f(a, b)"   , "f(b, a)")+      , ("strict-eq-same"  , True , EQ , "f(a)"      , "f(a)")+      , ("strict-eq-diff"  , True , EQ , "f(a)"      , "g(a)")+      , ("strict-gt"       , True , GT , "f(a, b)"   , "f(b, a)")+      , ("strict-lex-skip"  , True , GTE, "f(a, b)"   , "f(a, c)")+      , ("empty-left"      , False, GTE, "f"         , "f(a)")+      , ("empty-right"     , False, GTE, "f(a)"      , "f")+      , ("empty-both"      , False, GTE, "f"         , "f")+      ]++-- | Reference: the polymorphic LPO generator instantiated with 'SMTConstraint'.+ref :: SolverHandle -> Bool -> Relation -> RuntimeTerm -> RuntimeTerm -> SMTExpr Bool+ref z3 strict r t u =+  toSMT (runIdentity (gen strict (smtOC z3) r (OC.noConstraints (smtOC z3)) t u))+  where+    gen True  = lpoStrict+    gen False = lpo++notE :: SMTExpr Bool -> SMTExpr Bool+notE p = smtImplies p smtFalse++iff :: SMTExpr Bool -> SMTExpr Bool -> SMTExpr Bool+iff a b = smtAnd [smtImplies a b, smtImplies b a]++equiv :: SolverHandle -> SMTExpr Bool -> SMTExpr Bool -> IO Bool+equiv z3 e1 e2 = not <$> checkSat' z3 (notE (iff e1 e2))
− test/LazyOC.hs
@@ -1,16 +0,0 @@-module LazyOC where--import Data.Maybe-import Language.REST.WQOConstraints.Lazy as LC-import Language.REST.Internal.OpOrdering--oo :: String -> OpOrdering-oo = fromJust . parseOO--tests :: [(String, Bool)]-tests = [-  ("intersect",-    not $ LC.isSatisfiable $ LC.addConstraint (oo "g > f")-    (LC.addConstraint (oo "f > g ^ f > s") LC.noConstraints)-  )-  ]
test/Main.hs view
@@ -25,6 +25,7 @@ import NonTerm as NT import qualified Lists as Li +import Language.REST (rpoOCA, lpoOCA, lpoStrictOCA) import Language.REST.Core import Language.REST.ConcreteOC import Language.REST.ExploredTerms@@ -33,10 +34,8 @@ import Language.REST.Op import Language.REST.WQOConstraints as OC import qualified Language.REST.WQOConstraints.Strict as SC-import qualified Language.REST.WQOConstraints.ADT    as AC import Language.REST.KBO (kbo)-import Language.REST.LPO (lpo, lpoStrict)-import Language.REST.RPO+import Language.REST.LPO (lpo) import Language.REST.ProofGen import Language.REST.Rest import Language.REST.Types@@ -77,7 +76,8 @@       do         mapM_ (explain (refine impl (top impl))) pairs         printf "Result:\n%s\n" (show $ orient impl ts)-        isSatisfiable SC.strictOC (orient impl ts) >>= print+        let cs = runIdentity $ orient impl ts+        isSatisfiable SC.strictOC cs >>= print     where       impl :: OCAlgebra (SC.StrictOC Op) RuntimeTerm Identity       impl = lift SC.strictOC lpo@@ -119,15 +119,23 @@   -> GraphParams   -> IO () mkRESTGraph LPOStrict evalRWs0 userRWs0 name term0 params =-  withZ3 $ \z3 -> mkRESTGraph' (lift (AC.adtOC z3) lpoStrict) evalRWs0 userRWs0 name term0 params+  withZ3 $ \z3 -> do+    oca <- lpoStrictOCA z3 "$R0_"+    mkRESTGraph' oca evalRWs0 userRWs0 name term0 params mkRESTGraph LPO evalRWs0 userRWs0 name term0 params =-  withZ3 $ \z3 -> mkRESTGraph' (lift (AC.adtOC z3) lpo) evalRWs0 userRWs0 name term0 params+  withZ3 $ \z3 -> do+    oca <- lpoOCA z3 "$R1_"+    mkRESTGraph' oca evalRWs0 userRWs0 name term0 params mkRESTGraph RPO evalRWs0 userRWs0 name term0 params =-  withZ3 $ \z3 -> mkRESTGraph' (lift (AC.adtOC z3) rpo) evalRWs0 userRWs0 name term0 params+  withZ3 $ \z3 -> do+    oca <- rpoOCA z3 "$R2_"+    mkRESTGraph' oca evalRWs0 userRWs0 name term0 params mkRESTGraph (RPOConcrete ops) evalRWs0 userRWs0 name term0 params =   mkRESTGraph' (concreteOC $ DS.fromList ops) evalRWs0 userRWs0 name term0 params mkRESTGraph KBO evalRWs0 userRWs0 name term0 params =-  withZ3 $ \z3 -> mkRESTGraph' (kbo z3) evalRWs0 userRWs0 name term0 params+  withZ3 $ \z3 -> do+    oca <- kbo z3 "$R3_"+    mkRESTGraph' oca evalRWs0 userRWs0 name term0 params mkRESTGraph (Fuel n) evalRWs0 userRWs0 name term0 params =   mkRESTGraph' (fuelOC n) evalRWs0 userRWs0 name term0 params 
test/MultisetOrder.hs view
@@ -1,8 +1,9 @@+{-# LANGUAGE OverloadedStrings #-}+ module MultisetOrder where  import Prelude hiding (GT) - import Control.Monad.Identity  import Language.REST.Internal.MultiSet as M@@ -10,28 +11,33 @@ import Language.REST.WQOConstraints.Strict as SC import Language.REST.WQOConstraints as OC import Language.REST.Types+import Language.REST.Op -compareChar :: ConstraintGen impl Char Char Identity-compareChar impl r oc c1 c2 = Identity $ intersectRelation impl oc (c1, c2, r)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool) -existingOC :: StrictOC Char-existingOC = OC.intersectRelation strictOC' SC.noConstraints ('a', 'c', GTE)+compareOp :: ConstraintGen impl Op Op Identity+compareOp impl r oc c1 c2 = Identity $ intersectRelation impl oc (c1, c2, r) -ms :: StrictOC Char -> MultiSet Char -> MultiSet Char -> Identity (StrictOC Char)-ms = multisetOrder compareChar strictOC' GTE+existingOC :: StrictOC Op+existingOC = OC.intersectRelation strictOC' SC.noConstraints (Op "a", Op "c", GTE) -multisetNext :: Identity (StrictOC Char)-multisetNext = ms existingOC (M.fromList "bac") (M.fromList "aaaa")+ms :: StrictOC Op -> MultiSet Op -> MultiSet Op -> Identity (StrictOC Op)+ms = multisetOrder compareOp strictOC' GTE -unsat :: Identity (StrictOC Char)+multisetNext :: Identity (StrictOC Op)+multisetNext = ms existingOC (M.fromList [Op "b", Op "a", Op "c"]) (M.fromList (replicate 4 (Op "a")))++unsat :: Identity (StrictOC Op) unsat = do   mn <- multisetNext-  return $ OC.intersectRelation strictOC' mn ('c', 'a', GT)+  return $ OC.intersectRelation strictOC' mn (Op "c", Op "a", GT) -tests :: [(String, Bool)]-tests = [-    ("Constraints",-     SC.noConstraints /=-     runIdentity (ms SC.noConstraints (M.fromList "bc") (M.fromList "aa")))-  , ("Unsat", SC.isUnsatisfiable $ runIdentity unsat)+tests :: TestTree+tests = testGroup "MultisetOrder"+  [ testCase "Constraints" $ assertBool "Constraints" $+      SC.noConstraints /=+        runIdentity (ms SC.noConstraints (M.fromList [Op "b", Op "c"]) (M.fromList [Op "a", Op "a"]))+  , testCase "Unsat" $ assertBool "Unsat" $+      SC.isUnsatisfiable $ runIdentity unsat   ]
test/OpOrdering.hs view
@@ -6,23 +6,26 @@ import Language.REST.Internal.WQO import Data.Maybe as Mb -tests :: [(String, Bool)]-tests = [-  ("parse",-     fromJust (-      parseOO "cons = z ∧ g = nil ∧ h = s ∧ cons > g ∧ cons > h ∧ h > f ∧ h > g"-     ) == wqo)-  ,("minimal",-    fromJust (-      parseOO "f > + ^ g > z ^ + = cons ^ cons > z ^ f = g"-    ) ==-    fromJust (-      parseOO "f > + ^ + = cons ^ cons > z ^ f = g"-    )-  ) ]-        where+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool) -        Just wqo = mergeAll [ "cons" =. "z"+tests :: TestTree+tests = testGroup "OpOrdering"+  [ testCase "parse" $ assertBool "parse" $+      fromJust (+        parseOO "cons = z ∧ g = nil ∧ h = s ∧ cons > g ∧ cons > h ∧ h > f ∧ h > g"+      ) == wqo+  , testCase "minimal" $ assertBool "minimal" $+      fromJust (+        parseOO "f > + ^ g > z ^ + = cons ^ cons > z ^ f = g"+      ) ==+      fromJust (+        parseOO "f > + ^ + = cons ^ cons > z ^ f = g"+      )+  ]+    where++        wqo = fromJust $ mergeAll [ "cons" =. "z"                 , "g" =. "nil"                 , "h" =. "s"                 , "cons" >. "g"
test/QuickCheckTests.hs view
@@ -6,8 +6,14 @@  import Test.QuickCheck import Test.QuickCheck.Monadic+import Test.Tasty (TestTree, testGroup, localOption)+import Test.Tasty.QuickCheck+  ( testProperty+  , QuickCheckTests(..)+  , QuickCheckMaxSize(..)+  , QuickCheckMaxRatio(..)+  ) -import Control.Monad.Identity import Data.Hashable (Hashable) import Data.Maybe as Mb import qualified Data.Text as T@@ -16,7 +22,6 @@ import qualified Language.REST.Internal.WQO as WQO import qualified Language.REST.WQOConstraints        as OC import qualified Language.REST.WQOConstraints.Strict as SC-import qualified Language.REST.WQOConstraints.Lazy   as LC import           Language.REST.RPO import           Language.REST.Op import           Language.REST.RuntimeTerm@@ -148,17 +153,19 @@ --   where --     types = t0::RuntimeTerm -tests :: IO [()]-tests = sequence-        [-        --  quickCheckWith stdArgs{maxDiscardRatio = 1000} prop_rpot2-          quickCheckWith stdArgs prop_permits-        , quickCheckWith stdArgs{maxDiscardRatio = 1000} prop_poTrans-        , quickCheckWith stdArgs{maxDiscardRatio = 100} prop_wqoTrans-        , putStrLn "Transitivity of RPO:"-        , quickCheckWith stdArgs{maxDiscardRatio = 100} prop_rpoTrans-        , putStrLn "RPO aligns with concrete:"-        , quickCheckWith stdArgs{maxSize = 10, maxSuccess = 20, maxDiscardRatio = 100} (prop_rpoCons ?impl)-        ]+tests :: TestTree+tests = testGroup "QuickCheck"+  [ testProperty "permits" prop_permits+  , localOption (QuickCheckMaxRatio 1000) $+      testProperty "poTrans" prop_poTrans+  , localOption (QuickCheckMaxRatio 100) $+      testProperty "wqoTrans" prop_wqoTrans+  , localOption (QuickCheckMaxRatio 100) $+      testProperty "rpoTrans" prop_rpoTrans+  , localOption (QuickCheckMaxSize 10) $+      localOption (QuickCheckTests 20) $+        localOption (QuickCheckMaxRatio 100) $+          testProperty "rpoCons" (prop_rpoCons ?impl)+  ]   where-    ?impl = LC.lazyOC+    ?impl = SC.strictOC
test/RPO.hs view
@@ -1,5 +1,6 @@ {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}  module RPO where @@ -8,12 +9,16 @@ import Language.REST.Op import Language.REST.Internal.OpOrdering as OpOrdering import Language.REST.WQOConstraints as OC+import qualified Language.REST.WQOConstraints.Strict as SC (strictOC) import Language.REST.RuntimeTerm import Language.REST.RPO import Language.REST.Internal.WQO  import Data.Maybe as Mb +import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool)+ bigLeft, bigRight :: RuntimeTerm bigLeft = "f(h(s(g(z,nil))),f(g(z,z),nil,h(z)),f(z,nil,z) + g(z,s(z)))" bigRight = "g(g(g(s(nil),z),s(z) + z),g(s(s(h(nil))),s(z)))"@@ -52,29 +57,44 @@   go c _        = c  -tests :: (Hashable (oc Op), Eq (oc Op), Show (oc Op)) => (?impl :: WQOConstraints oc IO) => [(String, IO Bool)]+tests :: TestTree tests =+  let ?impl = SC.strictOC @IO in   let     f = Op "f"     g = Op "g"     h = Op "h"   in-    [ ("RPO1",   return $ rpoGTE "f(z)" "g(s(z))"-              == OC.intersect ?impl (OC.singleton ?impl (f >. g)) (OC.singleton ?impl (f >. s)))-    , ("RPO2", isUnsatisfiable ?impl $-         OC.intersect ?impl-           (rpoGTE "f(z)" "g(s(z))")-           (rpoGTE "g(s(z))" "f(h(z))"))-    , ("RPO3", isSatisfiable ?impl (rpoGTE bigLeft bigRight))-    , ("RPO4", isUnsatisfiable ?impl (rpoGTE massiveLeft massiveRight))-    , ("RPO5", isSatisfiable ?impl (rpoGTE listsLeft listsRight))-    , ("RPO6", isSatisfiable ?impl (rpoGTE flattenLeft2 flattenRight2))-    , ("RPOOrient", isUnsatisfiable ?impl $ rpoSeq flattenSeq)-    , ("SynGTE", return $ synGTE OpOrdering.empty (App s [App s [App g [App (Op "+") [App h [App s [App z []]],App z []],App s [App s [App g [App z [],App z []]]]]]]) (App z []))-    , ("SynGTE2",-        return $ synGTE (Mb.fromJust $ mergeAll [-          "cons" >. g-        , f >. s-        , h >. g-        , h >. "nil"]) "s(cons(h(h(z)), f(nil, nil, z)))"  "g(z, cons(g(nil, nil), s(s(z))))")+    testGroup "RPO"+      [ testCase "RPO1" $ assertBool "RPO1" $+          rpoGTE "f(z)" "g(s(z))"+            == OC.intersect ?impl (OC.singleton ?impl (f >. g)) (OC.singleton ?impl (f >. s))+      , testCase "SynGTE" $ assertBool "SynGTE" $+          synGTE OpOrdering.empty (App s [App s [App g [App (Op "+") [App h [App s [App z []]],App z []],App s [App s [App g [App z [],App z []]]]]]]) (App z [])+      , testCase "SynGTE2" $ assertBool "SynGTE2" $+          synGTE (Mb.fromJust $ mergeAll [+            "cons" >. g+          , f >. s+          , h >. g+          , h >. "nil"]) "s(cons(h(h(z)), f(nil, nil, z)))"  "g(z, cons(g(nil, nil), s(s(z))))"+      ]++-- | Satisfiability tests. These must run against a solver-backed instance+--   ('smtOC'), because folding a long RPO sequence through a DNF instance+--   ('Strict') expands exponentially.+solverTests :: (Hashable (oc Op), Eq (oc Op), Show (oc Op)) => (?impl :: WQOConstraints oc IO) => TestTree+solverTests =+  testGroup "RPO-solver"+    [ testCase "RPO2" $ do+        isUnsat <- isUnsatisfiable ?impl+          ( OC.intersect ?impl+              (rpoGTE "f(z)" "g(s(z))")+              (rpoGTE "g(s(z))" "f(h(z))")+          )+        assertBool "RPO2" isUnsat+    , testCase "RPO3" $ isSatisfiable ?impl (rpoGTE bigLeft bigRight) >>= assertBool "RPO3"+    , testCase "RPO4" $ isUnsatisfiable ?impl (rpoGTE massiveLeft massiveRight) >>= assertBool "RPO4"+    , testCase "RPO5" $ isSatisfiable ?impl (rpoGTE listsLeft listsRight) >>= assertBool "RPO5"+    , testCase "RPO6" $ isSatisfiable ?impl (rpoGTE flattenLeft2 flattenRight2) >>= assertBool "RPO6"+    , testCase "RPOOrient" $ isUnsatisfiable ?impl (rpoSeq flattenSeq) >>= assertBool "RPOOrient"     ]
+ test/RPOEquiv.hs view
@@ -0,0 +1,59 @@+{-# LANGUAGE OverloadedStrings #-}++-- | Checks that the direct SMT translation of RPO ('rpoSMTRel') is logically+--   equivalent to the SMT translation obtained by running the polymorphic+--   'rpo' generator with the 'SMTConstraint' implementation.+module RPOEquiv where++import Prelude hiding (GT, EQ)++import Control.Monad.Identity (runIdentity)++import Language.REST.SMT+import Language.REST.Types (Relation(..))+import Language.REST.RuntimeTerm+import Language.REST.RPO (rpoSMTRel, rpo)+import Language.REST.WQOConstraints as OC+import Language.REST.WQOConstraints.SMT (smtOC)+import Nat () -- IsString RuntimeTerm++import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool)++tests :: SolverHandle -> TestTree+tests z3 =+  testGroup "RPOEquiv"+    [ testCase label $ equiv z3 (rpoSMTRel r t u) (ref z3 r t u) >>= assertBool label+    | (label, r, t, u) <- cases+    ]+  where+    cases :: [(String, Relation, RuntimeTerm, RuntimeTerm)]+    cases =+      [ ("eq-gte"          , GTE, "f(a)"          , "f(a)")+      , ("subterm-l"       , GTE, "f(a)"          , "a")+      , ("subterm-r"       , GTE, "a"             , "f(a)")+      , ("head-same"       , GTE, "f(a, b)"       , "f(b, a)")+      , ("head-diff"       , GTE, "f(a)"          , "g(a)")+      , ("nested"          , GTE, "f(g(a), b)"    , "f(h(a), c)")+      , ("deep"            , GTE, "f(g(h(a)))"    , "g(a)")+      , ("two-args"        , GTE, "f(a, g(b))"    , "f(g(c), d)")+      , ("empty-left"      , GTE, "f"             , "f(a)")+      , ("empty-right"     , GTE, "f(a)"          , "f")+      , ("empty-both"      , GTE, "f"             , "f")+      , ("gt-equal"        , GT , "f(a)"          , "f(a)")+      , ("eq-equal"        , EQ , "f(a)"          , "f(a)")+      , ("gt-subterm-r"    , GT , "a"             , "f(a)")+      ]++-- | Reference: the polymorphic RPO generator instantiated with 'SMTConstraint'.+ref :: SolverHandle -> Relation -> RuntimeTerm -> RuntimeTerm -> SMTExpr Bool+ref z3 r t u = toSMT (runIdentity (rpo (smtOC z3) r (OC.noConstraints (smtOC z3)) t u))++notE :: SMTExpr Bool -> SMTExpr Bool+notE p = smtImplies p smtFalse++iff :: SMTExpr Bool -> SMTExpr Bool -> SMTExpr Bool+iff a b = smtAnd [smtImplies a b, smtImplies b a]++equiv :: SolverHandle -> SMTExpr Bool -> SMTExpr Bool -> IO Bool+equiv z3 e1 e2 = not <$> checkSat' z3 (notE (iff e1 e2))
test/SMT.hs view
@@ -3,6 +3,9 @@ import Language.REST.SMT import qualified Data.Map as M +import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool)+ model :: String model = "(\n\  \ (define-fun op_j () Int \n\@@ -26,5 +29,8 @@   , ("op_<", "5")   ] -tests :: [(String, Bool)]-tests = [("Parse SMT Model", parseModel model == expected)]+tests :: TestTree+tests = testGroup "SMT"+  [ testCase "Parse SMT Model" $+      assertBool "Parse SMT Model" (parseModel model == expected)+  ]
+ test/SMTExprInstances.hs view
@@ -0,0 +1,394 @@+{-# LANGUAGE OverloadedStrings #-}++-- | Exercises the hand-written 'Eq', 'Ord' and 'Hashable' instances of 'SMTExpr'+module SMTExprInstances where++import Data.Hashable (hashWithSalt)+import Language.REST.Op (Op (..))+import Language.REST.SMT+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool)++eqCase :: String -> SMTExpr a -> SMTExpr a -> Bool -> TestTree+eqCase label x y expected =+  testCase label $ assertBool label $ (x == y) == expected++ordCase :: String -> SMTExpr a -> SMTExpr a -> Ordering -> TestTree+ordCase label x y expected =+  testCase label $ assertBool label $ compare x y == expected++hashEqCase :: String -> SMTExpr a -> SMTExpr a -> TestTree+hashEqCase label x y =+  testCase label $ assertBool label $ hashWithSalt 0 x == hashWithSalt 0 y++hashNeqCase :: String -> SMTExpr a -> SMTExpr a -> TestTree+hashNeqCase label x y =+  testCase label $ assertBool label $ hashWithSalt 0 x /= hashWithSalt 0 y++eqTests :: TestTree+eqTests = testGroup "Eq"+  [ eqCase "And/equal"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      True+  , eqCase "And/unequal"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4), Greater (Const 5) (Const 6)])+      False+  , eqCase "Add/equal"+      (smtAdd [Const 1, Const 2])+      (smtAdd [Const 1, Const 2])+      True+  , eqCase "Add/unequal"+      (smtAdd [Const 1, Const 2])+      (smtAdd [Const 1, Const 3])+      False+  , eqCase "Or/equal"+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      True+  , eqCase "Or/unequal"+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtOr [Greater (Const 3) (Const 4), Greater (Const 1) (Const 2)])+      False+  , eqCase "Equal/equal"+      (smtEqual [Const 1, Const 2])+      (smtEqual [Const 1, Const 2])+      True+  , eqCase "Equal/unequal"+      (smtEqual [Const 1, Const 2])+      (smtEqual [Const 1, Const 3])+      False+  , eqCase "Greater/equal"+      (Greater (Const 1) (Const 2))+      (Greater (Const 1) (Const 2))+      True+  , eqCase "Greater/left"+      (Greater (Const 1) (Const 2))+      (Greater (Const 2) (Const 2))+      False+  , eqCase "Greater/right"+      (Greater (Const 1) (Const 2))+      (Greater (Const 1) (Const 3))+      False+  , eqCase "GTE/equal"+      (smtGTE (Const 1) (Const 2))+      (smtGTE (Const 1) (Const 2))+      True+  , eqCase "GTE/unequal"+      (smtGTE (Const 1) (Const 2))+      (smtGTE (Const 1) (Const 3))+      False+  , eqCase "Implies/equal"+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      True+  , eqCase "Implies/unequal"+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      (smtImplies (Greater (Const 3) (Const 4)) (Greater (Const 1) (Const 2)))+      False+  , eqCase "Var/equal"+      (toSMT (Op "x"))+      (toSMT (Op "x"))+      True+  , eqCase "Var/unequal"+      (toSMT (Op "x"))+      (toSMT (Op "y"))+      False+  , eqCase "Const/equal"+      (Const 1)+      (Const 1)+      True+  , eqCase "Const/unequal"+      (Const 1)+      (Const 2)+      False+    -- catch-all @_ == _ = False@ on 'SMTExpr Bool'+  , eqCase "And/Or"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      False+  , eqCase "And/Equal"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtEqual [Const 1, Const 2])+      False+  , eqCase "And/Greater"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (Greater (Const 1) (Const 2))+      False+  , eqCase "And/GTE"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtGTE (Const 1) (Const 2))+      False+  , eqCase "Or/Equal"+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtEqual [Const 1, Const 2])+      False+  , eqCase "Equal/Greater"+      (smtEqual [Const 1, Const 2])+      (Greater (Const 1) (Const 2))+      False+  , eqCase "Greater/GTE"+      (Greater (Const 1) (Const 2))+      (smtGTE (Const 1) (Const 2))+      False+  , eqCase "GTE/Implies"+      (smtGTE (Const 1) (Const 2))+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      False+    -- catch-all @_ == _ = False@ on 'SMTExpr Int'+  , eqCase "Const/Add"+      (Const 1)+      (smtAdd [Const 1, Const 2])+      False+  , eqCase "Add/Var"+      (smtAdd [Const 1, Const 2])+      (toSMT (Op "x"))+      False+  , eqCase "Var/Const"+      (toSMT (Op "x"))+      (Const 1)+      False+  , eqCase "Var/Add"+      (toSMT (Op "x"))+      (smtAdd [Const 1, Const 2])+      False+  ]++ordTests :: TestTree+ordTests = testGroup "Ord"+  [ ordCase "And/LT"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4), Greater (Const 5) (Const 6)])+      LT+  , ordCase "And/GT"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4), Greater (Const 5) (Const 6)])+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      GT+  , ordCase "And/EQ"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      EQ+  , ordCase "Add/LT"+      (smtAdd [Const 1])+      (smtAdd [Const 1, Const 2])+      LT+  , ordCase "Add/GT"+      (smtAdd [Const 1, Const 2])+      (smtAdd [Const 1])+      GT+  , ordCase "Add/EQ"+      (smtAdd [Const 1, Const 2])+      (smtAdd [Const 1, Const 2])+      EQ+  , ordCase "Or/LT"+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4), Greater (Const 5) (Const 6)])+      LT+  , ordCase "Or/GT"+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4), Greater (Const 5) (Const 6)])+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      GT+  , ordCase "Or/EQ"+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      EQ+  , ordCase "Equal/LT"+      (smtEqual [Const 1, Const 2])+      (smtEqual [Const 1, Const 3])+      LT+  , ordCase "Equal/GT"+      (smtEqual [Const 1, Const 3])+      (smtEqual [Const 1, Const 2])+      GT+  , ordCase "Equal/EQ"+      (smtEqual [Const 1, Const 2])+      (smtEqual [Const 1, Const 2])+      EQ+  , ordCase "Greater/LT"+      (Greater (Const 1) (Const 2))+      (Greater (Const 1) (Const 3))+      LT+  , ordCase "Greater/GT"+      (Greater (Const 1) (Const 3))+      (Greater (Const 1) (Const 2))+      GT+  , ordCase "Greater/EQ"+      (Greater (Const 1) (Const 2))+      (Greater (Const 1) (Const 2))+      EQ+  , ordCase "GTE/LT"+      (smtGTE (Const 1) (Const 2))+      (smtGTE (Const 1) (Const 3))+      LT+  , ordCase "GTE/GT"+      (smtGTE (Const 1) (Const 3))+      (smtGTE (Const 1) (Const 2))+      GT+  , ordCase "GTE/EQ"+      (smtGTE (Const 1) (Const 2))+      (smtGTE (Const 1) (Const 2))+      EQ+  , ordCase "Implies/LT"+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 5) (Const 6)))+      LT+  , ordCase "Implies/GT"+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 5) (Const 6)))+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      GT+  , ordCase "Implies/EQ"+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      EQ+  , ordCase "Var/LT"+      (toSMT (Op "x"))+      (toSMT (Op "y"))+      LT+  , ordCase "Var/GT"+      (toSMT (Op "y"))+      (toSMT (Op "x"))+      GT+  , ordCase "Var/EQ"+      (toSMT (Op "x"))+      (toSMT (Op "x"))+      EQ+  , ordCase "Const/LT"+      (Const 1)+      (Const 2)+      LT+  , ordCase "Const/GT"+      (Const 2)+      (Const 1)+      GT+  , ordCase "Const/EQ"+      (Const 1)+      (Const 1)+      EQ+    -- catch-all based on 'dataToTag#' (constructor declaration order)+  , ordCase "And<Or"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      LT+  , ordCase "Or>And"+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      GT+  , ordCase "Equal<GTE"+      (smtEqual [Const 1, Const 2])+      (smtGTE (Const 1) (Const 2))+      LT+  , ordCase "GTE>Equal"+      (smtGTE (Const 1) (Const 2))+      (smtEqual [Const 1, Const 2])+      GT+  , ordCase "Greater<GTE"+      (Greater (Const 1) (Const 2))+      (smtGTE (Const 1) (Const 2))+      LT+  , ordCase "GTE<Implies"+      (smtGTE (Const 1) (Const 2))+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      LT+  , ordCase "Add<Var"+      (smtAdd [Const 1, Const 2])+      (toSMT (Op "x"))+      LT+  , ordCase "Var>Add"+      (toSMT (Op "x"))+      (smtAdd [Const 1, Const 2])+      GT+  , ordCase "Var<Const"+      (toSMT (Op "x"))+      (Const 1)+      LT+  , ordCase "Const>Var"+      (Const 1)+      (toSMT (Op "x"))+      GT+  , ordCase "Add<Const"+      (smtAdd [Const 1, Const 2])+      (Const 1)+      LT+  , ordCase "Const>Add"+      (Const 1)+      (smtAdd [Const 1, Const 2])+      GT+  ]++hashTests :: TestTree+hashTests = testGroup "Hashable"+  [ hashEqCase "And/equal"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+  , hashNeqCase "And/payload"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4), Greater (Const 5) (Const 6)])+  , hashNeqCase "And/Or"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+  , hashEqCase "Add/equal"+      (smtAdd [Const 1, Const 2])+      (smtAdd [Const 1, Const 2])+  , hashNeqCase "Add/payload"+      (smtAdd [Const 1, Const 2])+      (smtAdd [Const 1, Const 3])+  , hashEqCase "Or/equal"+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+  , hashNeqCase "Or/payload"+      (smtOr [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtOr [Greater (Const 3) (Const 4), Greater (Const 1) (Const 2)])+  , hashEqCase "Equal/equal"+      (smtEqual [Const 1, Const 2])+      (smtEqual [Const 1, Const 2])+  , hashNeqCase "Equal/payload"+      (smtEqual [Const 1, Const 2])+      (smtEqual [Const 1, Const 3])+  , hashNeqCase "And/Equal"+      (smtAnd [Greater (Const 1) (Const 2), Greater (Const 3) (Const 4)])+      (smtEqual [Const 1, Const 2])+  , hashEqCase "Greater/equal"+      (Greater (Const 1) (Const 2))+      (Greater (Const 1) (Const 2))+  , hashNeqCase "Greater/payload"+      (Greater (Const 1) (Const 2))+      (Greater (Const 1) (Const 3))+  , hashEqCase "GTE/equal"+      (smtGTE (Const 1) (Const 2))+      (smtGTE (Const 1) (Const 2))+  , hashNeqCase "GTE/payload"+      (smtGTE (Const 1) (Const 2))+      (smtGTE (Const 1) (Const 3))+  , hashEqCase "Implies/equal"+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+  , hashNeqCase "Implies/payload"+      (smtImplies (Greater (Const 1) (Const 2)) (Greater (Const 3) (Const 4)))+      (smtImplies (Greater (Const 3) (Const 4)) (Greater (Const 1) (Const 2)))+  , hashEqCase "Var/equal"+      (toSMT (Op "x"))+      (toSMT (Op "x"))+  , hashNeqCase "Var/payload"+      (toSMT (Op "x"))+      (toSMT (Op "y"))+  , hashNeqCase "Add/Var"+      (smtAdd [Const 1, Const 2])+      (toSMT (Op "x"))+  , hashEqCase "Const/equal"+      (Const 1)+      (Const 1)+  , hashNeqCase "Const/payload"+      (Const 1)+      (Const 2)+  , hashNeqCase "Var/Const"+      (toSMT (Op "x"))+      (Const 1)+  ]++tests :: TestTree+tests = testGroup "SMTExpr instances"+  [ eqTests+  , ordTests+  , hashTests+  ]
test/StrictOC.hs view
@@ -7,13 +7,17 @@ import Language.REST.Internal.WQO import Language.REST.Internal.OpOrdering -tests :: [(String, Bool)]-tests =-  [-    ("permits", permits noConstraints wqo)-  , ("permits2", permits noConstraints $ fromJust $ parseOO "+ = f = nil = s ∧ + > g ∧ + > h ∧ cons > + ∧ cons > g")+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool)++tests :: TestTree+tests = testGroup "StrictOC"+  [ testCase "permits" $ assertBool "permits" (permits noConstraints wqo)+  , testCase "permits2" $ assertBool "permits2" $+      permits noConstraints $ fromJust $ parseOO "+ = f = nil = s ∧ + > g ∧ + > h ∧ cons > + ∧ cons > g"   ] where-  Just wqo = mergeAll [ "cons" =. "z"+  wqo = fromJust $ mergeAll+                      [ "cons" =. "z"                       , "g" =. "nil"                       , "h" =. "s"                       , "cons" >. "g"
test/Test.hs view
@@ -4,17 +4,13 @@ {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-}+{-# LANGUAGE TypeApplications #-}  module Main where -import qualified Data.List as L-import Data.Hashable-#if MIN_VERSION_mtl(2,3,0)-import Control.Monad (guard)-#endif-import Control.Monad.Identity import qualified Arith as A +import Data.Hashable import qualified Data.HashMap.Strict as M import qualified ExploredTerms import OpOrdering@@ -23,20 +19,26 @@ import MultisetOrder import Nat import RPO+import RPOEquiv+import LPOEquiv import KBO import StrictOC-import LazyOC import SMT+import qualified SMTExprInstances import qualified QuickCheckTests-import System.IO +import Test.Tasty (defaultMain, testGroup, TestTree)+import Test.Tasty.HUnit (testCase, assertBool)+import Control.Exception (bracket, finally)++import Language.REST (lpoOCA, rpoOCA) import Language.REST.ExploredTerms import Language.REST.OCAlgebra-import Language.REST.OCToAbstract import Language.REST.Core-import Language.REST.LPO (lpo) import Language.REST.KBO (kbo) import Language.REST.WQOConstraints as OC+import Language.REST.WQOConstraints.SMT (smtOC)+import qualified Language.REST.WQOConstraints.Strict as SC (strictOC) import Language.REST.Op import Language.REST.RPO import Language.REST.Internal.OpOrdering@@ -47,20 +49,13 @@ import Language.REST.Internal.WQO import Language.REST.Rest import Language.REST.SMT-import qualified Language.REST.WQOConstraints.ADT as AC import Language.REST.Internal.WorkStrategy import qualified Data.Maybe as Mb import qualified Data.HashSet as S  --- | 'canOrient' returns true iff the ordering constraint algebra permits an ordering---   that orients, the path, i.e., the constraints generated by 'orient' are satisfiable.-canOrient :: forall oc m . Show oc-  => (?impl :: OCAlgebra oc RuntimeTerm m) => [RuntimeTerm] -> m Bool-canOrient terms = isSat ?impl (orient ?impl terms)- diverges :: (Show oc) => OCAlgebra oc RuntimeTerm IO -> [RuntimeTerm] -> IO Bool-diverges impl ts = not <$> isSat impl (orient impl ts)+diverges impl ts = not <$> (orient impl ts >>= isSat impl)  rewrites :: (Show oc, Hashable oc, Eq oc)   => OCAlgebra oc RuntimeTerm IO@@ -79,43 +74,44 @@   where     ?impl = impl -runTest :: (String, IO Bool) -> IO ()-runTest (name, test) = do-  putStr $ "Running " ++ name ++ "... "-  hFlush stdout-  ok <- test-  if ok-    then putStrLn "Passed"-    else error $ "Test " ++ name ++ " FAILED"--class Testable a where-  toTest :: a -> IO Bool--instance Testable Bool where-  toTest = return--instance Testable (IO Bool) where-  toTest = id--runTestSuite :: Testable a => String -> [(String, a)] -> IO ()-runTestSuite name tests1 = do-  putStrLn $ "Running test suite: " ++ name-  mapM_ (runTest . go) tests1-  where-    go (name1, test) = (name1, toTest test)+ocaGroup :: String+         -> OCAlgebra (SMTExpr Bool) RuntimeTerm IO+         -> [String]+         -> TestTree+ocaGroup name impl toSkip =+  testGroup name+    [ testGroup "Arith"+        [ testCase n (t >>= assertBool n)+        | (n, t) <- arithTests impl+        , n `notElem` toSkip+        ]+    , testGroup "Complete"+        [ testCase n (t >>= assertBool n)+        | (n, t) <- completeTests impl+        , n `notElem` toSkip+        ]+    ]  -orderingTests :: (Hashable (oc Op), Show (oc Op), Ord (oc Op)) => (?impl :: WQOConstraints oc IO) => [(String, IO Bool)]+orderingTests :: TestTree orderingTests =-  [-    ("simple1", return $ not $ rpoGTE "f(t1)" "g(t2)" `permits'` (t1Op =. t2Op))-  , ("simple2", return $ rpoGTE "f(t1)" "g(t2)" `permits'` Mb.fromJust (merge (f >. g) (t1Op =. t2Op)))-  , ("simple3", return $ rpoGTE "f(t1)" "g(t2)" `permits'` Mb.fromJust (merge (f >. g) (t1Op >. t2Op)))-  , ("subterm", return $ rpoGTE "f(g)" "f" == noConstraints ?impl)-  , ("intersect", OC.isUnsatisfiable ?impl $ OC.intersect ?impl (OC.singleton ?impl (f  >. g)) (OC.singleton ?impl (g >. f)))-  ]-  where-    permits' = permits ?impl+  let ?impl = SC.strictOC @IO in+  let permits' = permits ?impl in+    testGroup "Ordering"+      [+        testCase "simple1" $+          assertBool "simple1" $ not $ rpoGTE "f(t1)" "g(t2)" `permits'` (t1Op =. t2Op)+      , testCase "simple2" $+          assertBool "simple2" $ rpoGTE "f(t1)" "g(t2)" `permits'` Mb.fromJust (merge (f >. g) (t1Op =. t2Op))+      , testCase "simple3" $+          assertBool "simple3" $ rpoGTE "f(t1)" "g(t2)" `permits'` Mb.fromJust (merge (f >. g) (t1Op >. t2Op))+      , testCase "subterm" $+          assertBool "subterm" $+            rpoGTE "f(g)" "f" == noConstraints ?impl+      , testCase "intersect" $ do+          isUnsat <- OC.isUnsatisfiable ?impl $ OC.intersect ?impl (OC.singleton ?impl (f  >. g)) (OC.singleton ?impl (g >. f))+          assertBool "intersect" isUnsat+      ]  proveEQ :: (Show oc, Hashable oc, Eq oc) =>      OCAlgebra oc RuntimeTerm IO@@ -230,41 +226,40 @@     s1      = Op "s1"     s2      = Op "s2" -ocTests :: (Handle, Handle) -> IO ()-ocTests z3 = do-  runTestSuite "LazyOC" LazyOC.tests-  runTestSuite "StrictOC" StrictOC.tests-  runTestSuite "RPO" RPO.tests-  runTestSuite "Ordering" orderingTests-  where-    ?impl = AC.adtOC z3+ocTests :: SolverHandle -> TestTree+ocTests z3 =+  testGroup "OC tests"+    [ RPO.tests+    , let ?impl = smtOC z3 in RPO.solverTests+    , orderingTests+    ]  main :: IO ()-main = spawnZ3 >>= go where--  implTests implName impl toSkip = do-    runTestSuite ("Arith" ++ implName) (withSkips $ arithTests impl)-    runTestSuite ("Complete" ++ implName) (withSkips $ completeTests impl)-    where-      withSkips tests1 = do-        (name, test) <- tests1-        guard $ L.notElem name toSkip-        return (name, test)---  go :: SolverHandle -> IO ()-  go z3 =-    do-      putStrLn "Running REST Test Suite"-      runTestSuite "ExploredTerms" ExploredTerms.tests-      runTestSuite "SMT" SMT.tests-      runTestSuite "KBO" (KBO.tests z3)-      _ <- QuickCheckTests.tests-      runTestSuite "OpOrdering" OpOrdering.tests-      ocTests z3-      runTestSuite "MultisetOrder" MultisetOrder.tests-      runTestSuite "WQO" WQO.tests-      implTests "KBO" (kbo z3) []-      implTests "RPO" (lift (AC.adtOC z3) rpo) []-      implTests "LPO" (lift (AC.adtOC z3) lpo) ["Diverge3", "Arith4", "Arith4.1", "Arith6"]-      killZ3 z3+main = withZ3 $ \z3 ->+  withZ3' $ \kboZ3 ->+  withZ3' $ \rpoZ3 ->+  withZ3' $ \lpoZ3 ->  do+    kboImpl <- kbo kboZ3 "$KBO_"+    rpoImpl <- rpoOCA rpoZ3 "$R_"+    lpoImpl <- lpoOCA lpoZ3 "$L_"+    flip finally (mapM_ killZ3 [z3, kboZ3, rpoZ3, lpoZ3]) $+      defaultMain $ testGroup "REST"+        [ ExploredTerms.tests+        , SMT.tests+        , SMTExprInstances.tests+        , KBO.tests+        , QuickCheckTests.tests+        , OpOrdering.tests+        , StrictOC.tests+        , ocTests z3+        , RPOEquiv.tests z3+        , LPOEquiv.tests z3+        , MultisetOrder.tests+        , WQO.tests+        , ocaGroup "KBO" kboImpl []+        , ocaGroup "RPO" rpoImpl []+        , ocaGroup "LPO" lpoImpl ["Diverge3", "Arith4", "Arith4.1", "Arith6"]+        ]+  where+    withZ3' :: (SolverHandle -> IO a) -> IO a+    withZ3' = bracket spawnZ3 killZ3
test/WQO.hs view
@@ -3,17 +3,28 @@ import Language.REST.Internal.WQO as WQO import Data.Maybe (isNothing) +import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, assertBool)+ basicInvalid :: Maybe (WQO Char) basicInvalid = do   wqo1 <- WQO.singleton ('A', 'C', QGT)   WQO.insertMaybe wqo1 ('C', 'A', QGT) -tests :: [(String, Bool)]+tests :: TestTree tests =-  let-    ValidExtension fg   = insert empty ("f", "g", QGT)-    ValidExtension fgyz = insert fg ("y", "z", QGT)-  in-    [ ("NotStrongerThan", fg `notStrongerThan` fgyz)-    , ("RejectInvalid", isNothing basicInvalid)+  testGroup "WQO"+    [+      testCase "RejectInvalid" $+        assertBool "RejectInvalid" $ isNothing basicInvalid+    , testCase "NotStrongerThan" $+        case insert empty ("f", "g", QGT) of+          ValidExtension fg ->+            case insert fg ("y", "z", QGT) of+              ValidExtension fgyz ->+                assertBool "NotStrongerThan" $ fg `notStrongerThan` fgyz+              _ ->+                error "Failed to insert (\"y\", \"z\", QGT)"+          _ ->+            error "Failed to insert (\"f\", \"g\", QGT)"     ]
testlib/Language/REST/ConcreteOC.hs view
@@ -1,5 +1,6 @@ {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE ScopedTypeVariables #-}  module Language.REST.ConcreteOC where @@ -19,7 +20,7 @@ instance Show ConcreteOC where   show (ConcreteOC ords) = show (S.size ords) ++ " orderings" -concreteOC :: Monad m => S.Set Op -> AOC.OCAlgebra ConcreteOC RuntimeTerm m+concreteOC :: forall m. Monad m => S.Set Op -> AOC.OCAlgebra ConcreteOC RuntimeTerm m concreteOC ops = AOC.OCAlgebra (return . isSat) refine (ConcreteOC (WQO.orderings ops)) union notStrongerThan   where     union (ConcreteOC ord1) (ConcreteOC ord2) = ConcreteOC $ S.union ord1 ord2@@ -28,5 +29,5 @@     isSat :: ConcreteOC -> Bool     isSat (ConcreteOC ords) = not $ S.null ords -    refine :: ConcreteOC -> RuntimeTerm -> RuntimeTerm -> ConcreteOC-    refine (ConcreteOC ords) t u = ConcreteOC (S.filter (\ord -> synGTE ord t u) ords)+    refine :: ConcreteOC -> RuntimeTerm -> RuntimeTerm -> m ConcreteOC+    refine (ConcreteOC ords) t u = pure $ ConcreteOC (S.filter (\ord -> synGTE ord t u) ords)
testlib/MultisetOrdering.hs view
@@ -97,7 +97,9 @@     toEdges mp (((ts, tsIndex), (us, usIndex)) : mss) =         concatMap redges repls ++ toEdges mp' mss       where-        Just (MultisetGE repls) = multisetGE (\t u -> gte (fst t) (fst u)) ts us+        MultisetGE repls =+          Mb.fromMaybe (error "toEdges: multisetGE failed") $+            multisetGE (\t u -> gte (fst t) (fst u)) ts us          lookupTIndex :: Int -> (Int, Int)         lookupTIndex tindex = Mb.fromMaybe (tindex, tsIndex) (Mp.lookup (tindex, tsIndex) mp)