{-# LANGUAGE GADTs, DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
module Propellor.Types.Info (
Info(..),
InfoEntry(..),
IsInfo(..),
PropagateInfo(..),
addInfo,
toInfo,
fromInfo,
mapInfo,
InfoVal(..),
fromInfoVal,
Typeable,
) where
import Data.Dynamic
import Data.Maybe
import Data.Monoid
import qualified Data.Semigroup as Sem
import qualified Data.Typeable as T
import Prelude
newtype Info = Info [InfoEntry]
deriving (Sem.Semigroup, Monoid, Show)
data InfoEntry where
InfoEntry :: (IsInfo v, Typeable v) => v -> InfoEntry
instance Show InfoEntry where
show (InfoEntry v) = show v
extractInfoEntry :: Typeable v => InfoEntry -> Maybe v
extractInfoEntry (InfoEntry v) = T.cast v
class (Typeable v, Monoid v, Show v) => IsInfo v where
propagateInfo :: v -> PropagateInfo
data PropagateInfo
= PropagateInfo Bool
| PropagatePrivData
addInfo :: IsInfo v => Info -> v -> Info
addInfo (Info l) v = Info (l++[InfoEntry v])
toInfo :: IsInfo v => v -> Info
toInfo = addInfo mempty
fromInfo :: IsInfo v => Info -> v
fromInfo (Info l) = mconcat (mapMaybe extractInfoEntry l)
mapInfo :: IsInfo v => (v -> v) -> Info -> Info
mapInfo f (Info l) = Info (map go l)
where
go i = case extractInfoEntry i of
Nothing -> i
Just v -> InfoEntry (f v)
data InfoVal v = NoInfoVal | InfoVal v
deriving (Typeable, Show)
instance Sem.Semigroup (InfoVal v) where
_ <> v@(InfoVal _) = v
v <> NoInfoVal = v
instance Monoid (InfoVal v) where
mempty = NoInfoVal
mappend = (Sem.<>)
instance (Typeable v, Show v) => IsInfo (InfoVal v) where
propagateInfo _ = PropagateInfo False
fromInfoVal :: InfoVal v -> Maybe v
fromInfoVal NoInfoVal = Nothing
fromInfoVal (InfoVal v) = Just v