Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
95751a9
add check for redundant guard conditions
nimec01 Nov 15, 2026
4508e2a
add spec
nimec01 Nov 16, 2026
d62193d
allow words
nimec01 Nov 16, 2026
b7fa22f
Merge branch 'master' into guards-check
jvoigtlaender Nov 30, 2026
9ae7d47
Merge branch 'master' into guards-check
nimec01 Dec 2, 2026
a780d45
share unwrapParens
nimec01 Dec 2, 2026
e2dccd0
share qName and qActName
nimec01 Dec 2, 2026
7131de8
refactor hasName
nimec01 Dec 2, 2026
4e22ab8
share and make use of ScopedExp
nimec01 Dec 2, 2026
da9620a
add haddock comment
nimec01 Dec 2, 2026
7c49294
fix computation of knowledge
nimec01 Dec 2, 2026
5dfe170
fix translation of negative numbers
nimec01 Dec 2, 2026
27c621a
add more test cases
nimec01 Dec 2, 2026
8d4e385
Merge branch 'master' into guards-check
nimec01 Dec 2, 2026
0b40561
clarify test case
nimec01 Dec 2, 2026
8570c10
add more tests
nimec01 Dec 3, 2026
25ce4e8
allow xit
nimec01 Dec 3, 2026
5f3209e
special treatment for otherwise
nimec01 Dec 3, 2026
82d8d88
formatting
nimec01 Dec 3, 2026
725dc63
test case
nimec01 Dec 3, 2026
e80936f
handle True just like otherwise
nimec01 Dec 3, 2026
1946ffc
add even more test cases
nimec01 Dec 3, 2026
40e3551
differentiate between redundant and unreachable conditions
nimec01 Dec 3, 2026
724ae77
also differentiate whether guards are explicitly exhaustive or not
nimec01 Dec 3, 2026
e4f4fbc
spelling config
nimec01 Dec 3, 2026
cfa94f9
two more test cases
nimec01 Dec 4, 2026
c41129a
make div, mod, rem work on integers instead of reals
nimec01 Dec 4, 2026
34f9b89
re-model result type
nimec01 Dec 4, 2026
96cbcce
also mark guards unreachable which are equivalent to false
nimec01 Dec 4, 2026
e9a9fa6
don't track exhaustiveness in result type
nimec01 Dec 4, 2026
2f66c3b
update some test case names
nimec01 Dec 4, 2026
1630fc0
more test cases
nimec01 Dec 4, 2026
26e395f
share more functions
nimec01 Dec 4, 2026
9428038
pass around precomputed lists
nimec01 Dec 4, 2026
c3e36d4
document expected vacuousness-detections
jvoigtlaender Dec 4, 2026
2abeee3
take z3 list instead of list z3
nimec01 Dec 4, 2026
91de09b
use newer condition to check for superfluous row
nimec01 Dec 4, 2026
0f13a7b
please hlint
nimec01 Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .github/actions/spelling/allow.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Aeson
autotool
Bifunctor
bimap
concat
elems
FCase
Expand All @@ -18,19 +19,26 @@ hlint
Hspec
HUnit
hyperlinks
Ite
mempty
mplus
msum
Mul
mzero
PApp
QCon
QName
QOp
QVar
Rebindable
scrutinee
snd
standalone
thd
uncurry
unlines
Unsat
Utf
Witherable
xit
yml
1 change: 1 addition & 0 deletions .github/actions/spelling/patterns.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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+
Expand Down
7 changes: 7 additions & 0 deletions haskell-template-task.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ source-repository head

library
exposed-modules:
Haskell.Template.Detection.Guards
Haskell.Template.Detection.Helper
Haskell.Template.Detection.Maybe
Haskell.Template.Match
Haskell.Template.Task
Expand Down Expand Up @@ -55,15 +57,18 @@ library
, syb
, text
, transformers
, witherable
, wl-pprint-text
, yaml
, z3
default-language: Haskell2010

test-suite haskell-template-task-test
type: exitcode-stdio-1.0
main-is: Spec.hs
other-modules:
Haskell.Template.ConfigSpec
Haskell.Template.Detection.GuardsSpec
Comment thread
nimec01 marked this conversation as resolved.
Resolved
Haskell.Template.Detection.MaybeSpec
Haskell.Template.GradingSpec
Haskell.Template.Helper
Expand Down Expand Up @@ -102,6 +107,8 @@ test-suite haskell-template-task-test
, temporary
, text
, transformers
, witherable
, wl-pprint-text
, yaml
, z3
default-language: Haskell2010
2 changes: 2 additions & 0 deletions package.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ dependencies:
- aeson
- containers
- haskell-names
- witherable
- transformers
- z3

