{-# LANGUAGE FlexibleInstances, Trustworthy #-}

{-
  This module is part of Chatty.
  Copyleft (c) 2014 Marvin Cohrs

  All wrongs reversed. Sharing is an act of love, not crime.
  Please share Antisplice with everyone you like.

  Chatty is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Chatty is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Chatty. If not, see <http://www.gnu.org/licenses/>.
-}

module Text.Chatty.Templates where

import Language.Haskell.TH

-- | Returns a TypeQ from a name
strToType :: Name -> Q Type
strToType :: Name -> Q Type
strToType Name
s = do
  TyConI Dec
d <- Name -> Q Info
reify Name
s
  case Dec
d of
    DataD Cxt
_ Name
n [TyVarBndr]
_ Maybe Type
_ [Con]
_ [DerivClause]
_ -> Name -> Q Type
conT (Name -> Q Type) -> Name -> Q Type
forall a b. (a -> b) -> a -> b
$ Name -> Name
simpleName Name
n
    NewtypeD Cxt
_ Name
n [TyVarBndr]
_ Maybe Type
_ Con
_ [DerivClause]
_ -> Name -> Q Type
conT (Name -> Q Type) -> Name -> Q Type
forall a b. (a -> b) -> a -> b
$ Name -> Name
simpleName Name
n
    TySynD Name
n [TyVarBndr]
_ Type
_ -> Name -> Q Type
conT (Name -> Q Type) -> Name -> Q Type
forall a b. (a -> b) -> a -> b
$ Name -> Name
simpleName Name
n
  where
    simpleName :: Name -> Name
    simpleName :: Name -> Name
simpleName Name
nm =
      let s :: String
s = Name -> String
nameBase Name
nm
      in case (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/=Char
':') String
s of
        []          -> String -> Name
mkName String
s
        Char
_:[]        -> String -> Name
mkName String
s
        Char
_:String
t         -> String -> Name
mkName String
t