Repository navigation
Look for redundant guard conditions #84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
95751a9
4508e2a
d62193d
b7fa22f
9ae7d47
a780d45
e2dccd0
7131de8
4e22ab8
da9620a
7c49294
5dfe170
27c621a
8d4e385
0b40561
8570c10
25ce4e8
5f3209e
82d8d88
725dc63
e80936f
1946ffc
40e3551
724ae77
e4f4fbc
cfa94f9
c41129a
34f9b89
96cbcce
e9a9fa6
2f66c3b
1630fc0
26e395f
9428038
c3e36d4
2abeee3
91de09b
0f13a7b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,305 @@ | ||
| {-# LANGUAGE TupleSections #-} | ||
| {-# LANGUAGE ViewPatterns #-} | ||
|
|
||
| module Haskell.Template.Detection.Guards (detectRedundantGuardCondition, Reason (..)) where | ||
|
|
||
| import Control.Monad (join, liftM2, liftM3, void, (<=<)) | ||
| import Data.Bifunctor (second) | ||
| import Data.List (singleton) | ||
| import Data.List.Extra (nubOrd) | ||
| import Data.List.NonEmpty (NonEmpty) | ||
| import qualified Data.List.NonEmpty as NE (fromList, toList) | ||
| import Data.Maybe (fromJust, mapMaybe, maybeToList) | ||
| import Haskell.Template.Detection.Helper ( | ||
| ScopedExp, | ||
| isTruthfulGuard, | ||
| qActName, | ||
| qActScopedName, | ||
| qOpActName', | ||
| unwrapParens, | ||
| ) | ||
| import Language.Haskell.Exts ( | ||
| Decl (FunBind, PatBind), | ||
| Exp (..), | ||
| GuardedRhs (..), | ||
| Literal (..), | ||
| Match (InfixMatch, Match), | ||
| Module (Module), | ||
| Name (..), | ||
| Pat (PVar), | ||
| Rhs (GuardedRhss, UnGuardedRhs), | ||
| SrcSpanInfo, | ||
| Stmt (Qualifier), | ||
| ann, | ||
| ) | ||
| import Language.Haskell.Names ( | ||
| NameInfo, | ||
| Scoped (..), | ||
| ) | ||
| import Witherable (witherM) | ||
| import Z3.Monad ( | ||
| AST, | ||
| Result (..), | ||
| Z3, | ||
| assert, | ||
| check, | ||
| evalZ3, | ||
| mkAdd, | ||
| mkAnd, | ||
| mkBoolVar, | ||
| mkDiv, | ||
| mkEq, | ||
| mkFalse, | ||
| mkGe, | ||
| mkGt, | ||
| mkIff, | ||
| mkImplies, | ||
| mkInt, | ||
| mkIntSort, | ||
| mkIntVar, | ||
| mkIte, | ||
| mkLe, | ||
| mkLt, | ||
| mkMod, | ||
| mkMul, | ||
| mkNot, | ||
| mkNumeral, | ||
| mkOr, | ||
| mkReal2Int, | ||
| mkRealSort, | ||
| mkRealVar, | ||
| mkRem, | ||
| mkStringSymbol, | ||
| mkSub, | ||
| mkTrue, | ||
| mkUnaryMinus, | ||
| ) | ||
|
|
||
| -- | Reason for a condition being reported | ||
| data Reason = Redundant | Unreachable | ||
| deriving (Eq, Ord, Show) | ||
|
|
||
| -- | Returns a list of redundant or unreachable guard conditions together with an exhaustion status | ||
| checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO [(Reason, ScopedExp a)] | ||
| checkForRedundancy [] = pure [] | ||
| checkForRedundancy guards@(_ : _) = do | ||
| case guards of | ||
| [x] -> do | ||
| let xList = NE.toList x | ||
| isTrue <- prove $ do | ||
| inQuestion <- mkAnd =<< mapM snd xList | ||
| mkIff inQuestion =<< mkTrue | ||
|
|
||
| if isTrue | ||
| then return $ map ((Redundant,) . fst) xList | ||
| else return [] | ||
| xs -> checking (pure []) (map NE.toList xs) | ||
| where | ||
| checking _ [] = pure [] | ||
| checking skipped ([] : remaining) = checking skipped remaining | ||
| checking skipped (r : remaining) = do | ||
| let known' = mkAnd =<< skipped | ||
|
|
||
| results <- do | ||
| guardIsSuperfluous <- prove $ do | ||
| known <- known' | ||
| mkImplies known =<< mkNot =<< mkAnd =<< mapM snd r | ||
|
|
||
| if guardIsSuperfluous | ||
| then pure $ map ((Unreachable,) . fst) r | ||
| else fmap (map (second fst)) $ flip witherM r $ \(e, c) -> do | ||
| isRedundant <- prove $ do | ||
| known <- known' | ||
| inQuestion <- c | ||
|
|
||
| mkImplies known inQuestion | ||
|
|
||
| if isRedundant && not (isTruthfulGuard e) | ||
| then pure $ Just (Redundant, (e, c)) | ||
| else pure Nothing | ||
|
|
||
| restResults <- | ||
| checking | ||
| ((:) <$> (mkNot =<< mkAnd =<< mapM snd r) <*> skipped) | ||
| (map (filter ((`notElem` map snd results) . fst)) remaining) | ||
|
|
||
| return $ results ++ restResults | ||
|
|
||
| -- | Returns a list of redundant or unreachable guard conditions per definition | ||
| detectRedundantGuardCondition | ||
| :: Module (Scoped SrcSpanInfo) | ||
| -> IO [(Name (Scoped SrcSpanInfo), [(Reason, ScopedExp SrcSpanInfo)])] | ||
| detectRedundantGuardCondition mod' = | ||
| flip witherM (extractFromModule mod') $ \(name, constraints) -> do | ||
| redundant <- checkForRedundancy constraints | ||
| case redundant of | ||
| [] -> pure Nothing | ||
| xs -> pure $ Just (name, nubOrd xs) | ||
|
|
||
| -- | Extracts all guard conditions from a definition using guards | ||
| extractFromModule | ||
| :: Module (Scoped SrcSpanInfo) | ||
| -> [(Name (Scoped SrcSpanInfo), [NonEmpty (ScopedExp SrcSpanInfo, Z3 AST)])] | ||
| extractFromModule (Module _ _ _ _ decls) = concatMap fromDecl decls | ||
| where | ||
| fromDecl (FunBind _ matches) = map fromMatch matches | ||
| fromDecl (PatBind _ (PVar _ name) rhs _) = [(name, fromRhs rhs)] | ||
| fromDecl _ = [] | ||
|
|
||
| fromRhs (UnGuardedRhs _ _) = [] | ||
| fromRhs (GuardedRhss _ gRhss) = mapMaybe extractConstraintsFromGuardedRhs gRhss | ||
|
|
||
| fromMatch (Match _ name _ rhs _) = (name, fromRhs rhs) | ||
| fromMatch (InfixMatch _ _ name _ rhs _) = (name, fromRhs rhs) | ||
| extractFromModule _ = [] | ||
|
|
||
| {- | Extracts all conditions from a given guard. | ||
| | | ||
| | Returns `Nothing` if one guard is not a pure boolean expression. | ||
| -} | ||
| extractConstraintsFromGuardedRhs | ||
| :: GuardedRhs (Scoped SrcSpanInfo) | ||
| -> Maybe (NonEmpty (ScopedExp SrcSpanInfo, Z3 AST)) | ||
| extractConstraintsFromGuardedRhs (GuardedRhs _ statements _) = case concat <$> mapM extractFromStmt statements of | ||
| Nothing -> Nothing | ||
| Just [] -> Nothing | ||
| Just xs -> Just $ NE.fromList xs | ||
| where | ||
| extractFromStmt (Qualifier _ conditionExpr) = Just $ astToZ3 conditionExpr | ||
| extractFromStmt _ = Nothing | ||
|
|
||
| -- | Returns the z3 variable name representing a scoped variable | ||
| scopedVarName :: Show a => (NameInfo a, String) -> String | ||
| scopedVarName (scope, name) = show scope ++ "::" ++ name | ||
|
|
||
| -- | Returns the z3 variable name representing the length of the list encapsulated in the expression | ||
| listVarName :: ScopedExp () -> String | ||
| listVarName expr = "::length_" ++ show expr | ||
|
|
||
| -- | Computes the z3 ast for a given expression inside an arithmetical expression | ||
| arithAstToZ3 :: Show a => ScopedExp a -> Maybe (ScopedExp a, Z3 AST) | ||
| arithAstToZ3 (unwrapParens -> expr) = | ||
| (expr,) <$> case unwrapParens expr of | ||
| ( Var | ||
| _ | ||
| ( qActScopedName -> | ||
| Just scopedName | ||
| ) | ||
| ) -> Just $ mkRealVar =<< mkStringSymbol (scopedVarName scopedName) | ||
| (Lit _ (Int _ _ valueString)) -> | ||
| Just $ mkNumeral valueString =<< mkIntSort | ||
| (Lit _ (Frac _ _ valueString)) -> | ||
| Just $ mkNumeral valueString =<< mkRealSort | ||
| (App _ (Var _ (qActName -> Just (mModName, name))) arg) -> | ||
| arithAppToZ3 mModName name [arg] | ||
| (App _ (unwrapParens -> App _ (unwrapParens -> Var _ (qActName -> Just (mModName, name))) arg1) arg2) -> | ||
| arithAppToZ3 mModName name [arg1, arg2] | ||
| (InfixApp _ l (qOpActName' -> Just (mModName, name)) r) -> | ||
| arithAppToZ3 mModName name [l, r] | ||
| (Let _ _ e) -> | ||
| snd <$> arithAstToZ3 e | ||
| (NegApp _ e) -> | ||
| (mkUnaryMinus <=< snd) <$> arithAstToZ3 e | ||
| _ -> | ||
| Nothing | ||
|
|
||
| -- | Computes the z3 ast for a given function or operator application inside an arithmetical expression | ||
| arithAppToZ3 :: Show a => Maybe String -> String -> [ScopedExp a] -> Maybe (Z3 AST) | ||
| arithAppToZ3 (Just "GHC.Num") "+" [l, r] = | ||
| combineMaybeArithExprs False (\a b -> mkAdd [a, b]) l r | ||
| arithAppToZ3 (Just "GHC.Num") "-" [l, r] = | ||
| combineMaybeArithExprs False (\a b -> mkSub [a, b]) l r | ||
| arithAppToZ3 (Just "GHC.Num") "*" [l, r] = | ||
| combineMaybeArithExprs False (\a b -> mkMul [a, b]) l r | ||
| arithAppToZ3 (Just "GHC.Real") "/" [l, r] = | ||
| combineMaybeArithExprs False mkDiv l r | ||
| arithAppToZ3 (Just "GHC.Real") "div" [l, r] = | ||
| combineMaybeArithExprs True mkDiv l r | ||
| arithAppToZ3 (Just "GHC.Real") "mod" [l, r] = | ||
| combineMaybeArithExprs True mkMod l r | ||
| arithAppToZ3 (Just "GHC.Real") "rem" [l, r] = | ||
| combineMaybeArithExprs True mkRem l r | ||
| arithAppToZ3 (Just "GHC.List") "length" [ls] = Just $ do | ||
| v <- mkIntVar =<< mkStringSymbol (listVarName $ fmap void ls) | ||
| assert =<< mkGe v =<< mkInt 0 =<< mkIntSort | ||
| return v | ||
| arithAppToZ3 (Just "Data.List") "sum" [unwrapParens -> List _ es] = | ||
| (mkAdd <=< sequence) <$> mapM (fmap snd . arithAstToZ3) es | ||
| arithAppToZ3 (Just "Data.List") "product" [unwrapParens -> List _ es] = | ||
| (mkMul <=< sequence) <$> mapM (fmap snd . arithAstToZ3) es | ||
| arithAppToZ3 _ _ _ = Nothing | ||
|
|
||
| -- | Computes the z3 ast for a given expression | ||
| astToZ3 :: Show a => ScopedExp a -> [(ScopedExp a, Z3 AST)] | ||
| astToZ3 (unwrapParens -> expr) = case expr of | ||
| (Var _ (qActName -> Just (Just "GHC.Base", "otherwise"))) -> | ||
| singleton (expr, mkTrue) | ||
| (Var _ (qActScopedName -> Just scopedName)) -> | ||
| -- variable outside arithmetic comparison | ||
| singleton $ (expr,) $ mkBoolVar =<< mkStringSymbol (scopedVarName scopedName) | ||
| (App _ (Var _ (qActName -> Just (mModName, name))) arg) -> | ||
| -- application outside arithmetic comparison | ||
| appToZ3 expr mModName name [arg] | ||
| (InfixApp _ l (qOpActName' -> Just (mModName, name)) r) -> | ||
| -- infix application outside arithmetic comparison | ||
| appToZ3 expr mModName name [l, r] | ||
| (Con _ (qActName -> Just (Just "GHC.Types", "True"))) -> | ||
| -- literal True | ||
| singleton (expr, mkTrue) | ||
| (Con _ (qActName -> Just (Just "GHC.Types", "False"))) -> | ||
| -- literal False | ||
| singleton (expr, mkFalse) | ||
| (Let _ _ e) -> astToZ3 e | ||
| (If _ cond t e) -> | ||
| map (expr,) $ | ||
| liftM3 (\(_, a) (_, b) (_, c) -> join $ liftM3 mkIte a b c) (astToZ3 cond) (astToZ3 t) (astToZ3 e) | ||
| _ -> [] | ||
|
|
||
| -- | Computes the z3 ast for a given function or operator application | ||
| appToZ3 :: Show a => ScopedExp a -> Maybe String -> String -> [ScopedExp a] -> [(ScopedExp a, Z3 AST)] | ||
| appToZ3 expr (Just "GHC.Classes") opName [l, r] | ||
| | opName `elem` map fst opMap = | ||
| map (expr,) $ maybeToList $ combineMaybeArithExprs False op l r | ||
| where | ||
| opMap = [("<", mkLt), ("<=", mkLe), (">", mkGt), (">=", mkGe), ("==", mkEq)] | ||
| op = fromJust $ lookup opName opMap | ||
| appToZ3 expr (Just "GHC.Classes") "&&" [l, r] = | ||
| appToZ3 expr (Just "GHC.List") "and" [List (ann l) [l, r]] | ||
| appToZ3 expr (Just "GHC.Classes") "||" [l, r] = | ||
| appToZ3 expr (Just "GHC.List") "or" [List (ann l) [l, r]] | ||
| appToZ3 expr (Just "GHC.Classes") "/=" [l, r] = | ||
| map (expr,) $ maybeToList ((mkNot =<<) <$> combineMaybeArithExprs False mkEq l r) | ||
| appToZ3 expr (Just "GHC.Classes") "not" [e] = | ||
| (expr,) . (mkNot <=< snd) <$> astToZ3 e | ||
| appToZ3 expr (Just "GHC.List") "null" [ls] = | ||
| singleton $ (expr,) $ do | ||
| v <- mkIntVar =<< mkStringSymbol (listVarName $ fmap void ls) | ||
| mkEq v =<< mkInt 0 =<< mkIntSort | ||
| appToZ3 _ (Just "GHC.List") "and" [unwrapParens -> List _ es] = | ||
| concat $ mapM astToZ3 es | ||
| appToZ3 expr (Just "GHC.List") "or" [unwrapParens -> List _ es] = | ||
| singleton $ (expr,) $ mkOr =<< mapM (mkAnd <=< (mapM snd . astToZ3)) es | ||
| appToZ3 _ _ _ _ = | ||
| [] | ||
|
|
||
| {- | Computes the z3 ast for a composition of two (arithmetic) expressions. | ||
| | | ||
| | Only returns `Just` when both expressions are arithmetic expressions. | ||
| -} | ||
| combineMaybeArithExprs :: Show a => Bool -> (AST -> AST -> Z3 AST) -> ScopedExp a -> ScopedExp a -> Maybe (Z3 AST) | ||
| combineMaybeArithExprs onInt f l r = liftM2 (\(_, a) (_, b) -> join $ liftM2 f a b) (toZ3 l) (toZ3 r) | ||
| where | ||
| toZ3 v = second (if onInt then (mkReal2Int =<<) else id) <$> arithAstToZ3 v | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are you sure this will give a semantic interpretation on the SMT side that is equivalent to the Haskell semantics of I remember that Oliver had problems with that. The SMT solver had a different interpretation of integer division in the negatives than what Haskell uses. With the consequence that relying on semantic information from the SMT solver could lead to wrong analysis results regarding the Haskell program under consideration.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I didn't investigate that yet. |
||
|
|
||
| -- | Proves if a given proposition in form of a z3 ast is valid | ||
| prove :: Z3 AST -> IO Bool | ||
| prove prop = do | ||
| res <- evalZ3 $ do | ||
| p <- prop | ||
|
|
||
| assert =<< mkNot p | ||
|
|
||
| check | ||
| case res of | ||
| Unsat -> pure True | ||
| _ -> pure False | ||
Uh oh!
There was an error while loading. Please reload this page.