Skip to content

Commit 9acdb90

Browse files
committed
Account for multiple patterns/guards and $ operator
1 parent e1aaccc commit 9acdb90

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

src/Hint/Monad.hs

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ issue978 = do \
6565
6666
foo x y z = return 7 -- Make foo into a pure function
6767
foo x y z = pure 7 -- Make foo into a pure function
68+
foo x y z = pure $ x + y -- Make foo into a pure function
6869
foo x y z = negate 7
6970
</TEST>
7071
-}
@@ -118,13 +119,10 @@ monadHint _ _ d =
118119
isHsDo _ = False
119120

120121
gratuitouslyMonadic :: LHsDecl GhcPs -> [Idea]
121-
gratuitouslyMonadic e@(L _ x) = case x of
122-
ValD _ func@(FunBind _ (L _ n) (MG _ (L _ ms))) ->
123-
let fname = occNameString $ rdrNameOcc n in do
124-
guard $ fname /= "main"
125-
L _ (Match _ _ _ (GRHSs _ xs _)) <- ms
126-
L _ (GRHS _ _ (L _ (HsApp _ (L _ (HsVar _ (L _ myFunc))) _))) <- xs
127-
guard (occNameString (rdrNameOcc myFunc) `elem` ["pure", "return"])
122+
gratuitouslyMonadic e@(L _ d) = case d of
123+
ValD _ func@(FunBind _ (L _ n) (MG _ (L _ ms))) -> do
124+
guard $ fname /= "main" -- Account for "main = pure ()" test
125+
guard $ all gratuitouslyMonadicExpr $ allMatchExprs ms
128126
pure $ rawIdea
129127
Suggestion
130128
"Unnecessarily monadic"
@@ -133,8 +131,21 @@ gratuitouslyMonadic e@(L _ x) = case x of
133131
(Just $ unwords ["Make", fname, "into a pure function"])
134132
[]
135133
[]
134+
where
135+
fname = occNameString $ rdrNameOcc n
136+
-- Iterate over all of the patterns of the function, as well as all of the guards
137+
allMatchExprs ms = [expr | L _ (Match _ _ _ (GRHSs _ xs _)) <- ms, L _ (GRHS _ _ expr) <- xs]
136138
_ -> []
137139

140+
-- | Handles both of:
141+
-- pure x
142+
-- pure $ f x
143+
gratuitouslyMonadicExpr :: LHsExpr GhcPs -> Bool
144+
gratuitouslyMonadicExpr x = case simplifyExp x of
145+
L _ (HsApp _ (L _ (HsVar _ (L _ myFunc))) _) ->
146+
occNameString (rdrNameOcc myFunc) `elem` ["pure", "return"]
147+
_ -> False
148+
138149
-- | Call with the name of the declaration,
139150
-- the nearest enclosing `do` expression
140151
-- the nearest enclosing expression

0 commit comments

Comments
 (0)