{-# LANGUAGE TemplateHaskell, CPP #-}
module Data.Accessor.Template (
nameDeriveAccessors, deriveAccessors,
) where
import qualified Data.Accessor.Basic as Accessor
import Language.Haskell.TH.Syntax
import qualified Data.Traversable as Trav
import Data.List (nub, )
import Data.List.HT (viewR, )
import Data.Maybe (catMaybes, )
import Control.Monad (liftM, when, )
deriveAccessors :: Name -> Q [Dec]
deriveAccessors n = nameDeriveAccessors n stripUnderscore
stripUnderscore :: String -> Maybe String
stripUnderscore s = do
(stem,'_') <- viewR s
return stem
namedFields :: Con -> [VarStrictType]
namedFields (RecC _ fs) = fs
namedFields (ForallC _ _ c) = namedFields c
namedFields _ = []
nameDeriveAccessors :: Name -> (String -> Maybe String) -> Q [Dec]
nameDeriveAccessors t namer = do
info <- reify t
reified <- case info of
TyConI dec -> return dec
_ -> fail errmsg
(params, cons) <- case reified of
DataD _ _ params _ cons' _ -> return (params, cons')
NewtypeD _ _ params _ con' _ -> return (params, [con'])
_ -> fail errmsg
decs <- makeAccs params . nub $ concatMap namedFields cons
when (null decs) $ qReport False nodefmsg
return decs
where
errmsg = "Cannot derive accessors for name " ++ show t ++ " because"
++ "\n it is not a type declared with 'data' or 'newtype'"
++ "\n Did you remember to double-tick the type as in"
++ "\n $(deriveAccessors ''TheType)?"
nodefmsg = "Warning: No accessors generated from the name " ++ show t
++ "\n If you are using deriveAccessors rather than"
++ "\n nameDeriveAccessors, remember accessors are"
++ "\n only generated for fields ending with an underscore"
makeAccs :: [TyVarBndr] -> [VarStrictType] -> Q [Dec]
makeAccs params vars =
liftM (concat . catMaybes) $
mapM (\ (name,_,ftype) -> makeAccFromName name params ftype) vars
transformName :: Name -> Maybe Name
transformName (Name occ f) = do
n <- namer (occString occ)
return $ Name (mkOccName n) f
makeAccFromName :: Name -> [TyVarBndr] -> Type -> Q (Maybe [Dec])
makeAccFromName name params ftype =
Trav.mapM (makeAcc name params ftype) $ transformName name
#ifndef __HADDOCK__
makeAcc ::Name -> [TyVarBndr] -> Type -> Name -> Q [Dec]
makeAcc name params ftype accName = do
let params' = map (\x -> case x of (PlainTV n) -> n; (KindedTV n _) -> n) params
let appliedT = foldl AppT (ConT t) (map VarT params')
body <- [|
Accessor.fromSetGet
( \x s ->
$( return $ RecUpdE (VarE 's) [(name, VarE 'x)] ) )
( $( return $ VarE name ) )
|]
return
[ SigD accName (ForallT (map PlainTV params')
[] (AppT (AppT (ConT ''Accessor.T) appliedT) ftype))
, ValD (VarP accName) (NormalB body) []
]
#endif