From 95751a90cb4488a5890924c2c28f107fd5d526cf Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:32:00 +0000 Subject: [PATCH 01/35] add check for redundant guard conditions --- haskell-template-task.cabal | 7 + package.yaml | 3 + src/Haskell/Template/Detection/Guards.hs | 318 +++++++++++++++++++++++ stack.yaml | 1 + 4 files changed, 329 insertions(+) create mode 100644 src/Haskell/Template/Detection/Guards.hs diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index b8bd804..86750fd 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -27,6 +27,7 @@ source-repository head library exposed-modules: + Haskell.Template.Detection.Guards Haskell.Template.Match Haskell.Template.Task other-modules: @@ -42,6 +43,7 @@ library , extra , file-embed , filepath + , haskell-names , haskell-src-exts , haskell-template-task-raw , hint @@ -51,8 +53,10 @@ library , string-interpolate , syb , text + , witherable , wl-pprint-text , yaml + , z3 default-language: Haskell2010 test-suite haskell-template-task-test @@ -78,6 +82,7 @@ test-suite haskell-template-task-test , extra , file-embed , filepath + , haskell-names , haskell-src-exts , haskell-template-task , haskell-template-task-raw @@ -92,6 +97,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 ed23d36..0bcf295 100644 --- a/package.yaml +++ b/package.yaml @@ -35,6 +35,9 @@ dependencies: - wl-pprint-text - yaml - aeson + - haskell-names + - z3 + - witherable 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..b6fc95b --- /dev/null +++ b/src/Haskell/Template/Detection/Guards.hs @@ -0,0 +1,318 @@ +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE ViewPatterns #-} + +module Haskell.Template.Detection.Guards (detectRedundantGuardCondition) where + +import Control.Monad (forM, join, liftM2, liftM3, void, (<=<)) +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 Language.Haskell.Exts ( + Decl (FunBind, PatBind), + Exp (..), + GuardedRhs (..), + Literal (..), + Match (InfixMatch, Match), + Module (Module), + ModuleName (..), + Name (..), + Pat (PVar), + QName (Qual, UnQual), + QOp (..), + Rhs (GuardedRhss, UnGuardedRhs), + SrcSpanInfo, + Stmt (Qualifier), + ann, + ) +import Language.Haskell.Names ( + NameInfo (GlobalSymbol), + Scoped (..), + Symbol (..), + ) +import Witherable (witherM) +import Z3.Monad ( + AST, + Result (..), + Z3, + assert, + check, + evalZ3, + mkAdd, + mkAnd, + mkBoolVar, + mkDiv, + mkEq, + mkFalse, + mkGe, + mkGt, + mkImplies, + mkInt, + mkIntSort, + mkIntVar, + mkIte, + mkLe, + mkLt, + mkMod, + mkMul, + mkNot, + mkNumeral, + mkOr, + mkRealSort, + mkRealVar, + mkRem, + mkStringSymbol, + mkSub, + mkTrue, + ) + +-- | Shorthand for a scoped expression +type ScopedExp a = Exp (Scoped a) + +{- | 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 + +{- | 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 + +-- | Unwraps an expression from parentheses +unwrapParens :: Exp a -> Exp a +unwrapParens (Paren _ e) = unwrapParens e +unwrapParens e = e + +-- | Returns a list of guard conditions which are redundant +checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO [ScopedExp a] +checkForRedundancy [] = pure [] +checkForRedundancy [_] = pure [] +checkForRedundancy (x : xs) = checking (NE.toList $ fmap snd x) (map NE.toList xs) + where + checking _ [] = pure [] + checking skipped ([] : remaining) = checking skipped remaining + checking skipped remaining = do + let allRemaining = concat remaining + + results <- forM allRemaining $ \(e, c) -> do + isRedundant <- prove $ do + known <- mkAnd =<< mapM (>>= mkNot) skipped + inQuestion <- c + + mkImplies known inQuestion + return ((e, c), isRedundant) + + let redundant = map fst $ filter snd results + + restResults <- + checking + ((mkAnd =<< mapM snd (head remaining)) : skipped) + (map (filter ((`notElem` map fst redundant) . fst)) $ drop 1 remaining) + + return $ map fst redundant ++ restResults + +detectRedundantGuardCondition + :: Module (Scoped SrcSpanInfo) + -> IO [(Name (Scoped SrcSpanInfo), [Exp (Scoped 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) -> + ((\v -> mkSub [v]) <=< 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 (\a b -> mkAdd [a, b]) l r +arithAppToZ3 (Just "GHC.Num") "-" [l, r] = + combineMaybeArithExprs (\a b -> mkSub [a, b]) l r +arithAppToZ3 (Just "GHC.Num") "*" [l, r] = + combineMaybeArithExprs (\a b -> mkMul [a, b]) l r +arithAppToZ3 (Just "GHC.Real") "/" [l, r] = + combineMaybeArithExprs mkDiv l r +arithAppToZ3 (Just "GHC.Real") "div" [l, r] = + combineMaybeArithExprs mkDiv l r +arithAppToZ3 (Just "GHC.Real") "mod" [l, r] = + combineMaybeArithExprs mkMod l r +arithAppToZ3 (Just "GHC.Real") "rem" [l, r] = + combineMaybeArithExprs 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 _ (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 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 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 => (AST -> AST -> Z3 AST) -> ScopedExp a -> ScopedExp a -> Maybe (Z3 AST) +combineMaybeArithExprs f l r = liftM2 (\(_, a) (_, b) -> join $ liftM2 f a b) (arithAstToZ3 l) (arithAstToZ3 r) + +-- | 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/stack.yaml b/stack.yaml index ceaaecf..f87719a 100644 --- a/stack.yaml +++ b/stack.yaml @@ -10,3 +10,4 @@ extra-deps: - git: https://github.com/owestphal/type-match commit: e1afab43d2e8bfa5e2006492ed34060036e7be51 - raw + - haskell-names-0.9.9.1@sha256:79bb41850a7832543731bdbcaf7aace6ddfe121d78656c3c8b184c9ebf36ea18,12681 From 4508e2a7016ebf2c2f0c38ca7d2cac56e06ef5bd Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:38:04 +0000 Subject: [PATCH 02/35] add spec --- haskell-template-task.cabal | 1 + test/Haskell/Template/Detection/GuardsSpec.hs | 173 ++++++++++++++++++ 2 files changed, 174 insertions(+) create mode 100644 test/Haskell/Template/Detection/GuardsSpec.hs diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index 86750fd..26fe645 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -63,6 +63,7 @@ test-suite haskell-template-task-test type: exitcode-stdio-1.0 main-is: Spec.hs other-modules: + Haskell.Template.Detection.GuardsSpec Haskell.Template.MatchSpec Haskell.Template.TaskSpec Paths_haskell_template_task diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs new file mode 100644 index 0000000..307428f --- /dev/null +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -0,0 +1,173 @@ +{-# LANGUAGE QuasiQuotes #-} + +module Haskell.Template.Detection.GuardsSpec where + +import Data.Bifunctor (bimap) +import qualified Data.String.Interpolate as SI (i) +import Haskell.Template.Detection.Guards (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, [String])] +detect code = case parse code of + ParseOk mod' -> do + baseEnv <- loadBase + redundant <- detectRedundantGuardCondition $ annotate baseEnv mod' + pure $ map (bimap prettyPrint (map 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", ["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", ["t >= 0", "t >= 0", "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", ["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", ["t >= 4", "t >= 4", "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", ["t >= 4", "t >= 4", "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", ["t >= 4", "t >= 4", "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", ["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", ["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", ["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", ["t /= 8"])] + 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", ["t /= 8"])] + 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", ["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", ["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` [] From d62193d5b76bde2b4e0a8cc33c25dc38c4e9dd05 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:56:21 +0000 Subject: [PATCH 03/35] allow words --- .github/actions/spelling/allow.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index 9406d9a..6590234 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -1,6 +1,7 @@ Aeson autotool Bifunctor +bimap concat elems finalise @@ -17,12 +18,20 @@ hlint Hspec HUnit hyperlinks +Ite mempty mplus msum +Mul mzero +QCon +QName +QOp +QVar snd thd uncurry unlines +Unsat +Witherable yml From a780d45274fa396a8611ce354c9be0735a435e25 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:36:14 +0000 Subject: [PATCH 04/35] share unwrapParens --- haskell-template-task.cabal | 1 + src/Haskell/Template/Detection/Guards.hs | 6 +----- src/Haskell/Template/Detection/Helper.hs | 10 ++++++++++ src/Haskell/Template/Detection/Maybe.hs | 15 ++++++--------- 4 files changed, 18 insertions(+), 14 deletions(-) create mode 100644 src/Haskell/Template/Detection/Helper.hs diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index b5ea76b..1aaf7d9 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -28,6 +28,7 @@ source-repository head library exposed-modules: Haskell.Template.Detection.Guards + Haskell.Template.Detection.Helper Haskell.Template.Detection.Maybe Haskell.Template.Match Haskell.Template.Task diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index b6fc95b..882b498 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -9,6 +9,7 @@ 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 (unwrapParens) import Language.Haskell.Exts ( Decl (FunBind, PatBind), Exp (..), @@ -110,11 +111,6 @@ qOpActName' :: QOp (Scoped a) -> Maybe (Maybe String, String) qOpActName' (QVarOp _ (qActName -> res)) = res qOpActName' (QConOp _ (qActName -> res)) = res --- | Unwraps an expression from parentheses -unwrapParens :: Exp a -> Exp a -unwrapParens (Paren _ e) = unwrapParens e -unwrapParens e = e - -- | Returns a list of guard conditions which are redundant checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO [ScopedExp a] checkForRedundancy [] = pure [] diff --git a/src/Haskell/Template/Detection/Helper.hs b/src/Haskell/Template/Detection/Helper.hs new file mode 100644 index 0000000..a19cf07 --- /dev/null +++ b/src/Haskell/Template/Detection/Helper.hs @@ -0,0 +1,10 @@ +module Haskell.Template.Detection.Helper ( + unwrapParens, +) where + +import Language.Haskell.Exts (Exp (..)) + +-- | Unwraps an expression from parentheses +unwrapParens :: Exp a -> Exp a +unwrapParens (Paren _ e) = unwrapParens e +unwrapParens e = e diff --git a/src/Haskell/Template/Detection/Maybe.hs b/src/Haskell/Template/Detection/Maybe.hs index dd10690..b647538 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 (unwrapParens) import Language.Haskell.Exts ( Alt (..), Decl (..), @@ -57,7 +58,7 @@ declName (PatBind _ (PVar _ pn) _ _) = Just $ fromName pn declName _ = Nothing exprToIfInfo :: String -> Exp (Scoped SrcSpanInfo) -> Maybe (Exp (Scoped SrcSpanInfo), Exp ()) -exprToIfInfo valueName expr@(If _ cond t e) = case removeParens cond of +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 +80,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 @@ -107,7 +108,7 @@ hasFromJust mExpr expr = notNull $ listify isFromJustApp expr where isFromJustApp :: Exp (Scoped 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 @@ -132,16 +133,12 @@ replaceFromJustWithValue :: String -> Exp (Scoped SrcSpanInfo) -> Exp (Scoped Sr replaceFromJustWithValue valueName maybeValue = void . everywhere' (mkT replace) where replace :: Exp (Scoped SrcSpanInfo) -> Exp (Scoped SrcSpanInfo) - replace expr = case removeParens expr of + 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 From e2dccd03f7164b3caa20d5db7a3cc791d91a2962 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:45:52 +0000 Subject: [PATCH 05/35] share qName and qActName --- src/Haskell/Template/Detection/Guards.hs | 30 +++--------------------- src/Haskell/Template/Detection/Helper.hs | 29 ++++++++++++++++++++++- 2 files changed, 31 insertions(+), 28 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 882b498..5833a65 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -9,7 +9,7 @@ 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 (unwrapParens) +import Haskell.Template.Detection.Helper (qActName, qName, unwrapParens) import Language.Haskell.Exts ( Decl (FunBind, PatBind), Exp (..), @@ -17,10 +17,9 @@ import Language.Haskell.Exts ( Literal (..), Match (InfixMatch, Match), Module (Module), - ModuleName (..), Name (..), Pat (PVar), - QName (Qual, UnQual), + QName, QOp (..), Rhs (GuardedRhss, UnGuardedRhs), SrcSpanInfo, @@ -28,9 +27,8 @@ import Language.Haskell.Exts ( ann, ) import Language.Haskell.Names ( - NameInfo (GlobalSymbol), + NameInfo, Scoped (..), - Symbol (..), ) import Witherable (witherM) import Z3.Monad ( @@ -71,28 +69,6 @@ import Z3.Monad ( -- | Shorthand for a scoped expression type ScopedExp a = Exp (Scoped a) -{- | 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 - {- | Returns the actual name of a (potentially) qualified name together with its scope information. | | Returns `Nothing` when `Special` is passed as the argument. diff --git a/src/Haskell/Template/Detection/Helper.hs b/src/Haskell/Template/Detection/Helper.hs index a19cf07..ad5bcfe 100644 --- a/src/Haskell/Template/Detection/Helper.hs +++ b/src/Haskell/Template/Detection/Helper.hs @@ -1,10 +1,37 @@ +{-# LANGUAGE ViewPatterns #-} + module Haskell.Template.Detection.Helper ( unwrapParens, + qName, + qActName, ) where -import Language.Haskell.Exts (Exp (..)) +import Language.Haskell.Exts (Exp (..), ModuleName (..), Name (..), QName (..)) +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 From 7131de8d60342e90943e7389898ae45d71644084 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:47:12 +0000 Subject: [PATCH 06/35] refactor hasName --- src/Haskell/Template/Detection/Maybe.hs | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/Haskell/Template/Detection/Maybe.hs b/src/Haskell/Template/Detection/Maybe.hs index b647538..5c0f3a7 100644 --- a/src/Haskell/Template/Detection/Maybe.hs +++ b/src/Haskell/Template/Detection/Maybe.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE ViewPatterns #-} + module Haskell.Template.Detection.Maybe (collectIfsWithMaybeChecks) where import Control.Monad (void) @@ -7,7 +9,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 (unwrapParens) +import Haskell.Template.Detection.Helper (qActName, unwrapParens) import Language.Haskell.Exts ( Alt (..), Decl (..), @@ -15,7 +17,6 @@ import Language.Haskell.Exts ( FieldDecl (..), Match (..), Module (..), - ModuleName (..), Name (..), Pat (..), QName (..), @@ -23,7 +24,7 @@ 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 _ _ _ _ decls) = concat $ mapMaybe process decls @@ -140,13 +141,5 @@ replaceFromJustWithValue valueName maybeValue = void . everywhere' (mkT replace) _ -> expr 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 mModuleName qName (qActName -> Just (modName, name)) = modName == mModuleName && name == qName hasName _ _ _ = False - -isGloballyScopedInModule :: Maybe String -> Scoped l -> Bool -isGloballyScopedInModule Nothing _ = True -isGloballyScopedInModule (Just modName) (Scoped (GlobalSymbol sym _) _) = symbolModule sym == ModuleName () modName -isGloballyScopedInModule (Just _) _ = False From 4e22ab87da7217c31ae8945bcbd419d90d472296 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:52:52 +0000 Subject: [PATCH 07/35] share and make use of ScopedExp --- src/Haskell/Template/Detection/Guards.hs | 7 ++----- src/Haskell/Template/Detection/Helper.hs | 4 ++++ src/Haskell/Template/Detection/Maybe.hs | 20 ++++++++++---------- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 5833a65..553e211 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -9,7 +9,7 @@ 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 (qActName, qName, unwrapParens) +import Haskell.Template.Detection.Helper (ScopedExp, qActName, qName, unwrapParens) import Language.Haskell.Exts ( Decl (FunBind, PatBind), Exp (..), @@ -66,9 +66,6 @@ import Z3.Monad ( mkTrue, ) --- | Shorthand for a scoped expression -type ScopedExp a = Exp (Scoped a) - {- | Returns the actual name of a (potentially) qualified name together with its scope information. | | Returns `Nothing` when `Special` is passed as the argument. @@ -117,7 +114,7 @@ checkForRedundancy (x : xs) = checking (NE.toList $ fmap snd x) (map NE.toList x detectRedundantGuardCondition :: Module (Scoped SrcSpanInfo) - -> IO [(Name (Scoped SrcSpanInfo), [Exp (Scoped SrcSpanInfo)])] + -> IO [(Name (Scoped SrcSpanInfo), [ScopedExp SrcSpanInfo])] detectRedundantGuardCondition mod' = flip witherM (extractFromModule mod') $ \(name, constraints) -> do redundant <- checkForRedundancy constraints diff --git a/src/Haskell/Template/Detection/Helper.hs b/src/Haskell/Template/Detection/Helper.hs index ad5bcfe..d087e1b 100644 --- a/src/Haskell/Template/Detection/Helper.hs +++ b/src/Haskell/Template/Detection/Helper.hs @@ -4,6 +4,7 @@ module Haskell.Template.Detection.Helper ( unwrapParens, qName, qActName, + ScopedExp, ) where import Language.Haskell.Exts (Exp (..), ModuleName (..), Name (..), QName (..)) @@ -35,3 +36,6 @@ qActName q = case qName q of where globalModName (Scoped (GlobalSymbol (symbolModule -> ModuleName () name) _) _) = Just name globalModName _ = Nothing + +-- | Shorthand for a scoped expression +type ScopedExp a = Exp (Scoped a) diff --git a/src/Haskell/Template/Detection/Maybe.hs b/src/Haskell/Template/Detection/Maybe.hs index 5c0f3a7..5845012 100644 --- a/src/Haskell/Template/Detection/Maybe.hs +++ b/src/Haskell/Template/Detection/Maybe.hs @@ -9,7 +9,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 (qActName, unwrapParens) +import Haskell.Template.Detection.Helper (ScopedExp, qActName, unwrapParens) import Language.Haskell.Exts ( Alt (..), Decl (..), @@ -26,7 +26,7 @@ import Language.Haskell.Exts ( ) 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. @@ -58,7 +58,7 @@ declName (PatBind _ (PVar _ pn) _ _) = Just $ fromName pn fromName (Symbol _ n) = n declName _ = Nothing -exprToIfInfo :: String -> Exp (Scoped SrcSpanInfo) -> Maybe (Exp (Scoped SrcSpanInfo), Exp ()) +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 @@ -104,19 +104,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 (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 @@ -130,10 +130,10 @@ 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 :: ScopedExp SrcSpanInfo -> ScopedExp SrcSpanInfo replace expr = case unwrapParens expr of App l (Var _ vn) fnBody | hasName (Just "Data.Maybe") "fromJust" vn && fmap void (unwrapParens fnBody) == fmap void maybeValue -> From da9620a000f373f2bae959945858fa2f1f02cfb5 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:54:55 +0000 Subject: [PATCH 08/35] add haddock comment --- src/Haskell/Template/Detection/Guards.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 553e211..49f45dd 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -112,6 +112,7 @@ checkForRedundancy (x : xs) = checking (NE.toList $ fmap snd x) (map NE.toList x return $ map fst redundant ++ restResults +-- | Return redundant guard conditions for each definition detectRedundantGuardCondition :: Module (Scoped SrcSpanInfo) -> IO [(Name (Scoped SrcSpanInfo), [ScopedExp SrcSpanInfo])] From 7c49294fcc29d19912db3a68af69ce980ce4bbfb Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:13:15 +0000 Subject: [PATCH 09/35] fix computation of knowledge --- src/Haskell/Template/Detection/Guards.hs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 49f45dd..4e1f398 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -3,7 +3,7 @@ module Haskell.Template.Detection.Guards (detectRedundantGuardCondition) where -import Control.Monad (forM, join, liftM2, liftM3, void, (<=<)) +import Control.Monad (forM, join, liftM2, liftM3, void, (<=<), (>=>)) import Data.List (singleton) import Data.List.Extra (nubOrd) import Data.List.NonEmpty (NonEmpty) @@ -88,7 +88,7 @@ qOpActName' (QConOp _ (qActName -> res)) = res checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO [ScopedExp a] checkForRedundancy [] = pure [] checkForRedundancy [_] = pure [] -checkForRedundancy (x : xs) = checking (NE.toList $ fmap snd x) (map NE.toList xs) +checkForRedundancy (x : xs) = checking [NE.toList $ fmap snd x] (map NE.toList xs) where checking _ [] = pure [] checking skipped ([] : remaining) = checking skipped remaining @@ -97,7 +97,8 @@ checkForRedundancy (x : xs) = checking (NE.toList $ fmap snd x) (map NE.toList x results <- forM allRemaining $ \(e, c) -> do isRedundant <- prove $ do - known <- mkAnd =<< mapM (>>= mkNot) skipped + let knownGuards = map (sequence >=> mkAnd) skipped + known <- mkAnd =<< mapM (>>= mkNot) knownGuards inQuestion <- c mkImplies known inQuestion @@ -107,7 +108,7 @@ checkForRedundancy (x : xs) = checking (NE.toList $ fmap snd x) (map NE.toList x restResults <- checking - ((mkAnd =<< mapM snd (head remaining)) : skipped) + (fmap snd (head remaining) : skipped) (map (filter ((`notElem` map fst redundant) . fst)) $ drop 1 remaining) return $ map fst redundant ++ restResults From 5dfe170e0dc2da89b35597441338190bd2ca7985 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:13:36 +0000 Subject: [PATCH 10/35] fix translation of negative numbers --- src/Haskell/Template/Detection/Guards.hs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 4e1f398..4e8469c 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -64,6 +64,7 @@ import Z3.Monad ( mkStringSymbol, mkSub, mkTrue, + mkUnaryMinus, ) {- | Returns the actual name of a (potentially) qualified name together with its scope information. @@ -187,7 +188,7 @@ arithAstToZ3 (unwrapParens -> expr) = (Let _ _ e) -> snd <$> arithAstToZ3 e (NegApp _ e) -> - ((\v -> mkSub [v]) <=< snd) <$> arithAstToZ3 e + (mkUnaryMinus <=< snd) <$> arithAstToZ3 e _ -> Nothing From 27c621add87e181d5b4b595b30aa676d481c341f Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:15:54 +0000 Subject: [PATCH 11/35] add more test cases --- test/Haskell/Template/Detection/GuardsSpec.hs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index 307428f..fed7841 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -169,5 +169,29 @@ test xs 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 in a single guard" $ do + let code = + [SI.i|module Main where +test t + | t < 0 = 0 + | t <= 10 && t <= 20 = 1 |] detect code `shouldReturn` [] From 0b40561b9ab3407ce0f160a3983548f14ac0e97e Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:27:58 +0000 Subject: [PATCH 12/35] clarify test case --- test/Haskell/Template/Detection/GuardsSpec.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index fed7841..329ad08 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -187,7 +187,7 @@ test t | t >= 0 = 1 |] detect code `shouldReturn` [] - it "currently doesn't report redundant conditions in a single guard" $ do + it "currently doesn't report redundant conditions within a single guard" $ do let code = [SI.i|module Main where test t From 8570c103521431637e6a19eef809c567df42df75 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:44:37 +0000 Subject: [PATCH 13/35] add more tests --- test/Haskell/Template/Detection/GuardsSpec.hs | 86 ++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index 329ad08..78811a4 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -7,7 +7,7 @@ import qualified Data.String.Interpolate as SI (i) import Haskell.Template.Detection.Guards (detectRedundantGuardCondition) import Language.Haskell.Exts (ParseResult (..), parse, prettyPrint) import Language.Haskell.Names (annotate, loadBase) -import Test.Hspec (Spec, describe, it, shouldReturn) +import Test.Hspec (Spec, describe, it, shouldReturn, xit) detect :: String -> IO [(String, [String])] detect code = case parse code of @@ -113,6 +113,14 @@ test t test t | t < sum [1,1,2] = 0 | t >= 4 && t < 9 = 1 +|] + detect code `shouldReturn` [("test", ["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", ["t >= 4"])] it "should find redundant guard condition (product application)" $ do @@ -195,3 +203,79 @@ test t | 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", ["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", ["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", ["4 <= t","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", ["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", ["t <= 3", "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", ["t >= 4", "t >= 9"])] + xit "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", ["t >= 9"])] + xit "should mark every condition redundant after otherwise" $ do + let code = + [SI.i|module Main where +test t + | t < 4 = 0 + | otherwise = 1 + | otherwise = 2 +|] + detect code `shouldReturn` [("test", ["otherwise"])] + 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", ["t >= 4 || t >= 5"])] From 25ce4e8f9ff7c424901c4bbf03576bbf5937a4f2 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:12:27 +0000 Subject: [PATCH 14/35] allow xit --- .github/actions/spelling/allow.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index cecb3ae..60f9a13 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -39,4 +39,5 @@ unlines Unsat Utf Witherable +xit yml From 5f3209ee0b403f170392ce953ccea319b3c71e60 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:51:27 +0000 Subject: [PATCH 15/35] special treatment for otherwise --- src/Haskell/Template/Detection/Guards.hs | 11 ++++++++++- test/Haskell/Template/Detection/GuardsSpec.hs | 6 +++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 4e8469c..bd892b2 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -67,6 +67,11 @@ import Z3.Monad ( mkUnaryMinus, ) +-- | Returns True when given expression represents 'otherwise' +isOtherwise :: ScopedExp a -> Bool +isOtherwise (unwrapParens -> Var _ (qActName -> Just (Just "GHC.Base", "otherwise"))) = True +isOtherwise _ = False + {- | Returns the actual name of a (potentially) qualified name together with its scope information. | | Returns `Nothing` when `Special` is passed as the argument. @@ -102,7 +107,9 @@ checkForRedundancy (x : xs) = checking [NE.toList $ fmap snd x] (map NE.toList x known <- mkAnd =<< mapM (>>= mkNot) knownGuards inQuestion <- c - mkImplies known inQuestion + if isOtherwise e + then mkNot known + else mkImplies known inQuestion return ((e, c), isRedundant) let redundant = map fst $ filter snd results @@ -221,6 +228,8 @@ 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) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index 78811a4..a735223 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -7,7 +7,7 @@ import qualified Data.String.Interpolate as SI (i) import Haskell.Template.Detection.Guards (detectRedundantGuardCondition) import Language.Haskell.Exts (ParseResult (..), parse, prettyPrint) import Language.Haskell.Names (annotate, loadBase) -import Test.Hspec (Spec, describe, it, shouldReturn, xit) +import Test.Hspec (Spec, describe, it, shouldReturn) detect :: String -> IO [(String, [String])] detect code = case parse code of @@ -253,7 +253,7 @@ test t | t >= 9 = 2 |] detect code `shouldReturn` [("test", ["t >= 4", "t >= 9"])] - xit "should mark every condition redundant after otherwise" $ do + it "should mark every condition redundant after otherwise" $ do let code = [SI.i|module Main where test t @@ -262,7 +262,7 @@ test t | t >= 9 = 2 |] detect code `shouldReturn` [("test", ["t >= 9"])] - xit "should mark every condition redundant after otherwise" $ do + it "should mark a repeated otherwise redundant" $ do let code = [SI.i|module Main where test t From 82d8d88fff646d7dce3527c7aee53a75ced3c3cf Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:52:15 +0000 Subject: [PATCH 16/35] formatting --- test/Haskell/Template/Detection/GuardsSpec.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index a735223..168bb8d 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -226,7 +226,7 @@ test t s | t < 4 || t == s = 0 | 4 <= t && s /= t && t < 9 = 1 |] - detect code `shouldReturn` [("test", ["4 <= t","s /= t"])] + detect code `shouldReturn` [("test", ["4 <= t", "s /= t"])] it "should find redundant guard condition (with gap)" $ do let code = [SI.i|module Main where From 725dc63f392fe750f093df59f2b485e987d881c7 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:04:09 +0000 Subject: [PATCH 17/35] test case --- test/Haskell/Template/Detection/GuardsSpec.hs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index 168bb8d..0df792f 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -271,6 +271,15 @@ test t | otherwise = 2 |] detect code `shouldReturn` [("test", ["otherwise"])] + it "should also mark otherwise as redundant 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", ["t >= 4", "otherwise"])] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where From e80936fd30ffa5bfad8237c2c5aee5d0539db1f5 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:28:41 +0000 Subject: [PATCH 18/35] handle True just like otherwise --- src/Haskell/Template/Detection/Guards.hs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index bd892b2..1b38082 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -67,10 +67,11 @@ import Z3.Monad ( mkUnaryMinus, ) --- | Returns True when given expression represents 'otherwise' -isOtherwise :: ScopedExp a -> Bool -isOtherwise (unwrapParens -> Var _ (qActName -> Just (Just "GHC.Base", "otherwise"))) = True -isOtherwise _ = False +-- | Returns True when given expression represents 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. | @@ -107,7 +108,7 @@ checkForRedundancy (x : xs) = checking [NE.toList $ fmap snd x] (map NE.toList x known <- mkAnd =<< mapM (>>= mkNot) knownGuards inQuestion <- c - if isOtherwise e + if isTruthfulGuard e then mkNot known else mkImplies known inQuestion return ((e, c), isRedundant) From 1946ffc4165a31fe38a440b3ef42b4bcdab0ee49 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:45:17 +0000 Subject: [PATCH 19/35] add even more test cases --- test/Haskell/Template/Detection/GuardsSpec.hs | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index 0df792f..c68abca 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -280,6 +280,23 @@ test t | otherwise = 2 |] detect code `shouldReturn` [("test", ["t >= 4", "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 redundant 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", ["t >= 4", "True"])] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where @@ -288,3 +305,38 @@ test t | t >= 4 || t >= 5 = 1 |] detect code `shouldReturn` [("test", ["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", ["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", ["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", ["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` [] From 40e3551b0b53e4ccee78ab75988f68e2bd305adc Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:48:33 +0000 Subject: [PATCH 20/35] differentiate between redundant and unreachable conditions --- src/Haskell/Template/Detection/Guards.hs | 49 ++++++++------ test/Haskell/Template/Detection/GuardsSpec.hs | 64 +++++++++---------- 2 files changed, 62 insertions(+), 51 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 1b38082..3071ee9 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -1,7 +1,7 @@ {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} -module Haskell.Template.Detection.Guards (detectRedundantGuardCondition) where +module Haskell.Template.Detection.Guards (detectRedundantGuardCondition, Reason (..)) where import Control.Monad (forM, join, liftM2, liftM3, void, (<=<), (>=>)) import Data.List (singleton) @@ -46,6 +46,7 @@ import Z3.Monad ( mkFalse, mkGe, mkGt, + mkIff, mkImplies, mkInt, mkIntSort, @@ -67,6 +68,9 @@ import Z3.Monad ( mkUnaryMinus, ) +data Reason = Redundant | Unreachable + deriving (Eq, Ord, Show) + -- | Returns True when given expression represents truthful value isTruthfulGuard :: ScopedExp a -> Bool isTruthfulGuard (unwrapParens -> Var _ (qActName -> Just (Just "GHC.Base", "otherwise"))) = True @@ -92,7 +96,7 @@ qOpActName' (QVarOp _ (qActName -> res)) = res qOpActName' (QConOp _ (qActName -> res)) = res -- | Returns a list of guard conditions which are redundant -checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO [ScopedExp a] +checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO [(Reason, ScopedExp a)] checkForRedundancy [] = pure [] checkForRedundancy [_] = pure [] checkForRedundancy (x : xs) = checking [NE.toList $ fmap snd x] (map NE.toList xs) @@ -100,32 +104,39 @@ checkForRedundancy (x : xs) = checking [NE.toList $ fmap snd x] (map NE.toList x checking _ [] = pure [] checking skipped ([] : remaining) = checking skipped remaining checking skipped remaining = do - let allRemaining = concat remaining + let + allRemaining = concat remaining + knownGuards = map (sequence >=> mkAnd) skipped + known' = mkAnd =<< mapM (>>= mkNot) knownGuards + + isUnreachable <- prove $ do + known <- known' + mkIff known =<< mkFalse - results <- forM allRemaining $ \(e, c) -> do - isRedundant <- prove $ do - let knownGuards = map (sequence >=> mkAnd) skipped - known <- mkAnd =<< mapM (>>= mkNot) knownGuards - inQuestion <- c + if isUnreachable + then return $ map (\(e, _) -> (Unreachable, e)) allRemaining + else do + results <- forM allRemaining $ \(e, c) -> do + isRedundant <- prove $ do + known <- known' + inQuestion <- c - if isTruthfulGuard e - then mkNot known - else mkImplies known inQuestion - return ((e, c), isRedundant) + mkImplies known inQuestion + return ((e, c), isRedundant) - let redundant = map fst $ filter snd results + let redundant = map fst $ filter (\((e, _), r) -> r && not (isTruthfulGuard e)) results - restResults <- - checking - (fmap snd (head remaining) : skipped) - (map (filter ((`notElem` map fst redundant) . fst)) $ drop 1 remaining) + restResults <- + checking + (fmap snd (head remaining) : skipped) + (map (filter ((`notElem` map fst redundant) . fst)) $ drop 1 remaining) - return $ map fst redundant ++ restResults + return $ map (\(e, _) -> (Redundant, e)) redundant ++ restResults -- | Return redundant guard conditions for each definition detectRedundantGuardCondition :: Module (Scoped SrcSpanInfo) - -> IO [(Name (Scoped SrcSpanInfo), [ScopedExp SrcSpanInfo])] + -> IO [(Name (Scoped SrcSpanInfo), [(Reason, ScopedExp SrcSpanInfo)])] detectRedundantGuardCondition mod' = flip witherM (extractFromModule mod') $ \(name, constraints) -> do redundant <- checkForRedundancy constraints diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index c68abca..b0bf6ed 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -2,19 +2,19 @@ module Haskell.Template.Detection.GuardsSpec where -import Data.Bifunctor (bimap) +import Data.Bifunctor (Bifunctor (second), bimap) import qualified Data.String.Interpolate as SI (i) -import Haskell.Template.Detection.Guards (detectRedundantGuardCondition) +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, [String])] +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 prettyPrint)) redundant + pure $ map (bimap prettyPrint (map (second prettyPrint))) redundant _ -> fail "failed to parse program" spec :: Spec @@ -27,7 +27,7 @@ test t | t < 0 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [("test", ["t >= 0"])] + detect code `shouldReturn` [("test", [(Redundant, "t >= 0")])] it "should find multiple redundant guard conditions" $ do let code = [SI.i|module Main where @@ -36,7 +36,7 @@ test t | t >= 0 && t < 3 = 1 | t >= 0 && t >= 3 && t < 9 = 2 |] - detect code `shouldReturn` [("test", ["t >= 0", "t >= 0", "t >= 3"])] + 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 @@ -71,7 +71,7 @@ test t | t < 0 || t > 0 = 0 | t == 0 = 1 |] - detect code `shouldReturn` [("test", ["t == 0"])] + detect code `shouldReturn` [("test", [(Redundant, "t == 0")])] it "should not find redundant guard conditions (otherwise)" $ do let code = [SI.i|module Main where @@ -88,7 +88,7 @@ test t | t >= 4 && t < 9 = 1 | t >= 4 && (t >= 9 && t < 20) = 1 |] - detect code `shouldReturn` [("test", ["t >= 4", "t >= 4", "t >= 9"])] + 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 @@ -97,7 +97,7 @@ test t | t >= 4 && t < 9 = 1 | and [t >= 4, t >= 9, t < 20] = 1 |] - detect code `shouldReturn` [("test", ["t >= 4", "t >= 4", "t >= 9"])] + 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 @@ -106,7 +106,7 @@ test t | t >= 4 && t < 9 = 1 | t >= 4, t >= 9, t < 20 = 1 |] - detect code `shouldReturn` [("test", ["t >= 4", "t >= 4", "t >= 9"])] + 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 @@ -114,7 +114,7 @@ test t | t < sum [1,1,2] = 0 | t >= 4 && t < 9 = 1 |] - detect code `shouldReturn` [("test", ["t >= 4"])] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4")])] it "should find redundant guard condition (manual sum)" $ do let code = [SI.i|module Main where @@ -122,7 +122,7 @@ test t | t < 1 + 1 + 2 = 0 | t >= 4 && t < 9 = 1 |] - detect code `shouldReturn` [("test", ["t >= 4"])] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4")])] it "should find redundant guard condition (product application)" $ do let code = [SI.i|module Main where @@ -130,7 +130,7 @@ test t | t < 4 = 0 | t >= product [2, 2] && t < 9 = 1 |] - detect code `shouldReturn` [("test", ["t >= product [2, 2]"])] + 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 @@ -138,7 +138,7 @@ test t | t `div` 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", ["t /= 8"])] + detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] it "should find redundant guard condition (prefix div application" $ do let code = [SI.i|module Main where @@ -146,7 +146,7 @@ test t | div t 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", ["t /= 8"])] + detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] it "should find redundant guard condition ( / application)" $ do let code = [SI.i|module Main where @@ -154,7 +154,7 @@ test t | t / 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", ["t /= 8"])] + detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] it "should find redundant guard condition on list" $ do let code = [SI.i|module Main where @@ -162,7 +162,7 @@ test xs | null xs = 0 | length xs >= 1 = 1 |] - detect code `shouldReturn` [("test", ["length xs >= 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 @@ -170,7 +170,7 @@ test xs | null xs = 0 | not (null xs) = 1 |] - detect code `shouldReturn` [("test", ["not (null xs)"])] + detect code `shouldReturn` [("test", [(Redundant, "not (null xs)")])] it "should ignore generators" $ do let code = [SI.i|module Main where @@ -210,7 +210,7 @@ test t | t < 4 = 0 | t - 2 >= 2 && t < 9 = 1 |] - detect code `shouldReturn` [("test", ["t - 2 >= 2"])] + 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 @@ -218,7 +218,7 @@ test t | t < 4 = 0 | 4 <= t && t < 9 = 1 |] - detect code `shouldReturn` [("test", ["4 <= t"])] + detect code `shouldReturn` [("test", [(Redundant, "4 <= t")])] it "should find redundant guard condition (two variables)" $ do let code = [SI.i|module Main where @@ -226,7 +226,7 @@ test t s | t < 4 || t == s = 0 | 4 <= t && s /= t && t < 9 = 1 |] - detect code `shouldReturn` [("test", ["4 <= t", "s /= t"])] + 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 @@ -235,7 +235,7 @@ test t | t >= 4 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", ["t < 9"])] + 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 @@ -243,7 +243,7 @@ test t | t > 3 = 0 | t <= 3 && t < 5 = 1 |] - detect code `shouldReturn` [("test", ["t <= 3", "t < 5"])] + detect code `shouldReturn` [("test", [(Redundant, "t <= 3"), (Redundant, "t < 5")])] it "should find redundant guard conditions" $ do let code = [SI.i|module Main where @@ -252,7 +252,7 @@ test t | t >= 4 = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", ["t >= 4", "t >= 9"])] + 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 @@ -261,7 +261,7 @@ test t | otherwise = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", ["t >= 9"])] + detect code `shouldReturn` [("test", [(Unreachable, "t >= 9")])] it "should mark a repeated otherwise redundant" $ do let code = [SI.i|module Main where @@ -270,7 +270,7 @@ test t | otherwise = 1 | otherwise = 2 |] - detect code `shouldReturn` [("test", ["otherwise"])] + detect code `shouldReturn` [("test", [(Unreachable, "otherwise")])] it "should also mark otherwise as redundant when previous conditions are exhaustive" $ do let code = [SI.i|module Main where @@ -279,7 +279,7 @@ test t | t >= 4 = 1 | otherwise = 2 |] - detect code `shouldReturn` [("test", ["t >= 4", "otherwise"])] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "otherwise")])] it "should treat True like otherwise" $ do let code = [SI.i|module Main where @@ -296,7 +296,7 @@ test t | t >= 4 = 1 | True = 2 |] - detect code `shouldReturn` [("test", ["t >= 4", "True"])] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "True")])] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where @@ -304,7 +304,7 @@ test t | t < 4 = 0 | t >= 4 || t >= 5 = 1 |] - detect code `shouldReturn` [("test", ["t >= 4 || t >= 5"])] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4 || t >= 5")])] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where @@ -312,7 +312,7 @@ test t | t < 4 = 0 | t >= 3 || t >= 5 = 1 |] - detect code `shouldReturn` [("test", ["t >= 3 || t >= 5"])] + 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 @@ -321,7 +321,7 @@ test t | True = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", ["t >= 9"])] + detect code `shouldReturn` [("test", [(Unreachable, "t >= 9")])] it "should mark a repeated True redundant" $ do let code = [SI.i|module Main where @@ -330,7 +330,7 @@ test t | True = 1 | True = 2 |] - detect code `shouldReturn` [("test", ["True"])] + detect code `shouldReturn` [("test", [(Unreachable, "True")])] it "correctly handles skipped False guard" $ do let code = [SI.i|module Main where From 724ae7785b41d0b365b4f621a54f25a803a562e3 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:46:04 +0000 Subject: [PATCH 21/35] also differentiate whether guards are explicitly exhaustive or not --- src/Haskell/Template/Detection/Guards.hs | 67 ++++++++++--- test/Haskell/Template/Detection/GuardsSpec.hs | 95 +++++++++++-------- 2 files changed, 112 insertions(+), 50 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 3071ee9..b668a02 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -4,6 +4,7 @@ module Haskell.Template.Detection.Guards (detectRedundantGuardCondition, Reason (..)) where import Control.Monad (forM, join, liftM2, liftM3, void, (<=<), (>=>)) +import Data.Bifunctor (bimap) import Data.List (singleton) import Data.List.Extra (nubOrd) import Data.List.NonEmpty (NonEmpty) @@ -68,9 +69,13 @@ import Z3.Monad ( mkUnaryMinus, ) +-- | Reason for a condition being reported data Reason = Redundant | Unreachable deriving (Eq, Ord, Show) +-- | Shorthand for a detection result +type GuardDetectionResult a = Either [(Reason, ScopedExp a)] [(Reason, ScopedExp a)] + -- | Returns True when given expression represents truthful value isTruthfulGuard :: ScopedExp a -> Bool isTruthfulGuard (unwrapParens -> Var _ (qActName -> Just (Just "GHC.Base", "otherwise"))) = True @@ -95,13 +100,46 @@ qOpActName' :: QOp (Scoped a) -> Maybe (Maybe String, String) qOpActName' (QVarOp _ (qActName -> res)) = res qOpActName' (QConOp _ (qActName -> res)) = res --- | Returns a list of guard conditions which are redundant -checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO [(Reason, ScopedExp a)] -checkForRedundancy [] = pure [] -checkForRedundancy [_] = pure [] -checkForRedundancy (x : xs) = checking [NE.toList $ fmap snd x] (map NE.toList xs) +{- | Returns a list of redundant or unreachable guard conditions encapsulated in Either +| +| Uses the `Right` constructor when the final guard is a standalone `otherwise` or `True`; +| otherwise uses `Left`. +-} +checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO (GuardDetectionResult a) +checkForRedundancy [] = pure $ Right [] +checkForRedundancy guards@(_ : _) = do + result <- 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 $ Right $ map ((Redundant,) . fst) xList + else return $ Left [] + x : xs -> checking [NE.toList $ fmap snd x] (map NE.toList xs) + + pure $ case result of + Left findings -> Left findings + Right findings + | hasCatchAll -> Right findings + | otherwise -> Left findings where - checking _ [] = pure [] + hasCatchAll = + case NE.toList (last guards) of + [(guard, _)] -> isTruthfulGuard guard + _ -> False + checking skipped [] = do + let + knownGuards = map (sequence >=> mkAnd) skipped + known' = mkAnd =<< mapM (>>= mkNot) knownGuards + + isExhaustive <- prove $ do + known <- known' + mkIff known =<< mkFalse + + pure $ (if isExhaustive then Right else Left) [] checking skipped ([] : remaining) = checking skipped remaining checking skipped remaining = do let @@ -114,7 +152,7 @@ checkForRedundancy (x : xs) = checking [NE.toList $ fmap snd x] (map NE.toList x mkIff known =<< mkFalse if isUnreachable - then return $ map (\(e, _) -> (Unreachable, e)) allRemaining + then return $ Right $ map (\(e, _) -> (Unreachable, e)) allRemaining else do results <- forM allRemaining $ \(e, c) -> do isRedundant <- prove $ do @@ -131,18 +169,23 @@ checkForRedundancy (x : xs) = checking [NE.toList $ fmap snd x] (map NE.toList x (fmap snd (head remaining) : skipped) (map (filter ((`notElem` map fst redundant) . fst)) $ drop 1 remaining) - return $ map (\(e, _) -> (Redundant, e)) redundant ++ restResults + let prepend = (map (\(e, _) -> (Redundant, e)) redundant ++) + return $ bimap prepend prepend restResults --- | Return redundant guard conditions for each definition +{- | Returns a list of redundant or unreachable guard conditions per definition encapsulated in Either +| +| Uses the `Right` constructor when the final guard is a standalone `otherwise` or `True`; +| otherwise uses `Left`. +-} detectRedundantGuardCondition :: Module (Scoped SrcSpanInfo) - -> IO [(Name (Scoped SrcSpanInfo), [(Reason, ScopedExp SrcSpanInfo)])] + -> IO [(Name (Scoped SrcSpanInfo), GuardDetectionResult SrcSpanInfo)] detectRedundantGuardCondition mod' = flip witherM (extractFromModule mod') $ \(name, constraints) -> do redundant <- checkForRedundancy constraints case redundant of - [] -> pure Nothing - xs -> pure $ Just (name, nubOrd xs) + Right [] -> pure Nothing + xs -> pure $ Just (name, bimap nubOrd nubOrd xs) -- | Extracts all guard conditions from a definition using guards extractFromModule diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index b0bf6ed..8163d08 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -9,12 +9,13 @@ 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 :: String -> IO [(String, Either [(Reason, 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 + let pretty = map (second prettyPrint) + pure $ map (bimap prettyPrint (bimap pretty pretty)) redundant _ -> fail "failed to parse program" spec :: Spec @@ -27,7 +28,7 @@ test t | t < 0 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t >= 0")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t >= 0")])] it "should find multiple redundant guard conditions" $ do let code = [SI.i|module Main where @@ -36,7 +37,7 @@ test t | 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")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t >= 0"), (Redundant, "t >= 0"), (Redundant, "t >= 3")])] it "should not find redundant guard conditions" $ do let code = [SI.i|module Main where @@ -45,7 +46,7 @@ test t | t >= 1 && t < 3 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [] + detect code `shouldReturn` [("test", Left [])] it "should not find redundant guard conditions" $ do let code = [SI.i|module Main where @@ -54,7 +55,7 @@ test t | t >= 4 && t < 6 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [] + detect code `shouldReturn` [("test", Left [])] it "should not find redundant guard conditions (wrong scope)" $ do let code = [SI.i|module Main where @@ -63,7 +64,7 @@ test t | (let t = 99 in t >= 0) && t < 6 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [] + detect code `shouldReturn` [("test", Left [])] it "should find redundant guard condition (negated or)" $ do let code = [SI.i|module Main where @@ -71,7 +72,7 @@ test t | t < 0 || t > 0 = 0 | t == 0 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t == 0")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t == 0")])] it "should not find redundant guard conditions (otherwise)" $ do let code = [SI.i|module Main where @@ -88,7 +89,7 @@ test t | 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")])] + detect code `shouldReturn` [("test", Left [(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 @@ -97,7 +98,7 @@ test t | 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")])] + detect code `shouldReturn` [("test", Left [(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 @@ -106,7 +107,7 @@ test t | 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")])] + detect code `shouldReturn` [("test", Left [(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 @@ -114,7 +115,7 @@ test t | t < sum [1,1,2] = 0 | t >= 4 && t < 9 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t >= 4")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4")])] it "should find redundant guard condition (manual sum)" $ do let code = [SI.i|module Main where @@ -122,7 +123,7 @@ test t | t < 1 + 1 + 2 = 0 | t >= 4 && t < 9 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t >= 4")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4")])] it "should find redundant guard condition (product application)" $ do let code = [SI.i|module Main where @@ -130,7 +131,7 @@ test t | t < 4 = 0 | t >= product [2, 2] && t < 9 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t >= product [2, 2]")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t >= product [2, 2]")])] it "should find redundant guard condition (infix div application)" $ do let code = [SI.i|module Main where @@ -138,7 +139,7 @@ test t | t `div` 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t /= 8")])] it "should find redundant guard condition (prefix div application" $ do let code = [SI.i|module Main where @@ -146,7 +147,7 @@ test t | div t 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t /= 8")])] it "should find redundant guard condition ( / application)" $ do let code = [SI.i|module Main where @@ -154,7 +155,7 @@ test t | t / 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t /= 8")])] it "should find redundant guard condition on list" $ do let code = [SI.i|module Main where @@ -162,7 +163,7 @@ test xs | null xs = 0 | length xs >= 1 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "length xs >= 1")])] + detect code `shouldReturn` [("test", Left [(Redundant, "length xs >= 1")])] it "should find redundant guard condition (not application)" $ do let code = [SI.i|module Main where @@ -170,7 +171,7 @@ test xs | null xs = 0 | not (null xs) = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "not (null xs)")])] + detect code `shouldReturn` [("test", Left [(Redundant, "not (null xs)")])] it "should ignore generators" $ do let code = [SI.i|module Main where @@ -178,7 +179,7 @@ test t | 1 <- t = 0 | t /= 1 = 1 |] - detect code `shouldReturn` [] + detect code `shouldReturn` [("test", Left [])] it "shouldn't wrongly report redundant conditions (comma separated)" $ do let code = [SI.i|module Main where @@ -186,7 +187,7 @@ test t | t < 0, t < -5 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [] + detect code `shouldReturn` [("test", Left [])] it "shouldn't wrongly report redundant conditions (conjunction)" $ do let code = [SI.i|module Main where @@ -194,7 +195,7 @@ test t | t < 0 && t < -5 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [] + detect code `shouldReturn` [("test", Left [])] it "currently doesn't report redundant conditions within a single guard" $ do let code = [SI.i|module Main where @@ -202,7 +203,7 @@ test t | t < 0 = 0 | t <= 10 && t <= 20 = 1 |] - detect code `shouldReturn` [] + detect code `shouldReturn` [("test", Left [])] it "should find redundant guard condition (equation)" $ do let code = [SI.i|module Main where @@ -210,7 +211,7 @@ test t | t < 4 = 0 | t - 2 >= 2 && t < 9 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t - 2 >= 2")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t - 2 >= 2")])] it "should find redundant guard condition (switched argument order)" $ do let code = [SI.i|module Main where @@ -218,7 +219,7 @@ test t | t < 4 = 0 | 4 <= t && t < 9 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "4 <= t")])] + detect code `shouldReturn` [("test", Left [(Redundant, "4 <= t")])] it "should find redundant guard condition (two variables)" $ do let code = [SI.i|module Main where @@ -226,7 +227,7 @@ 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")])] + detect code `shouldReturn` [("test", Left [(Redundant, "4 <= t"), (Redundant, "s /= t")])] it "should find redundant guard condition (with gap)" $ do let code = [SI.i|module Main where @@ -235,7 +236,7 @@ test t | t >= 4 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", [(Redundant, "t < 9")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t < 9")])] it "should find two redundant guard conditions based on skipped condition" $ do let code = [SI.i|module Main where @@ -243,7 +244,7 @@ test t | t > 3 = 0 | t <= 3 && t < 5 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t <= 3"), (Redundant, "t < 5")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t <= 3"), (Redundant, "t < 5")])] it "should find redundant guard conditions" $ do let code = [SI.i|module Main where @@ -252,7 +253,7 @@ test t | t >= 4 = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "t >= 9")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4"), (Unreachable, "t >= 9")])] it "should mark every condition redundant after otherwise" $ do let code = [SI.i|module Main where @@ -261,7 +262,7 @@ test t | otherwise = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", [(Unreachable, "t >= 9")])] + detect code `shouldReturn` [("test", Left [(Unreachable, "t >= 9")])] it "should mark a repeated otherwise redundant" $ do let code = [SI.i|module Main where @@ -270,7 +271,7 @@ test t | otherwise = 1 | otherwise = 2 |] - detect code `shouldReturn` [("test", [(Unreachable, "otherwise")])] + detect code `shouldReturn` [("test", Right [(Unreachable, "otherwise")])] it "should also mark otherwise as redundant when previous conditions are exhaustive" $ do let code = [SI.i|module Main where @@ -279,7 +280,7 @@ test t | t >= 4 = 1 | otherwise = 2 |] - detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "otherwise")])] + detect code `shouldReturn` [("test", Right [(Redundant, "t >= 4"), (Unreachable, "otherwise")])] it "should treat True like otherwise" $ do let code = [SI.i|module Main where @@ -296,7 +297,7 @@ test t | t >= 4 = 1 | True = 2 |] - detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "True")])] + detect code `shouldReturn` [("test", Right [(Redundant, "t >= 4"), (Unreachable, "True")])] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where @@ -304,7 +305,7 @@ test t | t < 4 = 0 | t >= 4 || t >= 5 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t >= 4 || t >= 5")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4 || t >= 5")])] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where @@ -312,7 +313,7 @@ test t | t < 4 = 0 | t >= 3 || t >= 5 = 1 |] - detect code `shouldReturn` [("test", [(Redundant, "t >= 3 || t >= 5")])] + detect code `shouldReturn` [("test", Left [(Redundant, "t >= 3 || t >= 5")])] it "should mark every condition redundant after True" $ do let code = [SI.i|module Main where @@ -321,7 +322,7 @@ test t | True = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", [(Unreachable, "t >= 9")])] + detect code `shouldReturn` [("test", Left [(Unreachable, "t >= 9")])] it "should mark a repeated True redundant" $ do let code = [SI.i|module Main where @@ -330,7 +331,7 @@ test t | True = 1 | True = 2 |] - detect code `shouldReturn` [("test", [(Unreachable, "True")])] + detect code `shouldReturn` [("test", Right [(Unreachable, "True")])] it "correctly handles skipped False guard" $ do let code = [SI.i|module Main where @@ -339,4 +340,22 @@ test t | t < 1 = 1 | t < 10 = 2 |] - detect code `shouldReturn` [] + detect code `shouldReturn` [("test", Left [])] + it "should report non-exhaustive for a single guard" $ do + let code = + [SI.i|module Main where +test t | t < 0 = 0 +|] + detect code `shouldReturn` [("test", Left [])] + 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", Left [(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", Right [(Redundant, "True")])] From e4f4fbcdc3d56d289bdc7eb53cb4b94467317298 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:07:38 +0000 Subject: [PATCH 22/35] spelling config --- .github/actions/spelling/allow.txt | 1 + .github/actions/spelling/patterns.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index 60f9a13..46517f1 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -33,6 +33,7 @@ QVar Rebindable scrutinee snd +standalone thd uncurry unlines 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+ From cfa94f91c68509b34680338d87853004af011493 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:20:27 +0000 Subject: [PATCH 23/35] two more test cases --- test/Haskell/Template/Detection/GuardsSpec.hs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index 8163d08..7e23d91 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -148,6 +148,14 @@ test t | t /= 8 = 1 |] detect code `shouldReturn` [("test", Left [(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", Left [(Redundant, "t /= 9")])] it "should find redundant guard condition ( / application)" $ do let code = [SI.i|module Main where @@ -156,6 +164,14 @@ test t | t /= 8 = 1 |] detect code `shouldReturn` [("test", Left [(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` [("test", Left [])] it "should find redundant guard condition on list" $ do let code = [SI.i|module Main where From c41129afb59d986a67b132c8374775804f03819b Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:22:00 +0000 Subject: [PATCH 24/35] make div, mod, rem work on integers instead of reals --- src/Haskell/Template/Detection/Guards.hs | 27 +++++++++++++----------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index b668a02..638ee34 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -4,7 +4,7 @@ module Haskell.Template.Detection.Guards (detectRedundantGuardCondition, Reason (..)) where import Control.Monad (forM, join, liftM2, liftM3, void, (<=<), (>=>)) -import Data.Bifunctor (bimap) +import Data.Bifunctor (bimap, second) import Data.List (singleton) import Data.List.Extra (nubOrd) import Data.List.NonEmpty (NonEmpty) @@ -60,6 +60,7 @@ import Z3.Monad ( mkNot, mkNumeral, mkOr, + mkReal2Int, mkRealSort, mkRealVar, mkRem, @@ -257,19 +258,19 @@ arithAstToZ3 (unwrapParens -> expr) = -- | 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 (\a b -> mkAdd [a, b]) l r + combineMaybeArithExprs False (\a b -> mkAdd [a, b]) l r arithAppToZ3 (Just "GHC.Num") "-" [l, r] = - combineMaybeArithExprs (\a b -> mkSub [a, b]) l r + combineMaybeArithExprs False (\a b -> mkSub [a, b]) l r arithAppToZ3 (Just "GHC.Num") "*" [l, r] = - combineMaybeArithExprs (\a b -> mkMul [a, b]) l r + combineMaybeArithExprs False (\a b -> mkMul [a, b]) l r arithAppToZ3 (Just "GHC.Real") "/" [l, r] = - combineMaybeArithExprs mkDiv l r + combineMaybeArithExprs False mkDiv l r arithAppToZ3 (Just "GHC.Real") "div" [l, r] = - combineMaybeArithExprs mkDiv l r + combineMaybeArithExprs True mkDiv l r arithAppToZ3 (Just "GHC.Real") "mod" [l, r] = - combineMaybeArithExprs mkMod l r + combineMaybeArithExprs True mkMod l r arithAppToZ3 (Just "GHC.Real") "rem" [l, r] = - combineMaybeArithExprs mkRem 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 @@ -310,7 +311,7 @@ astToZ3 (unwrapParens -> expr) = case expr of 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 op l r + map (expr,) $ maybeToList $ combineMaybeArithExprs False op l r where opMap = [("<", mkLt), ("<=", mkLe), (">", mkGt), (">=", mkGe), ("==", mkEq)] op = fromJust $ lookup opName opMap @@ -319,7 +320,7 @@ appToZ3 expr (Just "GHC.Classes") "&&" [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 mkEq 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] = @@ -337,8 +338,10 @@ appToZ3 _ _ _ _ = | | Only returns `Just` when both expressions are arithmetic expressions. -} -combineMaybeArithExprs :: Show a => (AST -> AST -> Z3 AST) -> ScopedExp a -> ScopedExp a -> Maybe (Z3 AST) -combineMaybeArithExprs f l r = liftM2 (\(_, a) (_, b) -> join $ liftM2 f a b) (arithAstToZ3 l) (arithAstToZ3 r) +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 From 34f9b8981e77df55abd593c9f03609227342094f Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:01:07 +0000 Subject: [PATCH 25/35] re-model result type --- src/Haskell/Template/Detection/Guards.hs | 39 ++++---- test/Haskell/Template/Detection/GuardsSpec.hs | 91 ++++++++++--------- 2 files changed, 64 insertions(+), 66 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 638ee34..3950d82 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -4,7 +4,7 @@ module Haskell.Template.Detection.Guards (detectRedundantGuardCondition, Reason (..)) where import Control.Monad (forM, join, liftM2, liftM3, void, (<=<), (>=>)) -import Data.Bifunctor (bimap, second) +import Data.Bifunctor (first, second) import Data.List (singleton) import Data.List.Extra (nubOrd) import Data.List.NonEmpty (NonEmpty) @@ -75,7 +75,7 @@ data Reason = Redundant | Unreachable deriving (Eq, Ord, Show) -- | Shorthand for a detection result -type GuardDetectionResult a = Either [(Reason, ScopedExp a)] [(Reason, ScopedExp a)] +type GuardDetectionResult a = (Bool, [(Reason, ScopedExp a)]) -- | Returns True when given expression represents truthful value isTruthfulGuard :: ScopedExp a -> Bool @@ -101,13 +101,13 @@ qOpActName' :: QOp (Scoped a) -> Maybe (Maybe String, String) qOpActName' (QVarOp _ (qActName -> res)) = res qOpActName' (QConOp _ (qActName -> res)) = res -{- | Returns a list of redundant or unreachable guard conditions encapsulated in Either +{- | Returns a list of redundant or unreachable guard conditions together with an exhaustion status | -| Uses the `Right` constructor when the final guard is a standalone `otherwise` or `True`; -| otherwise uses `Left`. +| Uses `True` when the final guard is a standalone `otherwise` or `True`; +| otherwise uses `False`. -} checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO (GuardDetectionResult a) -checkForRedundancy [] = pure $ Right [] +checkForRedundancy [] = pure (True, []) checkForRedundancy guards@(_ : _) = do result <- case guards of [x] -> do @@ -117,15 +117,11 @@ checkForRedundancy guards@(_ : _) = do mkIff inQuestion =<< mkTrue if isTrue - then return $ Right $ map ((Redundant,) . fst) xList - else return $ Left [] + then return (True, map ((Redundant,) . fst) xList) + else return (False, []) x : xs -> checking [NE.toList $ fmap snd x] (map NE.toList xs) - pure $ case result of - Left findings -> Left findings - Right findings - | hasCatchAll -> Right findings - | otherwise -> Left findings + return $ first (&& hasCatchAll) result where hasCatchAll = case NE.toList (last guards) of @@ -140,7 +136,7 @@ checkForRedundancy guards@(_ : _) = do known <- known' mkIff known =<< mkFalse - pure $ (if isExhaustive then Right else Left) [] + pure (isExhaustive, []) checking skipped ([] : remaining) = checking skipped remaining checking skipped remaining = do let @@ -153,7 +149,7 @@ checkForRedundancy guards@(_ : _) = do mkIff known =<< mkFalse if isUnreachable - then return $ Right $ map (\(e, _) -> (Unreachable, e)) allRemaining + then return (True, map (\(e, _) -> (Unreachable, e)) allRemaining) else do results <- forM allRemaining $ \(e, c) -> do isRedundant <- prove $ do @@ -170,13 +166,12 @@ checkForRedundancy guards@(_ : _) = do (fmap snd (head remaining) : skipped) (map (filter ((`notElem` map fst redundant) . fst)) $ drop 1 remaining) - let prepend = (map (\(e, _) -> (Redundant, e)) redundant ++) - return $ bimap prepend prepend restResults + return $ second (map (\(e, _) -> (Redundant, e)) redundant ++) restResults -{- | Returns a list of redundant or unreachable guard conditions per definition encapsulated in Either +{- | Returns a list of redundant or unreachable guard conditions per definition together with an exhaustion status | -| Uses the `Right` constructor when the final guard is a standalone `otherwise` or `True`; -| otherwise uses `Left`. +| Uses `True` when the final guard is a standalone `otherwise` or `True`; +| otherwise uses `False`. -} detectRedundantGuardCondition :: Module (Scoped SrcSpanInfo) @@ -185,8 +180,8 @@ detectRedundantGuardCondition mod' = flip witherM (extractFromModule mod') $ \(name, constraints) -> do redundant <- checkForRedundancy constraints case redundant of - Right [] -> pure Nothing - xs -> pure $ Just (name, bimap nubOrd nubOrd xs) + (True, []) -> pure Nothing + x -> pure $ Just (name, second nubOrd x) -- | Extracts all guard conditions from a definition using guards extractFromModule diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index 7e23d91..d3c00f7 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -9,13 +9,12 @@ import Language.Haskell.Exts (ParseResult (..), parse, prettyPrint) import Language.Haskell.Names (annotate, loadBase) import Test.Hspec (Spec, describe, it, shouldReturn) -detect :: String -> IO [(String, Either [(Reason, String)] [(Reason, String)])] +detect :: String -> IO [(String, (Bool, [(Reason, String)]))] detect code = case parse code of ParseOk mod' -> do baseEnv <- loadBase redundant <- detectRedundantGuardCondition $ annotate baseEnv mod' - let pretty = map (second prettyPrint) - pure $ map (bimap prettyPrint (bimap pretty pretty)) redundant + pure $ map (bimap prettyPrint (second (map (second prettyPrint)))) redundant _ -> fail "failed to parse program" spec :: Spec @@ -28,7 +27,7 @@ test t | t < 0 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 0")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 0")]))] it "should find multiple redundant guard conditions" $ do let code = [SI.i|module Main where @@ -37,7 +36,8 @@ test t | t >= 0 && t < 3 = 1 | t >= 0 && t >= 3 && t < 9 = 2 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 0"), (Redundant, "t >= 0"), (Redundant, "t >= 3")])] + detect code + `shouldReturn` [("test", (False, [(Redundant, "t >= 0"), (Redundant, "t >= 0"), (Redundant, "t >= 3")]))] it "should not find redundant guard conditions" $ do let code = [SI.i|module Main where @@ -46,7 +46,7 @@ test t | t >= 1 && t < 3 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (False, []))] it "should not find redundant guard conditions" $ do let code = [SI.i|module Main where @@ -55,7 +55,7 @@ test t | t >= 4 && t < 6 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (False, []))] it "should not find redundant guard conditions (wrong scope)" $ do let code = [SI.i|module Main where @@ -64,7 +64,7 @@ test t | (let t = 99 in t >= 0) && t < 6 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (False, []))] it "should find redundant guard condition (negated or)" $ do let code = [SI.i|module Main where @@ -72,7 +72,7 @@ test t | t < 0 || t > 0 = 0 | t == 0 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t == 0")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t == 0")]))] it "should not find redundant guard conditions (otherwise)" $ do let code = [SI.i|module Main where @@ -89,7 +89,8 @@ test t | t >= 4 && t < 9 = 1 | t >= 4 && (t >= 9 && t < 20) = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4"), (Redundant, "t >= 4"), (Redundant, "t >= 9")])] + detect code + `shouldReturn` [("test", (False, [(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 @@ -98,7 +99,8 @@ test t | t >= 4 && t < 9 = 1 | and [t >= 4, t >= 9, t < 20] = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4"), (Redundant, "t >= 4"), (Redundant, "t >= 9")])] + detect code + `shouldReturn` [("test", (False, [(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 @@ -107,7 +109,8 @@ test t | t >= 4 && t < 9 = 1 | t >= 4, t >= 9, t < 20 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4"), (Redundant, "t >= 4"), (Redundant, "t >= 9")])] + detect code + `shouldReturn` [("test", (False, [(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 @@ -115,7 +118,7 @@ test t | t < sum [1,1,2] = 0 | t >= 4 && t < 9 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 4")]))] it "should find redundant guard condition (manual sum)" $ do let code = [SI.i|module Main where @@ -123,7 +126,7 @@ test t | t < 1 + 1 + 2 = 0 | t >= 4 && t < 9 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 4")]))] it "should find redundant guard condition (product application)" $ do let code = [SI.i|module Main where @@ -131,7 +134,7 @@ test t | t < 4 = 0 | t >= product [2, 2] && t < 9 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= product [2, 2]")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t >= product [2, 2]")]))] it "should find redundant guard condition (infix div application)" $ do let code = [SI.i|module Main where @@ -139,7 +142,7 @@ test t | t `div` 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t /= 8")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t /= 8")]))] it "should find redundant guard condition (prefix div application" $ do let code = [SI.i|module Main where @@ -147,7 +150,7 @@ test t | div t 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t /= 8")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t /= 8")]))] it "should find redundant guard condition (prefix div application" $ do let code = [SI.i|module Main where @@ -155,7 +158,7 @@ test t | div t 2 == 4 = 0 | t /= 9 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t /= 9")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t /= 9")]))] it "should find redundant guard condition ( / application)" $ do let code = [SI.i|module Main where @@ -163,7 +166,7 @@ test t | t / 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t /= 8")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t /= 8")]))] it "shouldn't find redundant guard condition ( / application)" $ do let code = [SI.i|module Main where @@ -171,7 +174,7 @@ test t | t / 2 == 4 = 0 | t /= 9 = 1 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (False, []))] it "should find redundant guard condition on list" $ do let code = [SI.i|module Main where @@ -179,7 +182,7 @@ test xs | null xs = 0 | length xs >= 1 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "length xs >= 1")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "length xs >= 1")]))] it "should find redundant guard condition (not application)" $ do let code = [SI.i|module Main where @@ -187,7 +190,7 @@ test xs | null xs = 0 | not (null xs) = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "not (null xs)")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "not (null xs)")]))] it "should ignore generators" $ do let code = [SI.i|module Main where @@ -195,7 +198,7 @@ test t | 1 <- t = 0 | t /= 1 = 1 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (False, []))] it "shouldn't wrongly report redundant conditions (comma separated)" $ do let code = [SI.i|module Main where @@ -203,7 +206,7 @@ test t | t < 0, t < -5 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (False, []))] it "shouldn't wrongly report redundant conditions (conjunction)" $ do let code = [SI.i|module Main where @@ -211,7 +214,7 @@ test t | t < 0 && t < -5 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (False, []))] it "currently doesn't report redundant conditions within a single guard" $ do let code = [SI.i|module Main where @@ -219,7 +222,7 @@ test t | t < 0 = 0 | t <= 10 && t <= 20 = 1 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (False, []))] it "should find redundant guard condition (equation)" $ do let code = [SI.i|module Main where @@ -227,7 +230,7 @@ test t | t < 4 = 0 | t - 2 >= 2 && t < 9 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t - 2 >= 2")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t - 2 >= 2")]))] it "should find redundant guard condition (switched argument order)" $ do let code = [SI.i|module Main where @@ -235,7 +238,7 @@ test t | t < 4 = 0 | 4 <= t && t < 9 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "4 <= t")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "4 <= t")]))] it "should find redundant guard condition (two variables)" $ do let code = [SI.i|module Main where @@ -243,7 +246,7 @@ test t s | t < 4 || t == s = 0 | 4 <= t && s /= t && t < 9 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "4 <= t"), (Redundant, "s /= t")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "4 <= t"), (Redundant, "s /= t")]))] it "should find redundant guard condition (with gap)" $ do let code = [SI.i|module Main where @@ -252,7 +255,7 @@ test t | t >= 4 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t < 9")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t < 9")]))] it "should find two redundant guard conditions based on skipped condition" $ do let code = [SI.i|module Main where @@ -260,7 +263,7 @@ test t | t > 3 = 0 | t <= 3 && t < 5 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t <= 3"), (Redundant, "t < 5")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t <= 3"), (Redundant, "t < 5")]))] it "should find redundant guard conditions" $ do let code = [SI.i|module Main where @@ -269,7 +272,7 @@ test t | t >= 4 = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4"), (Unreachable, "t >= 9")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 4"), (Unreachable, "t >= 9")]))] it "should mark every condition redundant after otherwise" $ do let code = [SI.i|module Main where @@ -278,7 +281,7 @@ test t | otherwise = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", Left [(Unreachable, "t >= 9")])] + detect code `shouldReturn` [("test", (False, [(Unreachable, "t >= 9")]))] it "should mark a repeated otherwise redundant" $ do let code = [SI.i|module Main where @@ -287,7 +290,7 @@ test t | otherwise = 1 | otherwise = 2 |] - detect code `shouldReturn` [("test", Right [(Unreachable, "otherwise")])] + detect code `shouldReturn` [("test", (True, [(Unreachable, "otherwise")]))] it "should also mark otherwise as redundant when previous conditions are exhaustive" $ do let code = [SI.i|module Main where @@ -296,7 +299,7 @@ test t | t >= 4 = 1 | otherwise = 2 |] - detect code `shouldReturn` [("test", Right [(Redundant, "t >= 4"), (Unreachable, "otherwise")])] + detect code `shouldReturn` [("test", (True, [(Redundant, "t >= 4"), (Unreachable, "otherwise")]))] it "should treat True like otherwise" $ do let code = [SI.i|module Main where @@ -313,7 +316,7 @@ test t | t >= 4 = 1 | True = 2 |] - detect code `shouldReturn` [("test", Right [(Redundant, "t >= 4"), (Unreachable, "True")])] + detect code `shouldReturn` [("test", (True, [(Redundant, "t >= 4"), (Unreachable, "True")]))] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where @@ -321,7 +324,7 @@ test t | t < 4 = 0 | t >= 4 || t >= 5 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 4 || t >= 5")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 4 || t >= 5")]))] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where @@ -329,7 +332,7 @@ test t | t < 4 = 0 | t >= 3 || t >= 5 = 1 |] - detect code `shouldReturn` [("test", Left [(Redundant, "t >= 3 || t >= 5")])] + detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 3 || t >= 5")]))] it "should mark every condition redundant after True" $ do let code = [SI.i|module Main where @@ -338,7 +341,7 @@ test t | True = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", Left [(Unreachable, "t >= 9")])] + detect code `shouldReturn` [("test", (False, [(Unreachable, "t >= 9")]))] it "should mark a repeated True redundant" $ do let code = [SI.i|module Main where @@ -347,7 +350,7 @@ test t | True = 1 | True = 2 |] - detect code `shouldReturn` [("test", Right [(Unreachable, "True")])] + detect code `shouldReturn` [("test", (True, [(Unreachable, "True")]))] it "correctly handles skipped False guard" $ do let code = [SI.i|module Main where @@ -356,22 +359,22 @@ test t | t < 1 = 1 | t < 10 = 2 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (False, []))] it "should report non-exhaustive for a single guard" $ do let code = [SI.i|module Main where test t | t < 0 = 0 |] - detect code `shouldReturn` [("test", Left [])] + detect code `shouldReturn` [("test", (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", Left [(Redundant, "t < 0 || t >= 0")])] + detect code `shouldReturn` [("test", (False, [(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", Right [(Redundant, "True")])] + detect code `shouldReturn` [("test", (True, [(Redundant, "True")]))] From 96cbccef984af54fe22ca0ac6e96619a86d7f303 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:55:18 +0000 Subject: [PATCH 26/35] also mark guards unreachable which are equivalent to false --- src/Haskell/Template/Detection/Guards.hs | 53 +++++++++++-------- test/Haskell/Template/Detection/GuardsSpec.hs | 29 +++++++++- 2 files changed, 58 insertions(+), 24 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 3950d82..d7ccee7 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -3,7 +3,7 @@ module Haskell.Template.Detection.Guards (detectRedundantGuardCondition, Reason (..)) where -import Control.Monad (forM, join, liftM2, liftM3, void, (<=<), (>=>)) +import Control.Monad (join, liftM2, liftM3, void, (<=<), (>=>)) import Data.Bifunctor (first, second) import Data.List (singleton) import Data.List.Extra (nubOrd) @@ -119,7 +119,7 @@ checkForRedundancy guards@(_ : _) = do if isTrue then return (True, map ((Redundant,) . fst) xList) else return (False, []) - x : xs -> checking [NE.toList $ fmap snd x] (map NE.toList xs) + xs -> checking [] (map NE.toList xs) return $ first (&& hasCatchAll) result where @@ -138,35 +138,42 @@ checkForRedundancy guards@(_ : _) = do pure (isExhaustive, []) checking skipped ([] : remaining) = checking skipped remaining - checking skipped remaining = do + checking skipped (r : remaining) = do let - allRemaining = concat remaining knownGuards = map (sequence >=> mkAnd) skipped known' = mkAnd =<< mapM (>>= mkNot) knownGuards - isUnreachable <- prove $ do + alreadyExhaustive <- prove $ do known <- known' mkIff known =<< mkFalse - if isUnreachable - then return (True, map (\(e, _) -> (Unreachable, e)) allRemaining) + if alreadyExhaustive + then pure (True, map ((Unreachable,) . fst) $ r ++ concat remaining) else do - results <- forM allRemaining $ \(e, c) -> do - isRedundant <- prove $ do - known <- known' - inQuestion <- c - - mkImplies known inQuestion - return ((e, c), isRedundant) - - let redundant = map fst $ filter (\((e, _), r) -> r && not (isTruthfulGuard e)) results - - restResults <- - checking - (fmap snd (head remaining) : skipped) - (map (filter ((`notElem` map fst redundant) . fst)) $ drop 1 remaining) - - return $ second (map (\(e, _) -> (Redundant, e)) redundant ++) restResults + isFalsy <- prove $ do + guard <- mkAnd =<< mapM snd r + mkIff guard =<< mkFalse + + if isFalsy + then pure (True, map ((Unreachable,) . fst) r) + else do + results <- 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 + (fmap snd r : skipped) + (map (filter ((`notElem` map (fst . snd) results) . fst)) remaining) + + return $ (map (second fst) results ++) <$> restResults {- | Returns a list of redundant or unreachable guard conditions per definition together with an exhaustion status | diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index d3c00f7..c9fe2d5 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -359,7 +359,7 @@ test t | t < 1 = 1 | t < 10 = 2 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [("test", (False, [(Unreachable, "False")]))] it "should report non-exhaustive for a single guard" $ do let code = [SI.i|module Main where @@ -378,3 +378,30 @@ test t | t < 0 || t >= 0 = 0 test t | True = 0 |] detect code `shouldReturn` [("test", (True, [(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", (False, [(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", (False, [(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", (False, [(Unreachable, "t < 10"), (Unreachable, "t < 20")]))] From e9a9fa6f8731100ba000414887db4ae8dceba2d9 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:47:40 +0000 Subject: [PATCH 27/35] don't track exhaustiveness in result type --- src/Haskell/Template/Detection/Guards.hs | 56 +++-------- test/Haskell/Template/Detection/GuardsSpec.hs | 92 +++++++++---------- 2 files changed, 61 insertions(+), 87 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index d7ccee7..9eda058 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -4,7 +4,7 @@ module Haskell.Template.Detection.Guards (detectRedundantGuardCondition, Reason (..)) where import Control.Monad (join, liftM2, liftM3, void, (<=<), (>=>)) -import Data.Bifunctor (first, second) +import Data.Bifunctor (second) import Data.List (singleton) import Data.List.Extra (nubOrd) import Data.List.NonEmpty (NonEmpty) @@ -74,9 +74,6 @@ import Z3.Monad ( data Reason = Redundant | Unreachable deriving (Eq, Ord, Show) --- | Shorthand for a detection result -type GuardDetectionResult a = (Bool, [(Reason, ScopedExp a)]) - -- | Returns True when given expression represents truthful value isTruthfulGuard :: ScopedExp a -> Bool isTruthfulGuard (unwrapParens -> Var _ (qActName -> Just (Just "GHC.Base", "otherwise"))) = True @@ -101,15 +98,11 @@ qOpActName' :: QOp (Scoped a) -> Maybe (Maybe String, String) qOpActName' (QVarOp _ (qActName -> res)) = res qOpActName' (QConOp _ (qActName -> res)) = res -{- | Returns a list of redundant or unreachable guard conditions together with an exhaustion status -| -| Uses `True` when the final guard is a standalone `otherwise` or `True`; -| otherwise uses `False`. --} -checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO (GuardDetectionResult a) -checkForRedundancy [] = pure (True, []) +-- | 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 - result <- case guards of + case guards of [x] -> do let xList = NE.toList x isTrue <- prove $ do @@ -117,26 +110,11 @@ checkForRedundancy guards@(_ : _) = do mkIff inQuestion =<< mkTrue if isTrue - then return (True, map ((Redundant,) . fst) xList) - else return (False, []) + then return $ map ((Redundant,) . fst) xList + else return [] xs -> checking [] (map NE.toList xs) - - return $ first (&& hasCatchAll) result where - hasCatchAll = - case NE.toList (last guards) of - [(guard, _)] -> isTruthfulGuard guard - _ -> False - checking skipped [] = do - let - knownGuards = map (sequence >=> mkAnd) skipped - known' = mkAnd =<< mapM (>>= mkNot) knownGuards - - isExhaustive <- prove $ do - known <- known' - mkIff known =<< mkFalse - - pure (isExhaustive, []) + checking _ [] = pure [] checking skipped ([] : remaining) = checking skipped remaining checking skipped (r : remaining) = do let @@ -148,14 +126,14 @@ checkForRedundancy guards@(_ : _) = do mkIff known =<< mkFalse if alreadyExhaustive - then pure (True, map ((Unreachable,) . fst) $ r ++ concat remaining) + then pure $ map ((Unreachable,) . fst) $ r ++ concat remaining else do isFalsy <- prove $ do guard <- mkAnd =<< mapM snd r mkIff guard =<< mkFalse if isFalsy - then pure (True, map ((Unreachable,) . fst) r) + then pure $ map ((Unreachable,) . fst) r else do results <- flip witherM r $ \(e, c) -> do isRedundant <- prove $ do @@ -173,22 +151,18 @@ checkForRedundancy guards@(_ : _) = do (fmap snd r : skipped) (map (filter ((`notElem` map (fst . snd) results) . fst)) remaining) - return $ (map (second fst) results ++) <$> restResults + return $ map (second fst) results ++ restResults -{- | Returns a list of redundant or unreachable guard conditions per definition together with an exhaustion status -| -| Uses `True` when the final guard is a standalone `otherwise` or `True`; -| otherwise uses `False`. --} +-- | Returns a list of redundant or unreachable guard conditions per definition detectRedundantGuardCondition :: Module (Scoped SrcSpanInfo) - -> IO [(Name (Scoped SrcSpanInfo), GuardDetectionResult SrcSpanInfo)] + -> IO [(Name (Scoped SrcSpanInfo), [(Reason, ScopedExp SrcSpanInfo)])] detectRedundantGuardCondition mod' = flip witherM (extractFromModule mod') $ \(name, constraints) -> do redundant <- checkForRedundancy constraints case redundant of - (True, []) -> pure Nothing - x -> pure $ Just (name, second nubOrd x) + [] -> pure Nothing + xs -> pure $ Just (name, nubOrd xs) -- | Extracts all guard conditions from a definition using guards extractFromModule diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index c9fe2d5..11e2af3 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -9,12 +9,12 @@ import Language.Haskell.Exts (ParseResult (..), parse, prettyPrint) import Language.Haskell.Names (annotate, loadBase) import Test.Hspec (Spec, describe, it, shouldReturn) -detect :: String -> IO [(String, (Bool, [(Reason, String)]))] +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 (second (map (second prettyPrint)))) redundant + pure $ map (bimap prettyPrint (map (second prettyPrint))) redundant _ -> fail "failed to parse program" spec :: Spec @@ -27,7 +27,7 @@ test t | t < 0 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 0")]))] + detect code `shouldReturn` [("test", [(Redundant, "t >= 0")])] it "should find multiple redundant guard conditions" $ do let code = [SI.i|module Main where @@ -37,7 +37,7 @@ test t | t >= 0 && t >= 3 && t < 9 = 2 |] detect code - `shouldReturn` [("test", (False, [(Redundant, "t >= 0"), (Redundant, "t >= 0"), (Redundant, "t >= 3")]))] + `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 @@ -46,7 +46,7 @@ test t | t >= 1 && t < 3 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [] it "should not find redundant guard conditions" $ do let code = [SI.i|module Main where @@ -55,7 +55,7 @@ test t | t >= 4 && t < 6 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [] it "should not find redundant guard conditions (wrong scope)" $ do let code = [SI.i|module Main where @@ -64,7 +64,7 @@ test t | (let t = 99 in t >= 0) && t < 6 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [] it "should find redundant guard condition (negated or)" $ do let code = [SI.i|module Main where @@ -72,7 +72,7 @@ test t | t < 0 || t > 0 = 0 | t == 0 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t == 0")]))] + detect code `shouldReturn` [("test", [(Redundant, "t == 0")])] it "should not find redundant guard conditions (otherwise)" $ do let code = [SI.i|module Main where @@ -90,7 +90,7 @@ test t | t >= 4 && (t >= 9 && t < 20) = 1 |] detect code - `shouldReturn` [("test", (False, [(Redundant, "t >= 4"), (Redundant, "t >= 4"), (Redundant, "t >= 9")]))] + `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 @@ -100,7 +100,7 @@ test t | and [t >= 4, t >= 9, t < 20] = 1 |] detect code - `shouldReturn` [("test", (False, [(Redundant, "t >= 4"), (Redundant, "t >= 4"), (Redundant, "t >= 9")]))] + `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 @@ -110,7 +110,7 @@ test t | t >= 4, t >= 9, t < 20 = 1 |] detect code - `shouldReturn` [("test", (False, [(Redundant, "t >= 4"), (Redundant, "t >= 4"), (Redundant, "t >= 9")]))] + `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 @@ -118,7 +118,7 @@ test t | t < sum [1,1,2] = 0 | t >= 4 && t < 9 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 4")]))] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4")])] it "should find redundant guard condition (manual sum)" $ do let code = [SI.i|module Main where @@ -126,7 +126,7 @@ test t | t < 1 + 1 + 2 = 0 | t >= 4 && t < 9 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 4")]))] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4")])] it "should find redundant guard condition (product application)" $ do let code = [SI.i|module Main where @@ -134,7 +134,7 @@ test t | t < 4 = 0 | t >= product [2, 2] && t < 9 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t >= product [2, 2]")]))] + 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 @@ -142,7 +142,7 @@ test t | t `div` 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t /= 8")]))] + detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] it "should find redundant guard condition (prefix div application" $ do let code = [SI.i|module Main where @@ -150,7 +150,7 @@ test t | div t 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t /= 8")]))] + detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] it "should find redundant guard condition (prefix div application" $ do let code = [SI.i|module Main where @@ -158,7 +158,7 @@ test t | div t 2 == 4 = 0 | t /= 9 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t /= 9")]))] + detect code `shouldReturn` [("test", [(Redundant, "t /= 9")])] it "should find redundant guard condition ( / application)" $ do let code = [SI.i|module Main where @@ -166,7 +166,7 @@ test t | t / 2 == 4 = 0 | t /= 8 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t /= 8")]))] + detect code `shouldReturn` [("test", [(Redundant, "t /= 8")])] it "shouldn't find redundant guard condition ( / application)" $ do let code = [SI.i|module Main where @@ -174,7 +174,7 @@ test t | t / 2 == 4 = 0 | t /= 9 = 1 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [] it "should find redundant guard condition on list" $ do let code = [SI.i|module Main where @@ -182,7 +182,7 @@ test xs | null xs = 0 | length xs >= 1 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "length xs >= 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 @@ -190,7 +190,7 @@ test xs | null xs = 0 | not (null xs) = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "not (null xs)")]))] + detect code `shouldReturn` [("test", [(Redundant, "not (null xs)")])] it "should ignore generators" $ do let code = [SI.i|module Main where @@ -198,7 +198,7 @@ test t | 1 <- t = 0 | t /= 1 = 1 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [] it "shouldn't wrongly report redundant conditions (comma separated)" $ do let code = [SI.i|module Main where @@ -206,7 +206,7 @@ test t | t < 0, t < -5 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [] it "shouldn't wrongly report redundant conditions (conjunction)" $ do let code = [SI.i|module Main where @@ -214,7 +214,7 @@ test t | t < 0 && t < -5 = 0 | t >= 0 = 1 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [] it "currently doesn't report redundant conditions within a single guard" $ do let code = [SI.i|module Main where @@ -222,7 +222,7 @@ test t | t < 0 = 0 | t <= 10 && t <= 20 = 1 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [] it "should find redundant guard condition (equation)" $ do let code = [SI.i|module Main where @@ -230,7 +230,7 @@ test t | t < 4 = 0 | t - 2 >= 2 && t < 9 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t - 2 >= 2")]))] + 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 @@ -238,7 +238,7 @@ test t | t < 4 = 0 | 4 <= t && t < 9 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "4 <= t")]))] + detect code `shouldReturn` [("test", [(Redundant, "4 <= t")])] it "should find redundant guard condition (two variables)" $ do let code = [SI.i|module Main where @@ -246,7 +246,7 @@ test t s | t < 4 || t == s = 0 | 4 <= t && s /= t && t < 9 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "4 <= t"), (Redundant, "s /= t")]))] + 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 @@ -255,7 +255,7 @@ test t | t >= 4 = 1 | t < 9 = 2 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t < 9")]))] + 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 @@ -263,7 +263,7 @@ test t | t > 3 = 0 | t <= 3 && t < 5 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t <= 3"), (Redundant, "t < 5")]))] + detect code `shouldReturn` [("test", [(Redundant, "t <= 3"), (Redundant, "t < 5")])] it "should find redundant guard conditions" $ do let code = [SI.i|module Main where @@ -272,7 +272,7 @@ test t | t >= 4 = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 4"), (Unreachable, "t >= 9")]))] + 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 @@ -281,7 +281,7 @@ test t | otherwise = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", (False, [(Unreachable, "t >= 9")]))] + detect code `shouldReturn` [("test", [(Unreachable, "t >= 9")])] it "should mark a repeated otherwise redundant" $ do let code = [SI.i|module Main where @@ -290,7 +290,7 @@ test t | otherwise = 1 | otherwise = 2 |] - detect code `shouldReturn` [("test", (True, [(Unreachable, "otherwise")]))] + detect code `shouldReturn` [("test", [(Unreachable, "otherwise")])] it "should also mark otherwise as redundant when previous conditions are exhaustive" $ do let code = [SI.i|module Main where @@ -299,7 +299,7 @@ test t | t >= 4 = 1 | otherwise = 2 |] - detect code `shouldReturn` [("test", (True, [(Redundant, "t >= 4"), (Unreachable, "otherwise")]))] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "otherwise")])] it "should treat True like otherwise" $ do let code = [SI.i|module Main where @@ -316,7 +316,7 @@ test t | t >= 4 = 1 | True = 2 |] - detect code `shouldReturn` [("test", (True, [(Redundant, "t >= 4"), (Unreachable, "True")]))] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4"), (Unreachable, "True")])] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where @@ -324,7 +324,7 @@ test t | t < 4 = 0 | t >= 4 || t >= 5 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 4 || t >= 5")]))] + detect code `shouldReturn` [("test", [(Redundant, "t >= 4 || t >= 5")])] it "should find redundant disjunction in guard" $ do let code = [SI.i|module Main where @@ -332,7 +332,7 @@ test t | t < 4 = 0 | t >= 3 || t >= 5 = 1 |] - detect code `shouldReturn` [("test", (False, [(Redundant, "t >= 3 || t >= 5")]))] + 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 @@ -341,7 +341,7 @@ test t | True = 1 | t >= 9 = 2 |] - detect code `shouldReturn` [("test", (False, [(Unreachable, "t >= 9")]))] + detect code `shouldReturn` [("test", [(Unreachable, "t >= 9")])] it "should mark a repeated True redundant" $ do let code = [SI.i|module Main where @@ -350,7 +350,7 @@ test t | True = 1 | True = 2 |] - detect code `shouldReturn` [("test", (True, [(Unreachable, "True")]))] + detect code `shouldReturn` [("test", [(Unreachable, "True")])] it "correctly handles skipped False guard" $ do let code = [SI.i|module Main where @@ -359,25 +359,25 @@ test t | t < 1 = 1 | t < 10 = 2 |] - detect code `shouldReturn` [("test", (False, [(Unreachable, "False")]))] + detect code `shouldReturn` [("test", [(Unreachable, "False")])] it "should report non-exhaustive for a single guard" $ do let code = [SI.i|module Main where test t | t < 0 = 0 |] - detect code `shouldReturn` [("test", (False, []))] + detect code `shouldReturn` [] 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", (False, [(Redundant, "t < 0 || t >= 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", (True, [(Redundant, "True")]))] + detect code `shouldReturn` [("test", [(Redundant, "True")])] it "should report unreachable guard between other guards" $ do let code = [SI.i|module Main where @@ -386,7 +386,7 @@ test t | False = 1 | t < 10 = 2 |] - detect code `shouldReturn` [("test", (False, [(Unreachable, "False")]))] + detect code `shouldReturn` [("test", [(Unreachable, "False")])] it "should report unreachable guard (non-trivial)" $ do let code = [SI.i|module Main where @@ -395,7 +395,7 @@ test t | t < 10 = 2 |] -- this result is weird because the whole conjunction is unreachable and not the two arguments - detect code `shouldReturn` [("test", (False, [(Unreachable, "t < 0"), (Unreachable, "t >= 0")]))] + 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 @@ -404,4 +404,4 @@ test t | t < 10 = 2 | t < 20 = 3 |] - detect code `shouldReturn` [("test", (False, [(Unreachable, "t < 10"), (Unreachable, "t < 20")]))] + detect code `shouldReturn` [("test", [(Unreachable, "t < 10"), (Unreachable, "t < 20")])] From 2f66c3bf774f4a913a2e54dd0ff3c0d1063d652e Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:50:10 +0000 Subject: [PATCH 28/35] update some test case names --- test/Haskell/Template/Detection/GuardsSpec.hs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index 11e2af3..d923dff 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -291,7 +291,7 @@ test t | otherwise = 2 |] detect code `shouldReturn` [("test", [(Unreachable, "otherwise")])] - it "should also mark otherwise as redundant when previous conditions are exhaustive" $ do + it "should also mark otherwise as unreachable when previous conditions are exhaustive" $ do let code = [SI.i|module Main where test t @@ -308,7 +308,7 @@ test t | True = 1 |] detect code `shouldReturn` [] - it "should mark True redundant when previous conditions are exhaustive" $ do + it "should mark True unreachable when previous conditions are exhaustive" $ do let code = [SI.i|module Main where test t @@ -360,12 +360,6 @@ test t | t < 10 = 2 |] detect code `shouldReturn` [("test", [(Unreachable, "False")])] - it "should report non-exhaustive for a single guard" $ do - let code = - [SI.i|module Main where -test t | t < 0 = 0 -|] - detect code `shouldReturn` [] it "should report redundant conditions when single guard is exhaustive" $ do let code = [SI.i|module Main where From 1630fc05cfc4b897726ff3cadf72493b8b3a2941 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:58:28 +0000 Subject: [PATCH 29/35] more test cases --- test/Haskell/Template/Detection/GuardsSpec.hs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index d923dff..d3a95aa 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -399,3 +399,41 @@ test t | t < 20 = 3 |] detect code `shouldReturn` [("test", [(Unreachable, "t < 10"), (Unreachable, "t < 20")])] + it "currently doesn't 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` [] + it "currently doesn't 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` [] + 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")])] From 26e395ff48ed513ecc6b1417921b4eead689d11b Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 18:41:44 +0000 Subject: [PATCH 30/35] share more functions --- src/Haskell/Template/Detection/Guards.hs | 35 ++++++------------------ src/Haskell/Template/Detection/Helper.hs | 35 +++++++++++++++++++++++- src/Haskell/Template/Detection/Maybe.hs | 8 +----- 3 files changed, 43 insertions(+), 35 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 9eda058..7be3b7a 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -10,7 +10,14 @@ 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, qActName, qName, unwrapParens) +import Haskell.Template.Detection.Helper ( + ScopedExp, + isTruthfulGuard, + qActName, + qActScopedName, + qOpActName', + unwrapParens, + ) import Language.Haskell.Exts ( Decl (FunBind, PatBind), Exp (..), @@ -20,8 +27,6 @@ import Language.Haskell.Exts ( Module (Module), Name (..), Pat (PVar), - QName, - QOp (..), Rhs (GuardedRhss, UnGuardedRhs), SrcSpanInfo, Stmt (Qualifier), @@ -74,30 +79,6 @@ import Z3.Monad ( data Reason = Redundant | Unreachable deriving (Eq, Ord, Show) --- | Returns True when given expression represents 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 - -- | 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 [] diff --git a/src/Haskell/Template/Detection/Helper.hs b/src/Haskell/Template/Detection/Helper.hs index d087e1b..6c56566 100644 --- a/src/Haskell/Template/Detection/Helper.hs +++ b/src/Haskell/Template/Detection/Helper.hs @@ -5,9 +5,13 @@ module Haskell.Template.Detection.Helper ( qName, qActName, ScopedExp, + isTruthfulGuard, + qActScopedName, + qOpActName', + hasName, ) where -import Language.Haskell.Exts (Exp (..), ModuleName (..), Name (..), QName (..)) +import Language.Haskell.Exts (Exp (..), ModuleName (..), Name (..), QName (..), QOp (..)) import Language.Haskell.Names (NameInfo (..), Scoped (..), Symbol (..)) -- | Unwraps an expression from parentheses @@ -39,3 +43,32 @@ qActName q = case qName q of -- | 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 5845012..e1f07dd 100644 --- a/src/Haskell/Template/Detection/Maybe.hs +++ b/src/Haskell/Template/Detection/Maybe.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE ViewPatterns #-} - module Haskell.Template.Detection.Maybe (collectIfsWithMaybeChecks) where import Control.Monad (void) @@ -9,7 +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, qActName, unwrapParens) +import Haskell.Template.Detection.Helper (ScopedExp, hasName, unwrapParens) import Language.Haskell.Exts ( Alt (..), Decl (..), @@ -139,7 +137,3 @@ replaceFromJustWithValue valueName maybeValue = void . everywhere' (mkT replace) | hasName (Just "Data.Maybe") "fromJust" vn && fmap void (unwrapParens fnBody) == fmap void maybeValue -> Var l (UnQual l (Ident l valueName)) _ -> expr - -hasName :: Maybe String -> String -> QName (Scoped l) -> Bool -hasName mModuleName qName (qActName -> Just (modName, name)) = modName == mModuleName && name == qName -hasName _ _ _ = False From 9428038b1bffeccd3d2548f66feeb52222b293ec Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 18:51:48 +0000 Subject: [PATCH 31/35] pass around precomputed lists --- src/Haskell/Template/Detection/Guards.hs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 7be3b7a..e37f791 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -3,7 +3,7 @@ module Haskell.Template.Detection.Guards (detectRedundantGuardCondition, Reason (..)) where -import Control.Monad (join, liftM2, liftM3, void, (<=<), (>=>)) +import Control.Monad (join, liftM2, liftM3, void, (<=<)) import Data.Bifunctor (second) import Data.List (singleton) import Data.List.Extra (nubOrd) @@ -98,9 +98,7 @@ checkForRedundancy guards@(_ : _) = do checking _ [] = pure [] checking skipped ([] : remaining) = checking skipped remaining checking skipped (r : remaining) = do - let - knownGuards = map (sequence >=> mkAnd) skipped - known' = mkAnd =<< mapM (>>= mkNot) knownGuards + let known' = mkAnd =<< sequence skipped alreadyExhaustive <- prove $ do known <- known' @@ -129,7 +127,7 @@ checkForRedundancy guards@(_ : _) = do restResults <- checking - (fmap snd r : skipped) + ((mkNot =<< mkAnd =<< mapM snd r) : skipped) (map (filter ((`notElem` map (fst . snd) results) . fst)) remaining) return $ map (second fst) results ++ restResults From c3e36d4e4011ac917ebe339f0942ef569af1a2ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Fri, 4 Dec 2026 21:26:28 +0100 Subject: [PATCH 32/35] document expected vacuousness-detections --- test/Haskell/Template/Detection/GuardsSpec.hs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index d3a95aa..0fa8a7d 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -7,7 +7,7 @@ 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) +import Test.Hspec (Spec, describe, it, shouldNotReturn, shouldReturn) detect :: String -> IO [(String, [(Reason, String)])] detect code = case parse code of @@ -399,7 +399,7 @@ test t | t < 20 = 3 |] detect code `shouldReturn` [("test", [(Unreachable, "t < 10"), (Unreachable, "t < 20")])] - it "currently doesn't mark identical guard as unreachable" $ do + it "should mark identical guard as unreachable" $ do let code = [SI.i|module Main where test t @@ -407,8 +407,8 @@ test t | t < 10 = 2 | t < 20 = 3 |] - detect code `shouldReturn` [] - it "currently doesn't mark superfluous rows" $ do + detect code `shouldNotReturn` [] + it "should mark superfluous rows" $ do let code = [SI.i|module Main where scene t @@ -417,7 +417,7 @@ scene t | t < 1 = 2 | otherwise = 3 |] - detect code `shouldReturn` [] + detect code `shouldNotReturn` [] it "correctly works with lists" $ do let code = [SI.i|module Main where From 2abeee385af11de7cb9bdd4f767c6f1ae68fe357 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:35:59 +0000 Subject: [PATCH 33/35] take z3 list instead of list z3 --- src/Haskell/Template/Detection/Guards.hs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index e37f791..cf53d05 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -93,12 +93,12 @@ checkForRedundancy guards@(_ : _) = do if isTrue then return $ map ((Redundant,) . fst) xList else return [] - xs -> checking [] (map NE.toList xs) + xs -> checking (pure []) (map NE.toList xs) where checking _ [] = pure [] checking skipped ([] : remaining) = checking skipped remaining checking skipped (r : remaining) = do - let known' = mkAnd =<< sequence skipped + let known' = mkAnd =<< skipped alreadyExhaustive <- prove $ do known <- known' @@ -127,7 +127,7 @@ checkForRedundancy guards@(_ : _) = do restResults <- checking - ((mkNot =<< mkAnd =<< mapM snd r) : skipped) + ((:) <$> (mkNot =<< mkAnd =<< mapM snd r) <*> skipped) (map (filter ((`notElem` map (fst . snd) results) . fst)) remaining) return $ map (second fst) results ++ restResults From 91de09bfc565c6a81bb35e777b6041074b7f5c9e Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:14:19 +0000 Subject: [PATCH 34/35] use newer condition to check for superfluous row --- src/Haskell/Template/Detection/Guards.hs | 45 ++++++++----------- test/Haskell/Template/Detection/GuardsSpec.hs | 6 +-- 2 files changed, 22 insertions(+), 29 deletions(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index cf53d05..4990678 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -100,37 +100,30 @@ checkForRedundancy guards@(_ : _) = do checking skipped (r : remaining) = do let known' = mkAnd =<< skipped - alreadyExhaustive <- prove $ do - known <- known' - mkIff known =<< mkFalse + results <- do + guardIsSuperfluous <- prove $ do + known <- known' + mkImplies known =<< mkNot =<< mkAnd =<< mapM snd r - if alreadyExhaustive - then pure $ map ((Unreachable,) . fst) $ r ++ concat remaining - else do - isFalsy <- prove $ do - guard <- mkAnd =<< mapM snd r - mkIff guard =<< mkFalse + 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 - if isFalsy - then pure $ map ((Unreachable,) . fst) r - else do - results <- flip witherM r $ \(e, c) -> do - isRedundant <- prove $ do - known <- known' - inQuestion <- c + mkImplies known inQuestion - mkImplies known inQuestion + if isRedundant && not (isTruthfulGuard e) + then pure $ Just (Redundant, (e, c)) + else pure Nothing - 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) - restResults <- - checking - ((:) <$> (mkNot =<< mkAnd =<< mapM snd r) <*> skipped) - (map (filter ((`notElem` map (fst . snd) results) . fst)) remaining) - - return $ map (second fst) results ++ restResults + return $ results ++ restResults -- | Returns a list of redundant or unreachable guard conditions per definition detectRedundantGuardCondition diff --git a/test/Haskell/Template/Detection/GuardsSpec.hs b/test/Haskell/Template/Detection/GuardsSpec.hs index 0fa8a7d..4a51099 100644 --- a/test/Haskell/Template/Detection/GuardsSpec.hs +++ b/test/Haskell/Template/Detection/GuardsSpec.hs @@ -7,7 +7,7 @@ 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, shouldNotReturn, shouldReturn) +import Test.Hspec (Spec, describe, it, shouldReturn) detect :: String -> IO [(String, [(Reason, String)])] detect code = case parse code of @@ -407,7 +407,7 @@ test t | t < 10 = 2 | t < 20 = 3 |] - detect code `shouldNotReturn` [] + detect code `shouldReturn` [("test", [(Unreachable, "t < 10")])] it "should mark superfluous rows" $ do let code = [SI.i|module Main where @@ -417,7 +417,7 @@ scene t | t < 1 = 2 | otherwise = 3 |] - detect code `shouldNotReturn` [] + detect code `shouldReturn` [("scene", [(Unreachable, "t < 1")])] it "correctly works with lists" $ do let code = [SI.i|module Main where From 0f13a7bb3356f598e5f5ce57030b595220d08d2f Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:17:07 +0000 Subject: [PATCH 35/35] please hlint --- src/Haskell/Template/Detection/Guards.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Detection/Guards.hs b/src/Haskell/Template/Detection/Guards.hs index 4990678..088d611 100644 --- a/src/Haskell/Template/Detection/Guards.hs +++ b/src/Haskell/Template/Detection/Guards.hs @@ -121,7 +121,7 @@ checkForRedundancy guards@(_ : _) = do restResults <- checking ((:) <$> (mkNot =<< mkAnd =<< mapM snd r) <*> skipped) - (map (filter ((`notElem` map (snd) results) . fst)) remaining) + (map (filter ((`notElem` map snd results) . fst)) remaining) return $ results ++ restResults