@@ -3,41 +3,75 @@
33{-# LANGUAGE OverloadedStrings #-}
44{-# LANGUAGE TemplateHaskell #-}
55{-# LANGUAGE TypeFamilies #-}
6+{-# LANGUAGE UndecidableInstances #-}
67
7−module Control.Monad.Validation where
8+module Control.Monad.Validation
9+ ( ValidationT(..)
10+ , runValidationT
11+ , runValidationTEither
12+ , handleValidationT
13+ , vError
14+ , vWarning
15+ , vErrorL
16+ , vWarningL
17+ , vZoom
18+ , vZoomL
19+ , vPromote
20+ , mmSingleton
21+ , setMempty
22+ , neConcat
23+ , textErrors
24+ , _MonoidMap
25+ , MonoidMap(..)
26+ ) where
827
28+import Control.Applicative
929import Control.Lens hiding ((.=))
1030import Control.Monad.Base
1131import Control.Monad.Catch
1232import Control.Monad.Except
33+import Control.Monad.Fail
1334import Control.Monad.State.Strict
14−import Control.Monad.Trans.Lift.Local
35+import Control.Monad.Trans.Control
1536import Data.Aeson
1637import Data.Foldable as F
38+import Data.Functor
1739import Data.List as L
1840import Data.Map.Strict as M
19−import Data.Monoid
2041import Data.Text as T
2142import Data.Vector as V
2243import Test.QuickCheck
2344
24−-- | Collects all throwed "warnings" throwed through StateT and "errors" throwed
25−-- through ExceptT to single value using Monoid
26−-- FIXME: give more instances like HReaderT and MonadBaseControl/MonadMask
45+#if MIN_VERSION_mtl(2,3,0)
46+import Control.Monad
47+import Control.Monad.Fix
48+#endif
49+
50+-- | Collects all thrown warnings in 'StateT' and errors
51+-- in 'ExceptT' into a single value using 'Monoid'.
2752newtype ValidationT e m a = ValidationT
2853 { unValidationT :: ExceptT e (StateT e m) a
2954 } deriving ( Functor, Applicative, Monad, MonadThrow, MonadCatch
30− , MonadBase b )
55+ , MonadBase b, Alternative, MonadFix, MonadFail, Contravariant
56+ , MonadIO, MonadPlus, MonadBaseControl b, MonadMask )
3157
3258instance MonadTrans (ValidationT e) where
3359 lift = ValidationT . lift . lift
3460
35−instance LiftLocal (ValidationT e) where
36− liftLocal _ l f = ValidationT . mapExceptT (mapStateT $ l f) . unValidationT
37−
3861-- | Map with 'Monoid' instance which 'mappend' its values
62+--
63+-- This can be used as the `e` in `ValidationT e m a` to provide different
64+-- sets of errors and warnings for different keys.
65+--
66+-- >>> :{
67+-- mconcat
68+-- [ MonoidMap $ M.fromList [(1, "foo"), (2, "hello, "), (3, "oh no")]
69+-- , MonoidMap $ M.fromList [(1, "bar"), (2, "world")]
70+-- ]
71+-- :}
72+-- MonoidMap (fromList [(1,"foobar"),(2,"hello, world"),(3,"oh no")])
3973newtype MonoidMap k v = MonoidMap (Map k v)
40− deriving (Eq, Ord, Show, Arbitrary)
74+ deriving (Eq, Ord, Show, Arbitrary, Foldable)
4175
4276makePrisms ''MonoidMap
4377
@@ -55,7 +89,7 @@ instance (Ord k, Semigroup v) => Semigroup (MonoidMap k v) where
5589
5690instance (Ord k, Monoid v) => Monoid (MonoidMap k v) where
5791 mempty = MonoidMap M.empty
58− mappend = mmAppend
92+ mappend = (<>)
5993
6094instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
6195 toJSON (MonoidMap m) = toJSON $ L.map toObj $ M.toList m
@@ -65,7 +99,7 @@ instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
6599 , "value" .= v ]
66100
67101instance (Ord k, FromJSON k, FromJSON v) => FromJSON (MonoidMap k v) where
68− parseJSON v = withArray "MonoidMap" go v
102+ parseJSON = withArray "MonoidMap" go
69103 where
70104 go arr = do
71105 keyvals <- traverse fromObj arr
@@ -82,35 +116,60 @@ mmAppend :: (Ord k, Monoid v) => MonoidMap k v -> MonoidMap k v -> MonoidMap k v
82116#endif
83117mmAppend (MonoidMap a) (MonoidMap b) = MonoidMap $ M.unionWith (<>) a b
84118
85−-- | Convenient for 'vZoom' as first artument. Will prevent generation
86−-- of map with 'mempty' values
119+-- | Convenient for 'vZoom' as first argument. Will prevent generation
120+-- of map with 'mempty' values.
87121mmSingleton :: (Eq v, Monoid v, Ord k) => k -> v -> MonoidMap k v
88−mmSingleton k = memptyWrap mempty $ MonoidMap . M.singleton k
122+mmSingleton k v
123+ | v == mempty = mempty
124+ | otherwise = MonoidMap . M.singleton k $ v
89125
90−-- | Set given value to 'mempty'
126+-- | Sets given value to 'mempty'.
91127setMempty :: (Monoid s) => ASetter' s a -> a -> s
92128setMempty setter a = set setter a mempty
93129
94−memptyWrap :: (Eq a, Monoid a) => b -> (a -> b) -> a -> b
95−memptyWrap b f a
96− | a == mempty = b
97− | otherwise = f a
98−
99−-- | If given container is not 'mempty', then use given function to
100−-- append all its elements and return 'Just' result
101−neConcat
102− :: (Foldable f, Eq (f a), Monoid a, Monoid (f a))
103− => (a -> a -> a)
104− -> f a
105− -> Maybe a
106−neConcat f = memptyWrap Nothing (Just . F.foldl' f mempty)
130+neConcat :: Foldable f => (a -> a -> a) -> f a -> Maybe a
131+neConcat f a
132+ | F.null a = Nothing
133+ | otherwise = Just $ F.foldr1 f a
107134
135+-- | Returns the strings, concatanated with @", "@ if the list is not empty.
136+--
137+-- Returns Nothing if the list is empty
138+--
139+-- >>> textErrors ["foo", "bar"]
140+-- Just "foo, bar"
141+--
142+-- >>> textErrors ["foo"]
143+-- Just "foo"
144+--
145+-- >>> textErrors []
146+-- Nothing
108147textErrors :: [Text] -> Maybe Text
109148textErrors = neConcat (\a b -> a <> ", " <> b)
110149
111−-- | Returns `mempty` instead of error if no warnings was occured. So, your
112−-- error should have `Eq` instance to detect that any error was occured. Returns
113−-- Nothing for second element of tuple if compuration was interruped by 'vError'
150+-- | Returns 'mempty' instead of error if no warnings have occurred.
151+-- Returns 'Nothing' as the second element of tuple if computation was
152+-- interrupted by 'vError'.
153+--
154+-- Returns all concatenated errors and warnings and the result if no
155+-- errors have occurred (warnings could have occurred).
156+--
157+-- >>> :{
158+-- runValidationT $ do
159+-- vWarning ["warning1"]
160+-- vError ["error"]
161+-- vWarning ["warning2"]
162+-- return 8
163+-- :}
164+-- (["error","warning1"],Nothing)
165+--
166+-- >>> :{
167+-- runValidationT $ do
168+-- vWarning ["warning1"]
169+-- vWarning ["warning2"]
170+-- return 8
171+-- :}
172+-- (["warning1","warning2"],Just 8)
114173runValidationT :: (Monoid e, Monad m) => ValidationT e m a -> m (e, Maybe a)
115174runValidationT (ValidationT m) = do
116175 (res, warnings) <- runStateT (runExceptT m) mempty
@@ -118,6 +177,25 @@ runValidationT (ValidationT m) = do
118177 Left err -> (err <> warnings, Nothing)
119178 Right a -> (warnings, Just a)
120179
180+-- | Like 'runValidationT' but doesn't return the result
181+-- if any warning has occurred.
182+--
183+-- >>> :{
184+-- runValidationTEither $ do
185+-- vWarning ["warning1"]
186+-- vError ["error"]
187+-- vWarning ["warning2"]
188+-- return 8
189+-- :}
190+-- Left ["error","warning1"]
191+--
192+-- >>> :{
193+-- runValidationTEither $ do
194+-- vWarning ["warning1"]
195+-- vWarning ["warning2"]
196+-- return 8
197+-- :}
198+-- Left ["warning1","warning2"]
121199runValidationTEither
122200 :: (Monoid e, Eq e, Monad m)
123201 => ValidationT e m a
@@ -128,28 +206,71 @@ runValidationTEither action = do
128206 Just a | err == mempty -> Right a
129207 _ -> Left err
130208
209+-- | Like 'runValidationTEither', but takes an error handler instead of
210+-- returning errors and warnings.
211+--
212+-- >>> :{
213+-- handleValidationT (\_ -> return 11) $ do
214+-- vWarning ["warning1"]
215+-- vError ["error"]
216+-- vWarning ["warning2"]
217+-- return 8
218+-- :}
219+-- 11
220+--
221+-- >>> :{
222+-- handleValidationT (\_ -> return 11) $ do
223+-- vWarning ["warning1"]
224+-- vWarning ["warning2"]
225+-- return 8
226+-- :}
227+-- 11
131228handleValidationT
132229 :: (Monoid e, Monad m, Eq e)
133230 => (e -> m a)
134231 -> ValidationT e m a
135232 -> m a
136−handleValidationT handler action = do
233+handleValidationT handler action =
137234 runValidationTEither action >>= either handler return
138235
139−-- | Stops further execution of validation
236+-- | Stops further execution and appends the given error.
140237vError :: (Monad m) => e -> ValidationT e m a
141238vError e = ValidationT $ throwError e
142239
143−-- | Does not stop further execution, append warning to
240+-- | Does not stop further execution and appends the given warning.
144241vWarning :: (Monad m, Monoid e) => e -> ValidationT e m ()
145242vWarning e = ValidationT $ modify' (<> e)
146243
244+-- | Like 'vError' but allows you to use a setter to insert an error somewhere
245+-- deeper into an empty ('mempty') "e" from "ValidationT e m x", which is then
246+-- combined with all gathered warnings.
147247vErrorL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m x
148248vErrorL l a = vError $ setMempty l a
149249
250+-- | Like 'vWarning' but allows you to use a setter to insert an error somewhere
251+-- deeper into an empty ('mempty') "e" from "ValidationT e m x", which is then
252+-- combined with all gathered warnings.
150253vWarningL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m ()
151254vWarningL l a = vWarning $ setMempty l a
152255
256+-- | Allows you apply a transformation to the "e" in "ValidationT e m x".
257+--
258+-- >>> :{
259+--runValidationT . vZoom (Data.Map.singleton "password errors") $ do
260+-- vWarning ["warning1"]
261+-- vError ["error"]
262+-- vWarning ["warning2"]
263+-- return 8
264+-- :}
265+-- (fromList [("password errors",["error","warning1"])],Nothing)
266+--
267+-- >>> :{
268+-- runValidationT . vZoom (Data.Map.singleton "password errors") $ do
269+-- vWarning ["warning1"]
270+-- vWarning ["warning2"]
271+-- return 8
272+-- :}
273+-- (fromList [("password errors",["warning1","warning2"])],Just 8)
153274vZoom
154275 :: (Monad m, Monoid a, Monoid b)
155276 => (a -> b)
@@ -159,11 +280,21 @@ vZoom up action = do
159280 (err, res) <- lift $ runValidationT action
160281 case res of
161282 Nothing -> vError $ up err
162− Just a -> vWarning (up err) *> return a
283+ Just a -> vWarning (up err) $> a
163284
285+-- | Like 'vZoom' but takes a setter instead of a function.
164286vZoomL
165287 :: (Monad m, Monoid a, Monoid b)
166288 => ASetter' b a
167289 -> ValidationT a m x
168290 -> ValidationT b m x
169−vZoomL l action = vZoom (setMempty l) action
291+vZoomL l = vZoom (setMempty l)
292+
293+-- | Turn any warnings the have occurred into errors.
294+vPromote
295+ :: (Monad m, Monoid a, Eq a)
296+ => ValidationT a m x
297+ -> ValidationT a m x
298+vPromote m = do
299+ err <- lift $ runValidationTEither m
300+ either vError return err