module Data.GI.CodeGen.Type
( Type(..)
, BasicType(..)
, TypeRep
, con
, con0
, typeShow
, typeConName
, io
, ptr
, funptr
, maybeT
) where
import Data.Monoid ((<>))
import qualified Data.Text as T
import Data.Text (Text)
import Data.GI.GIR.BasicTypes (Type(..), BasicType(..))
data TypeRep = TypeRep { typeCon :: TypeCon
, typeConArgs :: [TypeRep]
} deriving (Eq)
data TypeCon = TupleCon
| ListCon
| TextualCon Text
deriving (Eq)
typeShow :: TypeRep -> Text
typeShow (TypeRep TupleCon args) =
"(" <> T.intercalate ", " (map typeShow args) <> ")"
typeShow (TypeRep ListCon args) =
"[" <> T.intercalate ", " (map typeShow args) <> "]"
typeShow (TypeRep (TextualCon con) args) =
T.intercalate " " (con : map (parenthesize . typeShow) args)
where parenthesize :: Text -> Text
parenthesize s = if T.any (== ' ') s
then "(" <> s <> ")"
else s
typeConName :: TypeRep -> Text
typeConName (TypeRep TupleCon _) = "(,)"
typeConName (TypeRep ListCon _) = "[,]"
typeConName (TypeRep (TextualCon s) _) = s
con :: Text -> [TypeRep] -> TypeRep
con "[]" xs = TypeRep {typeCon = ListCon, typeConArgs = xs }
con "(,)" xs = TypeRep {typeCon = TupleCon, typeConArgs = xs }
con s xs = TypeRep {typeCon = TextualCon s, typeConArgs = xs}
con0 :: Text -> TypeRep
con0 c = con c []
io :: TypeRep -> TypeRep
io t = "IO" `con` [t]
ptr :: TypeRep -> TypeRep
ptr t = "Ptr" `con` [t]
funptr :: TypeRep -> TypeRep
funptr t = "FunPtr" `con` [t]
maybeT :: TypeRep -> TypeRep
maybeT t = "Maybe" `con` [t]