@@ -1,13 +1,40 @@
1−module Common.Monad.Validation where
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+{-# LANGUAGE TemplateHaskell #-}
5+{-# LANGUAGE TypeFamilies #-}
6+{-# LANGUAGE UndecidableInstances #-}
27
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+ , mmSingleton
20+ , setMempty
21+ , neConcat
22+ , textErrors
23+ , _MonoidMap
24+ , MonoidMap(..)
25+ ) where
26+
27+import Control.Applicative
328import Control.Lens hiding ((.=))
429import Control.Monad.Base
530import Control.Monad.Catch
631import Control.Monad.Except
32+import Control.Monad.Fail
733import Control.Monad.State.Strict
8−import Control.Monad.Trans.Lift.Local
34+import Control.Monad.Trans.Control
935import Data.Aeson
1036import Data.Foldable as F
37+import Data.Functor
1138import Data.List as L
1239import Data.Map.Strict as M
1340import Data.Monoid
@@ -15,23 +42,32 @@ import Data.Text as T
1542import Data.Vector as V
1643import Test.QuickCheck
1744
18−-- | Collects all throwed "warnings" throwed through StateT and "errors" throwed
19−-- through ExceptT to single value using Monoid
20−-- FIXME: give more instances like HReaderT and MonadBaseControl/MonadMask
45+
46+-- | Collects all thrown warnings in 'StateT' and errors
47+-- in 'ExceptT' into a single value using 'Monoid'.
2148newtype ValidationT e m a = ValidationT
2249 { unValidationT :: ExceptT e (StateT e m) a
2350 } deriving ( Functor, Applicative, Monad, MonadThrow, MonadCatch
24− , MonadBase b )
51+ , MonadBase b, Alternative, MonadFix, MonadFail, Contravariant
52+ , MonadIO, MonadPlus, MonadBaseControl b, MonadMask )
2553
2654instance MonadTrans (ValidationT e) where
2755 lift = ValidationT . lift . lift
2856
29−instance LiftLocal (ValidationT e) where
30− liftLocal _ l f = ValidationT . mapExceptT (mapStateT $ l f) . unValidationT
31−
3257-- | Map with 'Monoid' instance which 'mappend' its values
58+--
59+-- This can be used as the `e` in `ValidationT e m a` to provide different
60+-- sets of errors and warnings for different keys.
61+--
62+-- >>> :{
63+-- mconcat
64+-- [ MonoidMap $ M.fromList [(1, "foo"), (2, "hello, "), (3, "oh no")]
65+-- , MonoidMap $ M.fromList [(1, "bar"), (2, "world")]
66+-- ]
67+-- :}
68+-- MonoidMap (fromList [(1,"foobar"),(2,"hello, world"),(3,"oh no")])
3369newtype MonoidMap k v = MonoidMap (Map k v)
34− deriving (Eq, Ord, Show, Arbitrary)
70+ deriving (Eq, Ord, Show, Arbitrary, Foldable)
3571
3672makePrisms ''MonoidMap
3773
@@ -42,10 +78,14 @@ instance (Ord k) => Ixed (MonoidMap k v) where
4278instance (Ord k) => At (MonoidMap k v) where
4379 at key = _MonoidMap . at key
4480
81+#if MIN_VERSION_base(4,11,0)
82+instance (Ord k, Semigroup v) => Semigroup (MonoidMap k v) where
83+ (<>) = mmAppend
84+#endif
85+
4586instance (Ord k, Monoid v) => Monoid (MonoidMap k v) where
4687 mempty = MonoidMap M.empty
47− mappend (MonoidMap a) (MonoidMap b) =
48− MonoidMap $ M.unionWith (<>) a b
88+ mappend = mmAppend
4989
5090instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
5191 toJSON (MonoidMap m) = toJSON $ L.map toObj $ M.toList m
@@ -55,7 +95,7 @@ instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
5595 , "value" .= v ]
5696
5797instance (Ord k, FromJSON k, FromJSON v) => FromJSON (MonoidMap k v) where
58− parseJSON v = withArray "MonoidMap" go v
98+ parseJSON = withArray "MonoidMap" go
5999 where
60100 go arr = do
61101 keyvals <- traverse fromObj arr
@@ -65,35 +105,67 @@ instance (Ord k, FromJSON k, FromJSON v) => FromJSON (MonoidMap k v) where
65105 val <- obj .: "value"
66106 return (key, val)
67107
68−-- | Convenient for 'vZoom' as first artument. Will prevent generation
69−-- of map with 'mempty' values
108+#if MIN_VERSION_base(4,11,0)
109+mmAppend :: (Ord k, Semigroup v) => MonoidMap k v -> MonoidMap k v -> MonoidMap k v
110+#else
111+mmAppend :: (Ord k, Monoid v) => MonoidMap k v -> MonoidMap k v -> MonoidMap k v
112+#endif
113+mmAppend (MonoidMap a) (MonoidMap b) = MonoidMap $ M.unionWith (<>) a b
114+
115+-- | Convenient for 'vZoom' as first argument. Will prevent generation
116+-- of map with 'mempty' values.
70117mmSingleton :: (Eq v, Monoid v, Ord k) => k -> v -> MonoidMap k v
71−mmSingleton k = memptyWrap mempty $ MonoidMap . M.singleton k
118+mmSingleton k v
119+ | v == mempty = mempty
120+ | otherwise = MonoidMap . M.singleton k $ v
72121
73−-- | Set given value to 'mempty'
122+-- | Sets given value to 'mempty'.
74123setMempty :: (Monoid s) => ASetter' s a -> a -> s
75124setMempty setter a = set setter a mempty
76125
77−memptyWrap :: (Eq a, Monoid a) => b -> (a -> b) -> a -> b
78−memptyWrap b f a
79− | a == mempty = b
80− | otherwise = f a
81−
82−-- | If given container is not 'mempty', then use given function to
83−-- append all its elements and return 'Just' result
84−neConcat
85− :: (Foldable f, Eq (f a), Monoid a, Monoid (f a))
86− => (a -> a -> a)
87− -> f a
88− -> Maybe a
89−neConcat f = memptyWrap Nothing (Just . F.foldl' f mempty)
126+neConcat :: Foldable f => (a -> a -> a) -> f a -> Maybe a
127+neConcat f a
128+ | F.null a = Nothing
129+ | otherwise = Just $ F.foldr1 f a
90130
131+-- | Returns the strings, concatanated with @", "@ if the list is not empty.
132+--
133+-- Returns Nothing if the list is empty
134+--
135+-- >>> textErrors ["foo", "bar"]
136+-- Just "foo, bar"
137+--
138+-- >>> textErrors ["foo"]
139+-- Just "foo"
140+--
141+-- >>> textErrors []
142+-- Nothing
91143textErrors :: [Text] -> Maybe Text
92144textErrors = neConcat (\a b -> a <> ", " <> b)
93145
94−-- | Returns `mempty` instead of error if no warnings was occured. So, your
95−-- error should have `Eq` instance to detect that any error was occured. Returns
96−-- Nothing for second element of tuple if compuration was interruped by 'vError'
146+-- | Returns 'mempty' instead of error if no warnings have occured.
147+-- Returns 'Nothing' as the second element of tuple if computation was
148+-- interrupted by 'vError'.
149+--
150+-- Returns all concatenated errors and warnings and the result if no
151+-- errors have occured (warnings could have occured).
152+--
153+-- >>> :{
154+-- runValidationT $ do
155+-- vWarning ["warning1"]
156+-- vError ["error"]
157+-- vWarning ["warning2"]
158+-- return 8
159+-- :}
160+-- (["error","warning1"],Nothing)
161+--
162+-- >>> :{
163+-- runValidationT $ do
164+-- vWarning ["warning1"]
165+-- vWarning ["warning2"]
166+-- return 8
167+-- :}
168+-- (["warning1","warning2"],Just 8)
97169runValidationT :: (Monoid e, Monad m) => ValidationT e m a -> m (e, Maybe a)
98170runValidationT (ValidationT m) = do
99171 (res, warnings) <- runStateT (runExceptT m) mempty
@@ -101,6 +173,25 @@ runValidationT (ValidationT m) = do
101173 Left err -> (err <> warnings, Nothing)
102174 Right a -> (warnings, Just a)
103175
176+-- | Like 'runValidationT' but doesn't return the result
177+-- if any warning has occured.
178+--
179+-- >>> :{
180+-- runValidationTEither $ do
181+-- vWarning ["warning1"]
182+-- vError ["error"]
183+-- vWarning ["warning2"]
184+-- return 8
185+-- :}
186+-- Left ["error","warning1"]
187+--
188+-- >>> :{
189+-- runValidationTEither $ do
190+-- vWarning ["warning1"]
191+-- vWarning ["warning2"]
192+-- return 8
193+-- :}
194+-- Left ["warning1","warning2"]
104195runValidationTEither
105196 :: (Monoid e, Eq e, Monad m)
106197 => ValidationT e m a
@@ -111,28 +202,71 @@ runValidationTEither action = do
111202 Just a | err == mempty -> Right a
112203 _ -> Left err
113204
205+-- | Like 'runValidationTEither', but takes an error handler instead of
206+-- returning errors and warnings.
207+--
208+-- >>> :{
209+-- handleValidationT (\_ -> return 11) $ do
210+-- vWarning ["warning1"]
211+-- vError ["error"]
212+-- vWarning ["warning2"]
213+-- return 8
214+-- :}
215+-- 11
216+--
217+-- >>> :{
218+-- handleValidationT (\_ -> return 11) $ do
219+-- vWarning ["warning1"]
220+-- vWarning ["warning2"]
221+-- return 8
222+-- :}
223+-- 11
114224handleValidationT
115225 :: (Monoid e, Monad m, Eq e)
116226 => (e -> m a)
117227 -> ValidationT e m a
118228 -> m a
119−handleValidationT handler action = do
229+handleValidationT handler action =
120230 runValidationTEither action >>= either handler return
121231
122−-- | Stops further execution of validation
232+-- | Stops further execution and appends the given error.
123233vError :: (Monad m) => e -> ValidationT e m a
124234vError e = ValidationT $ throwError e
125235
126−-- | Does not stop further execution, append warning to
236+-- | Does not stop further execution and appends the given warning.
127237vWarning :: (Monad m, Monoid e) => e -> ValidationT e m ()
128238vWarning e = ValidationT $ modify' (<> e)
129239
240+-- | Like 'vError' but allows you to use a setter to insert an error somewhere
241+-- deeper into an empty ('mempty') "e" from "ValidationT e m x", which is then
242+-- combined with all gathered warnings.
130243vErrorL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m x
131244vErrorL l a = vError $ setMempty l a
132245
246+-- | Like 'vWarning' but allows you to use a setter to insert an error somewhere
247+-- deeper into an empty ('mempty') "e" from "ValidationT e m x", which is then
248+-- combined with all gathered warnings.
133249vWarningL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m ()
134250vWarningL l a = vWarning $ setMempty l a
135251
252+-- | Allows you apply a transformation to the "e" in "ValidationT e m x".
253+--
254+-- >>> :{
255+--runValidationT . vZoom (Data.Map.singleton "password errors") $ do
256+-- vWarning ["warning1"]
257+-- vError ["error"]
258+-- vWarning ["warning2"]
259+-- return 8
260+-- :}
261+-- (fromList [("password errors",["error","warning1"])],Nothing)
262+--
263+-- >>> :{
264+-- runValidationT . vZoom (Data.Map.singleton "password errors") $ do
265+-- vWarning ["warning1"]
266+-- vWarning ["warning2"]
267+-- return 8
268+-- :}
269+-- (fromList [("password errors",["warning1","warning2"])],Just 8)
136270vZoom
137271 :: (Monad m, Monoid a, Monoid b)
138272 => (a -> b)
@@ -142,11 +276,12 @@ vZoom up action = do
142276 (err, res) <- lift $ runValidationT action
143277 case res of
144278 Nothing -> vError $ up err
145− Just a -> vWarning (up err) *> return a
279+ Just a -> vWarning (up err) $> a
146280
281+-- | Like 'vZoom' but takes a setter instead of a function.
147282vZoomL
148283 :: (Monad m, Monoid a, Monoid b)
149284 => ASetter' b a
150285 -> ValidationT a m x
151286 -> ValidationT b m x
152−vZoomL l action = vZoom (setMempty l) action
287+vZoomL l = vZoom (setMempty l)