ghc-options:
- -Wall
Expand Down
305 changes: 305 additions & 0 deletions src/Haskell/Template/Detection/Guards.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,305 @@
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}

module Haskell.Template.Detection.Guards (detectRedundantGuardCondition, Reason (..)) where

import Control.Monad (join, liftM2, liftM3, void, (<=<))
import Data.Bifunctor (second)
import Data.List (singleton)
import Data.List.Extra (nubOrd)
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NE (fromList, toList)
import Data.Maybe (fromJust, mapMaybe, maybeToList)
import Haskell.Template.Detection.Helper (
ScopedExp,
isTruthfulGuard,
qActName,
qActScopedName,
qOpActName',
unwrapParens,
)
import Language.Haskell.Exts (
Decl (FunBind, PatBind),
Exp (..),
GuardedRhs (..),
Literal (..),
Match (InfixMatch, Match),
Module (Module),
Name (..),
Pat (PVar),
Rhs (GuardedRhss, UnGuardedRhs),
SrcSpanInfo,
Stmt (Qualifier),
ann,
)
import Language.Haskell.Names (
NameInfo,
Scoped (..),
)
import Witherable (witherM)
import Z3.Monad (
AST,
Result (..),
Z3,
assert,
check,
evalZ3,
mkAdd,
mkAnd,
mkBoolVar,
mkDiv,
mkEq,
mkFalse,
mkGe,
mkGt,
mkIff,
mkImplies,
mkInt,
mkIntSort,
mkIntVar,
mkIte,
mkLe,
mkLt,
mkMod,
mkMul,
mkNot,
mkNumeral,
mkOr,
mkReal2Int,
mkRealSort,
mkRealVar,
mkRem,
mkStringSymbol,
mkSub,
mkTrue,
mkUnaryMinus,
)

-- | Reason for a condition being reported
data Reason = Redundant | Unreachable
deriving (Eq, Ord, Show)

-- | Returns a list of redundant or unreachable guard conditions together with an exhaustion status
checkForRedundancy :: Eq a => [NonEmpty (ScopedExp a, Z3 AST)] -> IO [(Reason, ScopedExp a)]
checkForRedundancy [] = pure []
checkForRedundancy guards@(_ : _) = do
case guards of
[x] -> do
let xList = NE.toList x
isTrue <- prove $ do
inQuestion <- mkAnd =<< mapM snd xList
mkIff inQuestion =<< mkTrue

if isTrue
then return $ map ((Redundant,) . fst) xList
else return []
xs -> checking (pure []) (map NE.toList xs)
where
checking _ [] = pure []
checking skipped ([] : remaining) = checking skipped remaining
checking skipped (r : remaining) = do
let known' = mkAnd =<< skipped

results <- do
guardIsSuperfluous <- prove $ do
known <- known'
mkImplies known =<< mkNot =<< mkAnd =<< mapM snd r

if guardIsSuperfluous
then pure $ map ((Unreachable,) . fst) r
else fmap (map (second fst)) $ flip witherM r $ \(e, c) -> do
isRedundant <- prove $ do
known <- known'
inQuestion <- c

mkImplies known inQuestion

if isRedundant && not (isTruthfulGuard e)
then pure $ Just (Redundant, (e, c))
else pure Nothing

restResults <-
checking
((:) <$> (mkNot =<< mkAnd =<< mapM snd r) <*> skipped)
(map (filter ((`notElem` map snd results) . fst)) remaining)

return $ results ++ restResults

