diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index f3a14a1..46517f1 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -1,6 +1,7 @@ Aeson autotool Bifunctor +bimap concat elems FCase @@ -18,19 +19,26 @@ hlint Hspec HUnit hyperlinks +Ite mempty mplus msum +Mul mzero PApp +QCon QName QOp QVar Rebindable scrutinee snd +standalone thd uncurry unlines +Unsat Utf +Witherable +xit yml diff --git a/.github/actions/spelling/patterns.txt b/.github/actions/spelling/patterns.txt index a7084b7..4c24771 100644 --- a/.github/actions/spelling/patterns.txt +++ b/.github/actions/spelling/patterns.txt @@ -8,6 +8,7 @@ # acceptable duplicates linebreak linebreak False False +prepend prepend # ls directory listings [-bcdlpsw](?:[-r][-w][-Ssx]){3}\s+\d+\s+\S+\s+\S+\s+\d+\s+ diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index 155b981..b04f7d3 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -27,6 +27,8 @@ source-repository head library exposed-modules: + Haskell.Template.Detection.Guards + Haskell.Template.Detection.Helper Haskell.Template.Detection.Maybe Haskell.Template.Match Haskell.Template.Task @@ -55,8 +57,10 @@ library , syb , text , transformers + , witherable , wl-pprint-text , yaml + , z3 default-language: Haskell2010 test-suite haskell-template-task-test @@ -64,6 +68,7 @@ test-suite haskell-template-task-test main-is: Spec.hs other-modules: Haskell.Template.ConfigSpec + Haskell.Template.Detection.GuardsSpec Haskell.Template.Detection.MaybeSpec Haskell.Template.GradingSpec Haskell.Template.Helper @@ -102,6 +107,8 @@ test-suite haskell-template-task-test , temporary , text , transformers + , witherable , wl-pprint-text , yaml + , z3 default-language: Haskell2010 diff --git a/package.yaml b/package.yaml index d6128a1..7460d13 100644 --- a/package.yaml +++ b/package.yaml @@ -37,7 +37,9 @@ dependencies: - aeson - containers - haskell-names + - witherable - transformers + - z3 ghc-options: - -Wall diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs new file mode 100644 index 0000000..088d611 --- /dev/null +++ b/src/Haskell/Template/Detection/Guards.hs @@ -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 + +-- | 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 diff --git a/src/Haskell/Template/Detection/Helper.hs b/src/Haskell/Template/Detection/Helper.hs new file mode 100644 index 0000000..6c56566 --- /dev/null +++ b/src/Haskell/Template/Detection/Helper.hs @@ -0,0 +1,74 @@ +{-# LANGUAGE ViewPatterns #-} + +module Haskell.Template.Detection.Helper ( + unwrapParens, + qName, + qActName, + ScopedExp, + isTruthfulGuard, + qActScopedName, + qOpActName', + hasName, +) where + +import Language.Haskell.Exts (Exp (..), ModuleName (..), Name (..), QName (..), QOp (..)) +import Language.Haskell.Names (NameInfo (..), Scoped (..), Symbol (..)) + +-- | Unwraps an expression from parentheses +unwrapParens :: Exp a -> Exp a +unwrapParens (Paren _ e) = unwrapParens e +unwrapParens e = e + +{- | Returns the name of a (potentially) qualified name. +| +| Returns `Nothing` when `Special` is passed as the argument. +-} +qName :: QName l -> Maybe (Name l) +qName (Qual _ _ n) = Just n +qName (UnQual _ n) = Just n +qName _ = Nothing + +{- | Returns the actual name of a (potentially) qualified name together with the module name if under global scope. +| +| Returns `Nothing` when `Special` is passed as the argument. +-} +qActName :: QName (Scoped a) -> Maybe (Maybe String, String) +qActName q = case qName q of + Just (Ident (globalModName -> mn) n) -> Just (mn, n) + Just (Symbol (globalModName -> mn) n) -> Just (mn, n) + Nothing -> Nothing + where + globalModName (Scoped (GlobalSymbol (symbolModule -> ModuleName () name) _) _) = Just name + globalModName _ = Nothing + +-- | Shorthand for a scoped expression +type ScopedExp a = Exp (Scoped a) + +-- | Returns True when given expression represents a truthful value +isTruthfulGuard :: ScopedExp a -> Bool +isTruthfulGuard (unwrapParens -> Var _ (qActName -> Just (Just "GHC.Base", "otherwise"))) = True +isTruthfulGuard (unwrapParens -> Con _ (qActName -> Just (Just "GHC.Types", "True"))) = True +isTruthfulGuard _ = False + +{- | Returns the actual name of a (potentially) qualified name together with its scope information. +| +| Returns `Nothing` when `Special` is passed as the argument. +-} +qActScopedName :: QName (Scoped a) -> Maybe (NameInfo a, String) +qActScopedName q = case qName q of + Just (Ident (Scoped scope _) n) -> Just (scope, n) + Just (Symbol (Scoped scope _) n) -> Just (scope, n) + Nothing -> Nothing + +{- | Returns the actual name of a (potentially) qualified operator together with the module name if under global scope. +| +| Returns `Nothing` when the operators name uses `Special` as the constructor. +-} +qOpActName' :: QOp (Scoped a) -> Maybe (Maybe String, String) +qOpActName' (QVarOp _ (qActName -> res)) = res +qOpActName' (QConOp _ (qActName -> res)) = res + +-- | Check if a (potentially qualified) name matches a specified name and optionally from a given module +hasName :: Maybe String -> String -> QName (Scoped l) -> Bool +hasName mModuleName gName (qActName -> Just (modName, name)) = modName == mModuleName && name == gName +hasName _ _ _ = False diff --git a/src/Haskell/Template/Detection/Maybe.hs b/src/Haskell/Template/Detection/Maybe.hs index dd10690..e1f07dd 100644 --- a/src/Haskell/Template/Detection/Maybe.hs +++ b/src/Haskell/Template/Detection/Maybe.hs @@ -7,6 +7,7 @@ import Data.List.Extra (notNull) import Data.Maybe (listToMaybe, mapMaybe, maybeToList) import Data.Set (Set) import qualified Data.Set as Set (empty, fromList, member, singleton, union) +import Haskell.Template.Detection.Helper (ScopedExp, hasName, unwrapParens) import Language.Haskell.Exts ( Alt (..), Decl (..), @@ -14,7 +15,6 @@ import Language.Haskell.Exts ( FieldDecl (..), Match (..), Module (..), - ModuleName (..), Name (..), Pat (..), QName (..), @@ -22,9 +22,9 @@ import Language.Haskell.Exts ( Rhs (..), SrcSpanInfo, ) -import Language.Haskell.Names (NameInfo (..), Scoped (..), symbolModule) +import Language.Haskell.Names (Scoped (..)) -collectIfsWithMaybeChecks :: Module (Scoped SrcSpanInfo) -> [(Exp (Scoped SrcSpanInfo), Exp ())] +collectIfsWithMaybeChecks :: Module (Scoped SrcSpanInfo) -> [(ScopedExp SrcSpanInfo, Exp ())] collectIfsWithMaybeChecks (Module _ _ _ _ decls) = concat $ mapMaybe process decls where -- Imports are disregarded as no module (available to the students) exports a 'value'-named symbol. @@ -56,8 +56,8 @@ declName (PatBind _ (PVar _ pn) _ _) = Just $ fromName pn fromName (Symbol _ n) = n declName _ = Nothing -exprToIfInfo :: String -> Exp (Scoped SrcSpanInfo) -> Maybe (Exp (Scoped SrcSpanInfo), Exp ()) -exprToIfInfo valueName expr@(If _ cond t e) = case removeParens cond of +exprToIfInfo :: String -> ScopedExp SrcSpanInfo -> Maybe (ScopedExp SrcSpanInfo, Exp ()) +exprToIfInfo valueName expr@(If _ cond t e) = case unwrapParens cond of (App _ (Var _ vn) maybeVal) | hasName maybeMod "isJust" vn -> transform maybeVal t e | hasName maybeMod "isNothing" vn -> transform maybeVal e t @@ -79,7 +79,7 @@ exprToIfInfo valueName expr@(If _ cond t e) = case removeParens cond of | isNothingExpression r = Just l | otherwise = Nothing - transform mValExpr j n = case removeParens mValExpr of + transform mValExpr j n = case unwrapParens mValExpr of mVal@(Var _ _) | hasFromJust mVal j -> Just (expr, asCaseExpression valueName mVal j n) | otherwise -> Nothing @@ -102,19 +102,19 @@ recordFieldNames = everything Set.union $ mkQ Set.empty extract nameToString (Ident _ n) = n nameToString (Symbol _ n) = n -hasFromJust :: Exp (Scoped SrcSpanInfo) -> Exp (Scoped SrcSpanInfo) -> Bool +hasFromJust :: ScopedExp SrcSpanInfo -> ScopedExp SrcSpanInfo -> Bool hasFromJust mExpr expr = notNull $ listify isFromJustApp expr where - isFromJustApp :: Exp (Scoped SrcSpanInfo) -> Bool + isFromJustApp :: ScopedExp SrcSpanInfo -> Bool isFromJustApp (App _ (Var _ vn) maybeVal) = - hasName (Just "Data.Maybe") "fromJust" vn && fmap void (removeParens maybeVal) == fmap void mExpr + hasName (Just "Data.Maybe") "fromJust" vn && fmap void (unwrapParens maybeVal) == fmap void mExpr isFromJustApp _ = False asCaseExpression :: String - -> Exp (Scoped SrcSpanInfo) - -> Exp (Scoped SrcSpanInfo) - -> Exp (Scoped SrcSpanInfo) + -> ScopedExp SrcSpanInfo + -> ScopedExp SrcSpanInfo + -> ScopedExp SrcSpanInfo -> Exp () asCaseExpression valueName maybeValue justCase nothingCase = Case @@ -128,28 +128,12 @@ asCaseExpression valueName maybeValue justCase nothingCase = Nothing ] -replaceFromJustWithValue :: String -> Exp (Scoped SrcSpanInfo) -> Exp (Scoped SrcSpanInfo) -> Exp () +replaceFromJustWithValue :: String -> ScopedExp SrcSpanInfo -> ScopedExp SrcSpanInfo -> Exp () replaceFromJustWithValue valueName maybeValue = void . everywhere' (mkT replace) where - replace :: Exp (Scoped SrcSpanInfo) -> Exp (Scoped SrcSpanInfo) - replace expr = case removeParens expr of + replace :: ScopedExp SrcSpanInfo -> ScopedExp SrcSpanInfo + replace expr = case unwrapParens expr of App l (Var _ vn) fnBody - | hasName (Just "Data.Maybe") "fromJust" vn && fmap void (removeParens fnBody) == fmap void maybeValue -> + | hasName (Just "Data.Maybe") "fromJust" vn && fmap void (unwrapParens fnBody) == fmap void maybeValue -> Var l (UnQual l (Ident l valueName)) _ -> expr - -removeParens :: Exp a -> Exp a -removeParens (Paren _ e) = removeParens e -removeParens e = e - -hasName :: Maybe String -> String -> QName (Scoped l) -> Bool -hasName mModuleName qName (UnQual scope (Ident _ n)) = n == qName && isGloballyScopedInModule mModuleName scope -hasName mModuleName qName (Qual scope _ (Ident _ n)) = n == qName && isGloballyScopedInModule mModuleName scope -hasName mModuleName qName (UnQual scope (Symbol _ n)) = n == qName && isGloballyScopedInModule mModuleName scope -hasName mModuleName qName (Qual scope _ (Symbol _ n)) = n == qName && isGloballyScopedInModule mModuleName scope -hasName _ _ _ = False - -isGloballyScopedInModule :: Maybe String -> Scoped l -> Bool -isGloballyScopedInModule Nothing _ = True -isGloballyScopedInModule (Just modName) (Scoped (GlobalSymbol sym _) _) = symbolModule sym == ModuleName () modName -isGloballyScopedInModule (Just _) _ = False diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs new file mode 100644 index 0000000..4a51099 --- /dev/null +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -0,0 +1,439 @@ +{-# LANGUAGE QuasiQuotes #-} + +module Haskell.Template.Detection.GuardsSpec where + +import Data.Bifunctor (Bifunctor (second), bimap) +import qualified Data.String.Interpolate as SI (i) +import Haskell.Template.Detection.Guards (Reason (..), detectRedundantGuardCondition) +import Language.Haskell.Exts (ParseResult (..), parse, prettyPrint) +import Language.Haskell.Names (annotate, loadBase) +import Test.Hspec (Spec, describe, it, shouldReturn) + +detect :: String -> IO [(String, [(Reason, String)])] +detect code = case parse code of + ParseOk mod' -> do + baseEnv <- loadBase + redundant <- detectRedundantGuardCondition $ annotate baseEnv mod' + pure $ map (bimap prettyPrint (map (second prettyPrint))) redundant + _ -> fail "failed to parse program" + +spec :: Spec +spec = + describe "redundant guard condition detection" $ do + it "should find one redundant guard condition" $ do + let code = + [SI.i|module Main where +test t + | t < 0 = 0 + | t >= 0 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t >= 0")])] + it "should find multiple redundant guard conditions" $ do + let code = + [SI.i|module Main where +test t + | t < 0 = 0 + | t >= 0 && t < 3 = 1 + | t >= 0 && t >= 3 && t < 9 = 2 +|] + detect code + `shouldReturn` [("test", [(Redundant, "t >= 0"), (Redundant, "t >= 0"), (Redundant, "t >= 3")])] + it "should not find redundant guard conditions" $ do + let code = + [SI.i|module Main where +test t + | t < 0 = 0 + | t >= 1 && t < 3 = 1 + | t < 9 = 2 +|] + detect code `shouldReturn` [] + it "should not find redundant guard conditions" $ do + let code = + [SI.i|module Main where +test t + | t < 3.9 = 0 + | t >= 4 && t < 6 = 1 + | t < 9 = 2 +|] + detect code `shouldReturn` [] + it "should not find redundant guard conditions (wrong scope)" $ do + let code = + [SI.i|module Main where +test t + | t < 0 = 0 + | (let t = 99 in t >= 0) && t < 6 = 1 + | t < 9 = 2 +|] + detect code `shouldReturn` [] + it "should find redundant guard condition (negated or)" $ do + let code = + [SI.i|module Main where +test t + | t < 0 || t > 0 = 0 + | t == 0 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t == 0")])] + it "should not find redundant guard conditions (otherwise)" $ do + let code = + [SI.i|module Main where +test t + | t < 0 || t > 0 = 0 + | otherwise = 1 +|] + detect code `shouldReturn` [] + it "should find redundant guard conditions (nested)" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t >= 4 && t < 9 = 1 + | t >= 4 && (t >= 9 && t < 20) = 1 +|] + detect code + `shouldReturn` [("test", [(Redundant, "t >= 4"), (Redundant, "t >= 4"), (Redundant, "t >= 9")])] + it "should find redundant guard conditions (and application)" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t >= 4 && t < 9 = 1 + | and [t >= 4, t >= 9, t < 20] = 1 +|] + detect code + `shouldReturn` [("test", [(Redundant, "t >= 4"), (Redundant, "t >= 4"), (Redundant, "t >= 9")])] + it "should find redundant guard conditions (comma separated)" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t >= 4 && t < 9 = 1 + | t >= 4, t >= 9, t < 20 = 1 +|] + detect code + `shouldReturn` [("test", [(Redundant, "t >= 4"), (Redundant, "t >= 4"), (Redundant, "t >= 9")])] + it "should find redundant guard condition (sum application)" $ do + let code = + [SI.i|module Main where +test t + | t < sum [1,1,2] = 0 + | t >= 4 && t < 9 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4")])] + it "should find redundant guard condition (manual sum)" $ do + let code = + [SI.i|module Main where +test t + | t < 1 + 1 + 2 = 0 + | t >= 4 && t < 9 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4")])] + it "should find redundant guard condition (product application)" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t >= product [2, 2] && t < 9 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t >= product [2, 2]")])] + it "should find redundant guard condition (infix div application)" $ do + let code = + [SI.i|module Main where +test t + | t `div` 2 == 4 = 0 + | t /= 8 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] + it "should find redundant guard condition (prefix div application" $ do + let code = + [SI.i|module Main where +test t + | div t 2 == 4 = 0 + | t /= 8 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] + it "should find redundant guard condition (prefix div application" $ do + let code = + [SI.i|module Main where +test t + | div t 2 == 4 = 0 + | t /= 9 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t /= 9")])] + it "should find redundant guard condition ( / application)" $ do + let code = + [SI.i|module Main where +test t + | t / 2 == 4 = 0 + | t /= 8 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] + it "shouldn't find redundant guard condition ( / application)" $ do + let code = + [SI.i|module Main where +test t + | t / 2 == 4 = 0 + | t /= 9 = 1 +|] + detect code `shouldReturn` [] + it "should find redundant guard condition on list" $ do + let code = + [SI.i|module Main where +test xs + | null xs = 0 + | length xs >= 1 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "length xs >= 1")])] + it "should find redundant guard condition (not application)" $ do + let code = + [SI.i|module Main where +test xs + | null xs = 0 + | not (null xs) = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "not (null xs)")])] + it "should ignore generators" $ do + let code = + [SI.i|module Main where +test t + | 1 <- t = 0 + | t /= 1 = 1 +|] + detect code `shouldReturn` [] + it "shouldn't wrongly report redundant conditions (comma separated)" $ do + let code = + [SI.i|module Main where +test t + | t < 0, t < -5 = 0 + | t >= 0 = 1 +|] + detect code `shouldReturn` [] + it "shouldn't wrongly report redundant conditions (conjunction)" $ do + let code = + [SI.i|module Main where +test t + | t < 0 && t < -5 = 0 + | t >= 0 = 1 +|] + detect code `shouldReturn` [] + it "currently doesn't report redundant conditions within a single guard" $ do + let code = + [SI.i|module Main where +test t + | t < 0 = 0 + | t <= 10 && t <= 20 = 1 +|] + detect code `shouldReturn` [] + it "should find redundant guard condition (equation)" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t - 2 >= 2 && t < 9 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t - 2 >= 2")])] + it "should find redundant guard condition (switched argument order)" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | 4 <= t && t < 9 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "4 <= t")])] + it "should find redundant guard condition (two variables)" $ do + let code = + [SI.i|module Main where +test t s + | t < 4 || t == s = 0 + | 4 <= t && s /= t && t < 9 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "4 <= t"), (Redundant, "s /= t")])] + it "should find redundant guard condition (with gap)" $ do + let code = + [SI.i|module Main where +test t + | t < 3.9 = 0 + | t >= 4 = 1 + | t < 9 = 2 +|] + detect code `shouldReturn` [("test", [(Redundant, "t < 9")])] + it "should find two redundant guard conditions based on skipped condition" $ do + let code = + [SI.i|module Main where +test t + | t > 3 = 0 + | t <= 3 && t < 5 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t <= 3"), (Redundant, "t < 5")])] + it "should find redundant guard conditions" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t >= 4 = 1 + | t >= 9 = 2 +|] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "t >= 9")])] + it "should mark every condition redundant after otherwise" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | otherwise = 1 + | t >= 9 = 2 +|] + detect code `shouldReturn` [("test", [(Unreachable, "t >= 9")])] + it "should mark a repeated otherwise redundant" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | otherwise = 1 + | otherwise = 2 +|] + detect code `shouldReturn` [("test", [(Unreachable, "otherwise")])] + it "should also mark otherwise as unreachable when previous conditions are exhaustive" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t >= 4 = 1 + | otherwise = 2 +|] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "otherwise")])] + it "should treat True like otherwise" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | True = 1 +|] + detect code `shouldReturn` [] + it "should mark True unreachable when previous conditions are exhaustive" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t >= 4 = 1 + | True = 2 +|] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "True")])] + it "should find redundant disjunction in guard" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t >= 4 || t >= 5 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4 || t >= 5")])] + it "should find redundant disjunction in guard" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | t >= 3 || t >= 5 = 1 +|] + detect code `shouldReturn` [("test", [(Redundant, "t >= 3 || t >= 5")])] + it "should mark every condition redundant after True" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | True = 1 + | t >= 9 = 2 +|] + detect code `shouldReturn` [("test", [(Unreachable, "t >= 9")])] + it "should mark a repeated True redundant" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | True = 1 + | True = 2 +|] + detect code `shouldReturn` [("test", [(Unreachable, "True")])] + it "correctly handles skipped False guard" $ do + let code = + [SI.i|module Main where +test t + | False = 0 + | t < 1 = 1 + | t < 10 = 2 +|] + detect code `shouldReturn` [("test", [(Unreachable, "False")])] + it "should report redundant conditions when single guard is exhaustive" $ do + let code = + [SI.i|module Main where +test t | t < 0 || t >= 0 = 0 +|] + detect code `shouldReturn` [("test", [(Redundant, "t < 0 || t >= 0")])] + it "should report redundant conditions when single guard is exhaustive (True)" $ do + let code = + [SI.i|module Main where +test t | True = 0 +|] + detect code `shouldReturn` [("test", [(Redundant, "True")])] + it "should report unreachable guard between other guards" $ do + let code = + [SI.i|module Main where +test t + | t < 0 = 0 + | False = 1 + | t < 10 = 2 +|] + detect code `shouldReturn` [("test", [(Unreachable, "False")])] + it "should report unreachable guard (non-trivial)" $ do + let code = + [SI.i|module Main where +test t + | t < 0 && t >= 0 = 0 + | t < 10 = 2 +|] + -- this result is weird because the whole conjunction is unreachable and not the two arguments + detect code `shouldReturn` [("test", [(Unreachable, "t < 0"), (Unreachable, "t >= 0")])] + it "should mark all following conditions as unreachable if already exhaustive" $ do + let code = + [SI.i|module Main where +test t + | True = 0 + | t < 10 = 2 + | t < 20 = 3 +|] + detect code `shouldReturn` [("test", [(Unreachable, "t < 10"), (Unreachable, "t < 20")])] + it "should mark identical guard as unreachable" $ do + let code = + [SI.i|module Main where +test t + | t < 10 = 0 + | t < 10 = 2 + | t < 20 = 3 +|] + detect code `shouldReturn` [("test", [(Unreachable, "t < 10")])] + it "should mark superfluous rows" $ do + let code = + [SI.i|module Main where +scene t + | t < 3 = 0 + | t > 4 = 1 + | t < 1 = 2 + | otherwise = 3 +|] + detect code `shouldReturn` [("scene", [(Unreachable, "t < 1")])] + it "correctly works with lists" $ do + let code = + [SI.i|module Main where +f list + | length list == 0 = True + | length list >= 2 = f (drop 2 list) + | length list == 1 = False + | otherwise = False +|] + detect code `shouldReturn` [("f", [(Redundant, "length list == 1"), (Unreachable, "otherwise")])] + it "correctly works with lists" $ do + let code = + [SI.i|module Main where +f list + | length list == 0 = True + | length list >= 2 = f (drop 2 list) + | length list == 1 = False +|] + detect code `shouldReturn` [("f", [(Redundant, "length list == 1")])]