@@ -1,43 +1,73 @@
1{-# LANGUAGE GeneralizedNewtypeDeriving #-}
2{-# LANGUAGE GeneralizedNewtypeDeriving #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE TemplateHaskell #-}
4{-# LANGUAGE TemplateHaskell #-}
4{-# LANGUAGE TypeFamilies #-}
5{-# LANGUAGE TypeFamilies #-}
6+{-# LANGUAGE UndecidableInstances #-}
6−module Control.Monad.Validation where
8+module Control.Monad.Validation
11+ , runValidationTEither
27+import Control.Applicative
8import Control.Lens hiding ((.=))
28import Control.Lens hiding ((.=))
9import Control.Monad.Base
29import Control.Monad.Base
10import Control.Monad.Catch
30import Control.Monad.Catch
11import Control.Monad.Except
31import Control.Monad.Except
32+import Control.Monad.Fail
12import Control.Monad.State.Strict
33import Control.Monad.State.Strict
13−import Control.Monad.Trans.Lift.Local
34+import Control.Monad.Trans.Control
14import Data.Aeson
35import Data.Aeson
15import Data.Foldable as F
36import Data.Foldable as F
16import Data.List as L
38import Data.List as L
17import Data.Map.Strict as M
39import Data.Map.Strict as M
18import Data.Monoid
40import Data.Monoid
19−import qualified Data.Semigroup as S
20import Data.Text as T
41import Data.Text as T
21import Data.Vector as V
42import Data.Vector as V
22import Test.QuickCheck
43import Test.QuickCheck
24−-- | Collects all throwed "warnings" throwed through StateT and "errors" throwed
46+-- | Collects all thrown warnings in 'StateT' and errors
25−-- through ExceptT to single value using Monoid
47+-- in 'ExceptT' into a single value using 'Monoid'.
26−-- FIXME: give more instances like HReaderT and MonadBaseControl/MonadMask
27newtype ValidationT e m a = ValidationT
48newtype ValidationT e m a = ValidationT
28 { unValidationT :: ExceptT e (StateT e m) a
49 { unValidationT :: ExceptT e (StateT e m) a
29 } deriving ( Functor, Applicative, Monad, MonadThrow, MonadCatch
50 } deriving ( Functor, Applicative, Monad, MonadThrow, MonadCatch
30− , MonadBase b )
51+ , MonadBase b, Alternative, MonadFix, MonadFail, Contravariant
52+ , MonadIO, MonadPlus, MonadBaseControl b, MonadMask )
32instance MonadTrans (ValidationT e) where
54instance MonadTrans (ValidationT e) where
33 lift = ValidationT . lift . lift
55 lift = ValidationT . lift . lift
35−instance LiftLocal (ValidationT e) where
36− liftLocal _ l f = ValidationT . mapExceptT (mapStateT $ l f) . unValidationT
38-- | Map with 'Monoid' instance which 'mappend' its values
57-- | Map with 'Monoid' instance which 'mappend' its values
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.
64+-- [ MonoidMap $ M.fromList [(1, "foo"), (2, "hello, "), (3, "oh no")]
65+-- , MonoidMap $ M.fromList [(1, "bar"), (2, "world")]
68+-- MonoidMap (fromList [(1,"foobar"),(2,"hello, world"),(3,"oh no")])
39newtype MonoidMap k v = MonoidMap (Map k v)
69newtype MonoidMap k v = MonoidMap (Map k v)
40− deriving (Eq, Ord, Show, Arbitrary)
70+ deriving (Eq, Ord, Show, Arbitrary, Foldable)
42makePrisms ''MonoidMap
72makePrisms ''MonoidMap
@@ -48,14 +78,14 @@ instance (Ord k) => Ixed (MonoidMap k v) where
48instance (Ord k) => At (MonoidMap k v) where
78instance (Ord k) => At (MonoidMap k v) where
49 at key = _MonoidMap . at key
79 at key = _MonoidMap . at key
81+#if MIN_VERSION_base(4,11,0)
51−instance (Ord k, S.Semigroup v) => S.Semigroup (MonoidMap k v) where
82+instance (Ord k, Semigroup v) => Semigroup (MonoidMap k v) where
52− (MonoidMap a) <> (MonoidMap b) =
83+ (<>) = mmAppend
53− MonoidMap $ M.unionWith (S.<>) a b
84+#endif
55instance (Ord k, Monoid v) => Monoid (MonoidMap k v) where
86instance (Ord k, Monoid v) => Monoid (MonoidMap k v) where
56 mempty = MonoidMap M.empty
87 mempty = MonoidMap M.empty
57− mappend (MonoidMap a) (MonoidMap b) =
88+ mappend = mmAppend
58− MonoidMap $ M.unionWith (<>) a b
60instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
90instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
61 toJSON (MonoidMap m) = toJSON $ L.map toObj $ M.toList m
91 toJSON (MonoidMap m) = toJSON $ L.map toObj $ M.toList m
@@ -65,7 +95,7 @@ instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
65 , "value" .= v ]
95 , "value" .= v ]
67instance (Ord k, FromJSON k, FromJSON v) => FromJSON (MonoidMap k v) where
97instance (Ord k, FromJSON k, FromJSON v) => FromJSON (MonoidMap k v) where
68− parseJSON v = withArray "MonoidMap" go v
98+ parseJSON = withArray "MonoidMap" go
70 go arr = do
100 go arr = do
71 keyvals <- traverse fromObj arr
101 keyvals <- traverse fromObj arr
@@ -75,35 +105,67 @@ instance (Ord k, FromJSON k, FromJSON v) => FromJSON (MonoidMap k v) where
75 val <- obj .: "value"
105 val <- obj .: "value"
76 return (key, val)
106 return (key, val)
108+#if MIN_VERSION_base(4,11,0)
109+mmAppend :: (Ord k, Semigroup v) => MonoidMap k v -> MonoidMap k v -> MonoidMap k v
111+mmAppend :: (Ord k, Monoid v) => MonoidMap k v -> MonoidMap k v -> MonoidMap k v
113+mmAppend (MonoidMap a) (MonoidMap b) = MonoidMap $ M.unionWith (<>) a b
78−-- | Convenient for 'vZoom' as first artument. Will prevent generation
115+-- | Convenient for 'vZoom' as first argument. Will prevent generation
79−-- of map with 'mempty' values
116+-- of map with 'mempty' values.
80mmSingleton :: (Eq v, Monoid v, Ord k) => k -> v -> MonoidMap k v
117mmSingleton :: (Eq v, Monoid v, Ord k) => k -> v -> MonoidMap k v
119+ | v == mempty = mempty
81−mmSingleton k = memptyWrap mempty $ MonoidMap . M.singleton k
120+ | otherwise = MonoidMap . M.singleton k $ v
83−-- | Set given value to 'mempty'
122+-- | Sets given value to 'mempty'.
84setMempty :: (Monoid s) => ASetter' s a -> a -> s
123setMempty :: (Monoid s) => ASetter' s a -> a -> s
85setMempty setter a = set setter a mempty
124setMempty setter a = set setter a mempty
87−memptyWrap :: (Eq a, Monoid a) => b -> (a -> b) -> a -> b
126+neConcat :: Foldable f => (a -> a -> a) -> f a -> Maybe a
88−memptyWrap b f a
127+neConcat f a
89− | a == mempty = b
128+ | F.null a = Nothing
90− | otherwise = f a
129+ | otherwise = Just $ F.foldr1 f a
92−-- | If given container is not 'mempty', then use given function to
93−-- append all its elements and return 'Just' result
95− :: (Foldable f, Eq (f a), Monoid a, Monoid (f a))
99−neConcat f = memptyWrap Nothing (Just . F.foldl' f mempty)
131+-- | Returns the strings, concatanated with @", "@ if the list is not empty.
133+-- Returns Nothing if the list is empty
135+-- >>> textErrors ["foo", "bar"]
138+-- >>> textErrors ["foo"]
101textErrors :: [Text] -> Maybe Text
143textErrors :: [Text] -> Maybe Text
102textErrors = neConcat (\a b -> a <> ", " <> b)
144textErrors = neConcat (\a b -> a <> ", " <> b)
104−-- | Returns `mempty` instead of error if no warnings was occured. So, your
146+-- | Returns 'mempty' instead of error if no warnings have occured.
105−-- error should have `Eq` instance to detect that any error was occured. Returns
106−-- Nothing for second element of tuple if compuration was interruped by 'vError'
147+-- Returns 'Nothing' as the second element of tuple if computation was
148+-- interrupted by 'vError'.
150+-- Returns all concatenated errors and warnings and the result if no
151+-- errors have occured (warnings could have occured).
154+-- runValidationT $ do
155+-- vWarning ["warning1"]
157+-- vWarning ["warning2"]
160+-- (["error","warning1"],Nothing)
163+-- runValidationT $ do
164+-- vWarning ["warning1"]
165+-- vWarning ["warning2"]
168+-- (["warning1","warning2"],Just 8)
107runValidationT :: (Monoid e, Monad m) => ValidationT e m a -> m (e, Maybe a)
169runValidationT :: (Monoid e, Monad m) => ValidationT e m a -> m (e, Maybe a)
108runValidationT (ValidationT m) = do
170runValidationT (ValidationT m) = do
109 (res, warnings) <- runStateT (runExceptT m) mempty
171 (res, warnings) <- runStateT (runExceptT m) mempty
@@ -111,6 +173,25 @@ runValidationT (ValidationT m) = do
111 Left err -> (err <> warnings, Nothing)
173 Left err -> (err <> warnings, Nothing)
112 Right a -> (warnings, Just a)
174 Right a -> (warnings, Just a)
176+-- | Like 'runValidationT' but doesn't return the result
177+-- if any warning has occured.
180+-- runValidationTEither $ do
181+-- vWarning ["warning1"]
183+-- vWarning ["warning2"]
186+-- Left ["error","warning1"]
189+-- runValidationTEither $ do
190+-- vWarning ["warning1"]
191+-- vWarning ["warning2"]
194+-- Left ["warning1","warning2"]
114runValidationTEither
195runValidationTEither
115 :: (Monoid e, Eq e, Monad m)
196 :: (Monoid e, Eq e, Monad m)
116 => ValidationT e m a
197 => ValidationT e m a
@@ -121,28 +202,71 @@ runValidationTEither action = do
121 Just a | err == mempty -> Right a
202 Just a | err == mempty -> Right a
122 _ -> Left err
203 _ -> Left err
205+-- | Like 'runValidationTEither', but takes an error handler instead of
206+-- returning errors and warnings.
209+-- handleValidationT (\_ -> return 11) $ do
210+-- vWarning ["warning1"]
212+-- vWarning ["warning2"]
218+-- handleValidationT (\_ -> return 11) $ do
219+-- vWarning ["warning1"]
220+-- vWarning ["warning2"]
124handleValidationT
224handleValidationT
125 :: (Monoid e, Monad m, Eq e)
225 :: (Monoid e, Monad m, Eq e)
126 => (e -> m a)
226 => (e -> m a)
127 -> ValidationT e m a
227 -> ValidationT e m a
129−handleValidationT handler action = do
229+handleValidationT handler action =
130 runValidationTEither action >>= either handler return
230 runValidationTEither action >>= either handler return
132−-- | Stops further execution of validation
232+-- | Stops further execution and appends the given error.
133vError :: (Monad m) => e -> ValidationT e m a
233vError :: (Monad m) => e -> ValidationT e m a
134vError e = ValidationT $ throwError e
234vError e = ValidationT $ throwError e
136−-- | Does not stop further execution, append warning to
236+-- | Does not stop further execution and appends the given warning.
137vWarning :: (Monad m, Monoid e) => e -> ValidationT e m ()
237vWarning :: (Monad m, Monoid e) => e -> ValidationT e m ()
138vWarning e = ValidationT $ modify' (<> e)
238vWarning e = ValidationT $ modify' (<> e)
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.
140vErrorL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m x
243vErrorL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m x
141vErrorL l a = vError $ setMempty l a
244vErrorL l a = vError $ setMempty l a
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.
143vWarningL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m ()
249vWarningL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m ()
144vWarningL l a = vWarning $ setMempty l a
250vWarningL l a = vWarning $ setMempty l a
252+-- | Allows you apply a transformation to the "e" in "ValidationT e m x".
255+--runValidationT . vZoom (Data.Map.singleton "password errors") $ do
256+-- vWarning ["warning1"]
258+-- vWarning ["warning2"]
261+-- (fromList [("password errors",["error","warning1"])],Nothing)
264+-- runValidationT . vZoom (Data.Map.singleton "password errors") $ do
265+-- vWarning ["warning1"]
266+-- vWarning ["warning2"]
269+-- (fromList [("password errors",["warning1","warning2"])],Just 8)
147 :: (Monad m, Monoid a, Monoid b)
271 :: (Monad m, Monoid a, Monoid b)
148 => (a -> b)
272 => (a -> b)
@@ -152,11 +276,12 @@ vZoom up action = do
152 (err, res) <- lift $ runValidationT action
276 (err, res) <- lift $ runValidationT action
153 case res of
277 case res of
154 Nothing -> vError $ up err
278 Nothing -> vError $ up err
155− Just a -> vWarning (up err) *> return a
279+ Just a -> vWarning (up err) $> a
281+-- | Like 'vZoom' but takes a setter instead of a function.
158 :: (Monad m, Monoid a, Monoid b)
283 :: (Monad m, Monoid a, Monoid b)
159 => ASetter' b a
284 => ASetter' b a
160 -> ValidationT a m x
285 -> ValidationT a m x
161 -> ValidationT b m x
286 -> ValidationT b m x
162−vZoomL l action = vZoom (setMempty l) action
287+vZoomL l = vZoom (setMempty l)