{- |
Support for creating Show instances using the accessors.
-}
module Data.Accessor.Show (field, showsPrec) where

import qualified Data.Accessor.Basic as Accessor

import Data.Maybe (catMaybes)

-- import qualified Text.Show as Show
import qualified Prelude as Show
import Prelude hiding (showsPrec)


toMaybe :: Bool -> a -> Maybe a
toMaybe :: forall a. Bool -> a -> Maybe a
toMaybe Bool
False a
_ = forall a. Maybe a
Nothing
toMaybe Bool
True  a
x = forall a. a -> Maybe a
Just a
x

field :: (Show a, Eq a) =>
   String -> Accessor.T r a -> r -> r -> Maybe ShowS
field :: forall a r.
(Show a, Eq a) =>
String -> T r a -> r -> r -> Maybe ShowS
field String
name T r a
acc r
deflt r
record =
   let x :: a
x = forall r a. T r a -> r -> a
Accessor.get T r a
acc r
record
   in  forall a. Bool -> a -> Maybe a
toMaybe
          (a
x forall a. Eq a => a -> a -> Bool
/= forall r a. T r a -> r -> a
Accessor.get T r a
acc r
deflt)
          (String -> ShowS
showString String
name forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> ShowS
showString String
" ^= " forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Show a => Int -> a -> ShowS
Show.showsPrec Int
5 a
x)

showsPrec ::
   [r -> r -> Maybe ShowS] -> String -> r -> Int -> r -> ShowS
showsPrec :: forall r.
[r -> r -> Maybe ShowS] -> String -> r -> Int -> r -> ShowS
showsPrec [r -> r -> Maybe ShowS]
fields String
defltName r
deflt Int
p r
record =
   let calls :: [ShowS]
calls =
          forall a. [Maybe a] -> [a]
catMaybes forall a b. (a -> b) -> a -> b
$
          forall a b. (a -> b) -> [a] -> [b]
map (\r -> r -> Maybe ShowS
f -> r -> r -> Maybe ShowS
f r
deflt r
record) forall a b. (a -> b) -> a -> b
$
          [r -> r -> Maybe ShowS]
fields
   in  if forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ShowS]
calls
         then String -> ShowS
showString String
defltName
         else Bool -> ShowS -> ShowS
showParen (Int
pforall a. Ord a => a -> a -> Bool
>Int
0)
                 (forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr
                     (\ShowS
acc ShowS
s -> ShowS
acc forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> ShowS
showString String
" $ " forall b c a. (b -> c) -> (a -> b) -> a -> c
. ShowS
s)
                     (String -> ShowS
showString String
defltName)
                     [ShowS]
calls)