module Data.Comp.Derive.ExpFunctor
(
ExpFunctor,
instanceExpFunctor
) where
import Data.Comp.ExpFunctor
import Data.Comp.Derive.Utils
import Language.Haskell.TH
instanceExpFunctor :: Name -> Q [Dec]
instanceExpFunctor fname = do
TyConI (DataD _ name args constrs _) <- abstractNewtypeQ $ reify fname
let fArg :: Name = tyVarBndrName $ last args
let argNames = map (VarT . tyVarBndrName) (init args)
let complType = foldl AppT (ConT name) argNames
let classType = AppT (ConT ''ExpFunctor) complType
constrs' :: [(Name,[Type])] <- mapM normalConExp constrs
xmapDecl <- funD 'xmap (map (xmapClause fArg) constrs')
return [InstanceD [] classType [xmapDecl]]
where xmapClause :: Name -> (Name,[Type]) -> ClauseQ
xmapClause fArg (constr, args) = do
fn <- newName "_f"
gn <- newName "_g"
varNs <- newNames (length args) "x"
let f = varE fn
let g = varE gn
let fp = VarP fn
let gp = VarP gn
let pat = ConP constr $ map VarP varNs
body <- xmapArgs fArg f g (zip varNs args) (conE constr)
return $ Clause [fp, gp, pat] (NormalB body) []
xmapArgs :: Name -> ExpQ -> ExpQ -> [(Name, Type)] -> ExpQ -> ExpQ
xmapArgs _ _ _ [] acc =
acc
xmapArgs fArg f g ((x,tp):tps) acc =
xmapArgs fArg f g tps (acc `appE`
(xmapArg fArg tp f g `appE` varE x))
xmapArg :: Name -> Type -> ExpQ -> ExpQ -> ExpQ
xmapArg fArg tp f g =
if not $ containsType tp (VarT fArg) then
[|id|]
else
case tp of
ForallT vars _ tp' ->
if any ((==) fArg . tyVarBndrName) vars then
[|id|]
else
xmapArg fArg tp' f g
VarT a ->
if a == fArg then f else [|id|]
ConT _ ->
[|id|]
AppT (AppT ArrowT tp1) tp2 -> do
xn <- newName "x"
let ftp1 = xmapArg fArg tp1 g f
let ftp2 = xmapArg fArg tp2 f g
lamE [varP xn]
(infixE (Just ftp2)
[|(.)|]
(Just $ infixE (Just $ varE xn)
[|(.)|]
(Just ftp1)))
AppT _ tp' ->
[|fmap|] `appE` xmapArg fArg tp' f g
SigT tp' _ ->
xmapArg fArg tp' f g
_ ->
error $ "unsopported type: " ++ show tp