-- | Returns a list of redundant or unreachable guard conditions per definition
detectRedundantGuardCondition
:: Module (Scoped SrcSpanInfo)
-> IO [(Name (Scoped SrcSpanInfo), [(Reason, ScopedExp SrcSpanInfo)])]
detectRedundantGuardCondition mod' =
flip witherM (extractFromModule mod') $ \(name, constraints) -> do
redundant <- checkForRedundancy constraints
case redundant of
[] -> pure Nothing
xs -> pure $ Just (name, nubOrd xs)

-- | Extracts all guard conditions from a definition using guards
extractFromModule
:: Module (Scoped SrcSpanInfo)
-> [(Name (Scoped SrcSpanInfo), [NonEmpty (ScopedExp SrcSpanInfo, Z3 AST)])]
extractFromModule (Module _ _ _ _ decls) = concatMap fromDecl decls
where
fromDecl (FunBind _ matches) = map fromMatch matches
fromDecl (PatBind _ (PVar _ name) rhs _) = [(name, fromRhs rhs)]
fromDecl _ = []

fromRhs (UnGuardedRhs _ _) = []
fromRhs (GuardedRhss _ gRhss) = mapMaybe extractConstraintsFromGuardedRhs gRhss

fromMatch (Match _ name _ rhs _) = (name, fromRhs rhs)
fromMatch (InfixMatch _ _ name _ rhs _) = (name, fromRhs rhs)
extractFromModule _ = []

{- | Extracts all conditions from a given guard.
|
| Returns `Nothing` if one guard is not a pure boolean expression.
-}
extractConstraintsFromGuardedRhs
:: GuardedRhs (Scoped SrcSpanInfo)
-> Maybe (NonEmpty (ScopedExp SrcSpanInfo, Z3 AST))
extractConstraintsFromGuardedRhs (GuardedRhs _ statements _) = case concat <$> mapM extractFromStmt statements of
Nothing -> Nothing
Just [] -> Nothing
Just xs -> Just $ NE.fromList xs
where
extractFromStmt (Qualifier _ conditionExpr) = Just $ astToZ3 conditionExpr
extractFromStmt _ = Nothing

-- | Returns the z3 variable name representing a scoped variable
scopedVarName :: Show a => (NameInfo a, String) -> String
scopedVarName (scope, name) = show scope ++ "::" ++ name

-- | Returns the z3 variable name representing the length of the list encapsulated in the expression
listVarName :: ScopedExp () -> String
listVarName expr = "::length_" ++ show expr

-- | Computes the z3 ast for a given expression inside an arithmetical expression
arithAstToZ3 :: Show a => ScopedExp a -> Maybe (ScopedExp a, Z3 AST)
arithAstToZ3 (unwrapParens -> expr) =
(expr,) <$> case unwrapParens expr of
( Var
_
( qActScopedName ->
Just scopedName
)
) -> Just $ mkRealVar =<< mkStringSymbol (scopedVarName scopedName)
(Lit _ (Int _ _ valueString)) ->
Just $ mkNumeral valueString =<< mkIntSort
(Lit _ (Frac _ _ valueString)) ->
Just $ mkNumeral valueString =<< mkRealSort
(App _ (Var _ (qActName -> Just (mModName, name))) arg) ->
arithAppToZ3 mModName name [arg]
(App _ (unwrapParens -> App _ (unwrapParens -> Var _ (qActName -> Just (mModName, name))) arg1) arg2) ->
arithAppToZ3 mModName name [arg1, arg2]
(InfixApp _ l (qOpActName' -> Just (mModName, name)) r) ->
arithAppToZ3 mModName name [l, r]
(Let _ _ e) ->
snd <$> arithAstToZ3 e
(NegApp _ e) ->
(mkUnaryMinus <=< snd) <$> arithAstToZ3 e
_ ->
Nothing

-- | Computes the z3 ast for a given function or operator application inside an arithmetical expression
arithAppToZ3 :: Show a => Maybe String -> String -> [ScopedExp a] -> Maybe (Z3 AST)
arithAppToZ3 (Just "GHC.Num") "+" [l, r] =
combineMaybeArithExprs False (\a b -> mkAdd [a, b]) l r
arithAppToZ3 (Just "GHC.Num") "-" [l, r] =
combineMaybeArithExprs False (\a b -> mkSub [a, b]) l r
arithAppToZ3 (Just "GHC.Num") "*" [l, r] =
combineMaybeArithExprs False (\a b -> mkMul [a, b]) l r
arithAppToZ3 (Just "GHC.Real") "/" [l, r] =
combineMaybeArithExprs False mkDiv l r
arithAppToZ3 (Just "GHC.Real") "div" [l, r] =
combineMaybeArithExprs True mkDiv l r
arithAppToZ3 (Just "GHC.Real") "mod" [l, r] =
combineMaybeArithExprs True mkMod l r
arithAppToZ3 (Just "GHC.Real") "rem" [l, r] =
combineMaybeArithExprs True mkRem l r
arithAppToZ3 (Just "GHC.List") "length" [ls] = Just $ do
v <- mkIntVar =<< mkStringSymbol (listVarName $ fmap void ls)
assert =<< mkGe v =<< mkInt 0 =<< mkIntSort
return v
arithAppToZ3 (Just "Data.List") "sum" [unwrapParens -> List _ es] =
(mkAdd <=< sequence) <$> mapM (fmap snd . arithAstToZ3) es
arithAppToZ3 (Just "Data.List") "product" [unwrapParens -> List _ es] =
(mkMul <=< sequence) <$> mapM (fmap snd . arithAstToZ3) es
arithAppToZ3 _ _ _ = Nothing

-- | Computes the z3 ast for a given expression
astToZ3 :: Show a => ScopedExp a -> [(ScopedExp a, Z3 AST)]
astToZ3 (unwrapParens -> expr) = case expr of
(Var _ (qActName -> Just (Just "GHC.Base", "otherwise"))) ->
singleton (expr, mkTrue)
(Var _ (qActScopedName -> Just scopedName)) ->
-- variable outside arithmetic comparison
singleton $ (expr,) $ mkBoolVar =<< mkStringSymbol (scopedVarName scopedName)
(App _ (Var _ (qActName -> Just (mModName, name))) arg) ->
-- application outside arithmetic comparison
appToZ3 expr mModName name [arg]
(InfixApp _ l (qOpActName' -> Just (mModName, name)) r) ->
-- infix application outside arithmetic comparison
appToZ3 expr mModName name [l, r]
(Con _ (qActName -> Just (Just "GHC.Types", "True"))) ->
-- literal True
singleton (expr, mkTrue)
(Con _ (qActName -> Just (Just "GHC.Types", "False"))) ->
-- literal False
singleton (expr, mkFalse)
(Let _ _ e) -> astToZ3 e
(If _ cond t e) ->
map (expr,) $
liftM3 (\(_, a) (_, b) (_, c) -> join $ liftM3 mkIte a b c) (astToZ3 cond) (astToZ3 t) (astToZ3 e)
_ -> []

-- | Computes the z3 ast for a given function or operator application
appToZ3 :: Show a => ScopedExp a -> Maybe String -> String -> [ScopedExp a] -> [(ScopedExp a, Z3 AST)]
appToZ3 expr (Just "GHC.Classes") opName [l, r]
| opName `elem` map fst opMap =
map (expr,) $ maybeToList $ combineMaybeArithExprs False op l r
where
opMap = [("<", mkLt), ("<=", mkLe), (">", mkGt), (">=", mkGe), ("==", mkEq)]
op = fromJust $ lookup opName opMap
appToZ3 expr (Just "GHC.Classes") "&&" [l, r] =
appToZ3 expr (Just "GHC.List") "and" [List (ann l) [l, r]]
appToZ3 expr (Just "GHC.Classes") "||" [l, r] =
appToZ3 expr (Just "GHC.List") "or" [List (ann l) [l, r]]
appToZ3 expr (Just "GHC.Classes") "/=" [l, r] =
map (expr,) $ maybeToList ((mkNot =<<) <$> combineMaybeArithExprs False mkEq l r)
appToZ3 expr (Just "GHC.Classes") "not" [e] =
(expr,) . (mkNot <=< snd) <$> astToZ3 e
appToZ3 expr (Just "GHC.List") "null" [ls] =
singleton $ (expr,) $ do
v <- mkIntVar =<< mkStringSymbol (listVarName $ fmap void ls)
mkEq v =<< mkInt 0 =<< mkIntSort
appToZ3 _ (Just "GHC.List") "and" [unwrapParens -> List _ es] =
concat $ mapM astToZ3 es
appToZ3 expr (Just "GHC.List") "or" [unwrapParens -> List _ es] =
singleton $ (expr,) $ mkOr =<< mapM (mkAnd <=< (mapM snd . astToZ3)) es
appToZ3 _ _ _ _ =
[]

{- | Computes the z3 ast for a composition of two (arithmetic) expressions.
|
| Only returns `Just` when both expressions are arithmetic expressions.
-}
combineMaybeArithExprs :: Show a => Bool -> (AST -> AST -> Z3 AST) -> ScopedExp a -> ScopedExp a -> Maybe (Z3 AST)
combineMaybeArithExprs onInt f l r = liftM2 (\(_, a) (_, b) -> join $ liftM2 f a b) (toZ3 l) (toZ3 r)
where
toZ3 v = second (if onInt then (mkReal2Int =<<) else id) <$> arithAstToZ3 v

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure this will give a semantic interpretation on the SMT side that is equivalent to the Haskell semantics of mod etc.?

I remember that Oliver had problems with that. The SMT solver had a different interpretation of integer division in the negatives than what Haskell uses. With the consequence that relying on semantic information from the SMT solver could lead to wrong analysis results regarding the Haskell program under consideration.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't investigate that yet.


-- | Proves if a given proposition in form of a z3 ast is valid
prove :: Z3 AST -> IO Bool
prove prop = do
res <- evalZ3 $ do
p <- prop

assert =<< mkNot p

check
case res of
Unsat -> pure True
_ -> pure False
Loading
Loading