Last active
July 2, 2017 13:42
-
-
Save Icelandjack/1f578e7103ff327cbcfb3426c005e26c to your computer and use it in GitHub Desktop.
Template Haskell deriving, first implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# Language InstanceSigs, ViewPatterns, TupleSections, GeneralizedNewtypeDeriving, TemplateHaskell, LambdaCase #-} | |
module D where | |
import Language.Haskell.TH | |
import Data.Coerce | |
deriveVia :: Name -> Name -> Name -> Q [Dec] | |
deriveVia className ty viaNewTy = do | |
a <- reify className | |
let | |
instanceHead, coerceType :: Type | |
instanceHead = ConT className `AppT` ConT ty | |
coerceType = ConT viaNewTy `AppT` ConT ty | |
methods :: [Dec] | |
methods = concatMap (g coerceType ty) (f a) | |
return [InstanceD [] instanceHead methods] | |
f :: Info -> [(Name, Name, Dec)] | |
f (ClassI (ClassD _ semigroup [getName -> m] [] methods) _) = | |
map (semigroup, m,) methods | |
f (ClassI d _) = error (show d) | |
removeForall = \case | |
ForallT _ _ ty -> removeForall ty | |
AppT f x -> removeForall f `AppT` removeForall x | |
SigT f x -> removeForall f `SigT` removeForall x | |
x -> x | |
g :: Type -> Name -> (Name, Name, Dec) -> [Dec] | |
g m_all underlying (semigroup, m, SigD methodName methodTy) | |
= [signature, definition] | |
where | |
signature :: Dec | |
signature = SigD methodName (removeWith (ConT underlying) ty) where | |
ForallT _ _ ty = methodTy | |
definition :: Dec | |
definition = | |
ValD (VarP methodName) | |
(NormalB body) | |
[] | |
body :: Exp | |
body = | |
VarE 'coerce | |
`AppE` | |
SigE (VarE methodName) | |
(removeForall (removeWith m_all methodTy)) | |
removeWith constructor = \case | |
AppT f x -> | |
AppT (removeWith constructor f) (removeWith constructor x) | |
ForallT tyVars ctxs ty | |
| let vars = [ var | var <- tyVars, getName var /= m ] | |
-> if null vars | |
then removeWith constructor ty | |
else ForallT | |
vars | |
[ ctx | ctx <- ctxs, ctx /= ClassP semigroup [VarT m] ] | |
(removeWith constructor ty) | |
ArrowT -> | |
ArrowT | |
VarT var | |
| var == m | |
-> constructor | |
| otherwise | |
-> VarT var | |
a -> a | |
getName :: TyVarBndr -> Name | |
getName = \case | |
PlainTV name -> name | |
KindedTV name _ -> name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works for most