2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 This module converts Template Haskell syntax into HsSyn
9 module Convert( convertToHsExpr, convertToHsDecls, convertToHsType ) where
11 #include "HsVersions.h"
13 import Language.Haskell.TH as TH
14 import Language.Haskell.TH.Syntax as TH
17 import RdrName ( RdrName, mkRdrUnqual, mkRdrQual, mkOrig, nameRdrName, getRdrName )
18 import Module ( ModuleName, mkModuleName )
19 import RdrHsSyn ( mkHsIntegral, mkHsFractional, mkClassDecl, mkTyData )
20 import Name ( mkInternalName )
21 import qualified OccName
22 import SrcLoc ( SrcLoc, generatedSrcLoc, noLoc, unLoc, Located(..),
23 noSrcSpan, SrcSpan, srcLocSpan, noSrcLoc )
25 import TysWiredIn ( unitTyCon, tupleTyCon, trueDataCon, falseDataCon )
26 import BasicTypes( Boxity(..), RecFlag(Recursive), NewOrData(..) )
27 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
29 import HsDecls ( CImportSpec(..), ForeignImport(..), ForeignExport(..),
31 import FastString( FastString, mkFastString, nilFS )
32 import Char ( ord, isAscii, isAlphaNum, isAlpha )
33 import List ( partition )
34 import Unique ( Unique, mkUniqueGrimily )
35 import ErrUtils (Message)
36 import GLAEXTS ( Int#, Int(..) )
37 import Bag ( emptyBag, consBag )
41 -------------------------------------------------------------------
42 convertToHsDecls :: [TH.Dec] -> [Either (LHsDecl RdrName) Message]
43 convertToHsDecls ds = map cvt_ltop ds
45 mk_con con = L loc0 $ case con of
47 -> ConDecl (noLoc (cName c)) noExistentials noContext
48 (PrefixCon (map mk_arg strtys))
50 -> ConDecl (noLoc (cName c)) noExistentials noContext
51 (RecCon (map mk_id_arg varstrtys))
53 -> ConDecl (noLoc (cName c)) noExistentials noContext
54 (InfixCon (mk_arg st1) (mk_arg st2))
56 mk_arg (IsStrict, ty) = noLoc $ BangType HsStrict (cvtType ty)
57 mk_arg (NotStrict, ty) = noLoc $ BangType HsNoBang (cvtType ty)
59 mk_id_arg (i, IsStrict, ty)
60 = (noLoc (vName i), noLoc $ BangType HsStrict (cvtType ty))
61 mk_id_arg (i, NotStrict, ty)
62 = (noLoc (vName i), noLoc $ BangType HsNoBang (cvtType ty))
64 mk_derivs [] = Nothing
65 mk_derivs cs = Just (noLoc [noLoc $ HsClassP (tconName c) [] | c <- cs])
67 cvt_ltop :: TH.Dec -> Either (LHsDecl RdrName) Message
68 cvt_ltop d = case cvt_top d of
69 Left d -> Left (L loc0 d)
72 cvt_top :: TH.Dec -> Either (HsDecl RdrName) Message
73 cvt_top d@(TH.ValD _ _ _) = Left $ Hs.ValD (unLoc (cvtd d))
74 cvt_top d@(TH.FunD _ _) = Left $ Hs.ValD (unLoc (cvtd d))
76 cvt_top (TySynD tc tvs rhs)
77 = Left $ TyClD (TySynonym (noLoc (tconName tc)) (cvt_tvs tvs) (cvtType rhs))
79 cvt_top (DataD ctxt tc tvs constrs derivs)
80 = Left $ TyClD (mkTyData DataType
81 (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs)
85 cvt_top (NewtypeD ctxt tc tvs constr derivs)
86 = Left $ TyClD (mkTyData NewType
87 (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs)
91 cvt_top (ClassD ctxt cl tvs decs)
92 = Left $ TyClD (mkClassDecl (cvt_context ctxt, noLoc (tconName cl), cvt_tvs tvs)
96 (binds,sigs) = cvtBindsAndSigs decs
98 cvt_top (InstanceD tys ty decs)
99 = Left $ InstD (InstDecl (noLoc inst_ty) binds sigs)
101 (binds, sigs) = cvtBindsAndSigs decs
102 inst_ty = mkImplicitHsForAllTy (cvt_context tys) (noLoc (HsPredTy (cvt_pred ty)))
104 cvt_top (TH.SigD nm typ) = Left $ Hs.SigD (Sig (noLoc (vName nm)) (cvtType typ))
106 cvt_top (ForeignD (ImportF callconv safety from nm typ))
108 Just (c_header, cis) ->
109 let i = CImport callconv' safety' c_header nilFS cis
110 in Left $ ForD (ForeignImport (noLoc (vName nm)) (cvtType typ) i False)
111 Nothing -> Right $ text (show from)
112 <+> ptext SLIT("is not a valid ccall impent")
113 where callconv' = case callconv of
115 StdCall -> StdCallConv
116 safety' = case safety of
118 Safe -> PlaySafe False
119 Threadsafe -> PlaySafe True
120 parsed = parse_ccall_impent (TH.nameBase nm) from
122 cvt_top (ForeignD (ExportF callconv as nm typ))
123 = let e = CExport (CExportStatic (mkFastString as) callconv')
124 in Left $ ForD (ForeignExport (noLoc (vName nm)) (cvtType typ) e False)
125 where callconv' = case callconv of
127 StdCall -> StdCallConv
129 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
130 parse_ccall_impent nm s
131 = case lex_ccall_impent s of
132 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
133 Just ["wrapper"] -> Just (nilFS, CWrapper)
134 Just ("static":ts) -> parse_ccall_impent_static nm ts
135 Just ts -> parse_ccall_impent_static nm ts
138 parse_ccall_impent_static :: String
140 -> Maybe (FastString, CImportSpec)
141 parse_ccall_impent_static nm ts
142 = let ts' = case ts of
143 [ "&", cid] -> [ cid]
144 [fname, "&" ] -> [fname ]
145 [fname, "&", cid] -> [fname, cid]
148 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
149 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
150 [ ] -> Just (nilFS, mk_cid nm)
151 [fname ] -> Just (mkFastString fname, mk_cid nm)
153 where is_cid :: String -> Bool
154 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
155 mk_cid :: String -> CImportSpec
156 mk_cid = CFunction . StaticTarget . mkFastString
158 lex_ccall_impent :: String -> Maybe [String]
159 lex_ccall_impent "" = Just []
160 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
161 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
162 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
163 lex_ccall_impent xs = case span is_valid xs of
165 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
166 where is_valid :: Char -> Bool
167 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
173 -------------------------------------------------------------------
174 convertToHsExpr :: TH.Exp -> LHsExpr RdrName
175 convertToHsExpr = cvtl
177 cvtl e = noLoc (cvt e)
179 cvt (VarE s) = HsVar (vName s)
180 cvt (ConE s) = HsVar (cName s)
182 | overloadedLit l = HsOverLit (cvtOverLit l)
183 | otherwise = HsLit (cvtLit l)
185 cvt (AppE x y) = HsApp (cvtl x) (cvtl y)
186 cvt (LamE ps e) = HsLam (mkSimpleMatch (map cvtlp ps) (cvtl e) void)
187 cvt (TupE [e]) = cvt e
188 cvt (TupE es) = ExplicitTuple(map cvtl es) Boxed
189 cvt (CondE x y z) = HsIf (cvtl x) (cvtl y) (cvtl z)
190 cvt (LetE ds e) = HsLet (cvtdecs ds) (cvtl e)
191 cvt (CaseE e ms) = HsCase (cvtl e) (map cvtm ms)
192 cvt (DoE ss) = HsDo DoExpr (cvtstmts ss) [] void
193 cvt (CompE ss) = HsDo ListComp (cvtstmts ss) [] void
194 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
195 cvt (ListE xs) = ExplicitList void (map cvtl xs)
196 cvt (InfixE (Just x) s (Just y))
197 = HsPar (noLoc $ OpApp (cvtl x) (cvtl s) undefined (cvtl y))
198 cvt (InfixE Nothing s (Just y)) = SectionR (cvtl s) (cvtl y)
199 cvt (InfixE (Just x) s Nothing ) = SectionL (cvtl x) (cvtl s)
200 cvt (InfixE Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
201 cvt (SigE e t) = ExprWithTySig (cvtl e) (cvtType t)
202 cvt (RecConE c flds) = RecordCon (noLoc (cName c)) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
203 cvt (RecUpdE e flds) = RecordUpd (cvtl e) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
205 cvtdecs :: [TH.Dec] -> [HsBindGroup RdrName]
207 cvtdecs ds = [HsBindGroup binds sigs Recursive]
209 (binds, sigs) = cvtBindsAndSigs ds
212 = (cvtds non_sigs, map cvtSig sigs)
214 (sigs, non_sigs) = partition sigP ds
216 cvtSig (TH.SigD nm typ) = noLoc (Hs.Sig (noLoc (vName nm)) (cvtType typ))
218 cvtds :: [TH.Dec] -> LHsBinds RdrName
220 cvtds (d:ds) = cvtd d `consBag` cvtds ds
222 cvtd :: TH.Dec -> LHsBind RdrName
223 -- Used only for declarations in a 'let/where' clause,
224 -- not for top level decls
225 cvtd (TH.ValD (TH.VarP s) body ds)
226 = noLoc $ FunBind (noLoc (vName s)) False [cvtclause (Clause [] body ds)]
228 = noLoc $ FunBind (noLoc (vName nm)) False (map cvtclause cls)
229 cvtd (TH.ValD p body ds)
230 = noLoc $ PatBind (cvtlp p) (GRHSs (cvtguard body) (cvtdecs ds) void)
232 cvtd d = cvtPanic "Illegal kind of declaration in where clause"
233 (text (show (TH.ppr d)))
236 cvtclause :: TH.Clause -> Hs.LMatch RdrName
237 cvtclause (Clause ps body wheres)
238 = noLoc $ Hs.Match (map cvtlp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
242 cvtdd :: Range -> ArithSeqInfo RdrName
243 cvtdd (FromR x) = (From (cvtl x))
244 cvtdd (FromThenR x y) = (FromThen (cvtl x) (cvtl y))
245 cvtdd (FromToR x y) = (FromTo (cvtl x) (cvtl y))
246 cvtdd (FromThenToR x y z) = (FromThenTo (cvtl x) (cvtl y) (cvtl z))
249 cvtstmts :: [TH.Stmt] -> [Hs.LStmt RdrName]
250 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
251 cvtstmts [NoBindS e] = [nlResultStmt (cvtl e)] -- when its the last element use ResultStmt
252 cvtstmts (NoBindS e : ss) = nlExprStmt (cvtl e) : cvtstmts ss
253 cvtstmts (TH.BindS p e : ss) = nlBindStmt (cvtlp p) (cvtl e) : cvtstmts ss
254 cvtstmts (TH.LetS ds : ss) = nlLetStmt (cvtdecs ds) : cvtstmts ss
255 cvtstmts (TH.ParS dss : ss) = nlParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
257 cvtm :: TH.Match -> Hs.LMatch RdrName
258 cvtm (TH.Match p body wheres)
259 = noLoc (Hs.Match [cvtlp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void))
261 cvtguard :: TH.Body -> [LGRHS RdrName]
262 cvtguard (GuardedB pairs) = map cvtpair pairs
263 cvtguard (NormalB e) = [noLoc (GRHS [ nlResultStmt (cvtl e) ])]
265 cvtpair :: (TH.Exp,TH.Exp) -> LGRHS RdrName
266 cvtpair (x,y) = noLoc (GRHS [nlBindStmt truePat (cvtl x),
267 nlResultStmt (cvtl y)])
269 cvtOverLit :: Lit -> HsOverLit
270 cvtOverLit (IntegerL i) = mkHsIntegral i
271 cvtOverLit (RationalL r) = mkHsFractional r
272 -- An Integer is like an an (overloaded) '3' in a Haskell source program
273 -- Similarly 3.5 for fractionals
275 cvtLit :: Lit -> HsLit
276 cvtLit (IntPrimL i) = HsIntPrim i
277 cvtLit (FloatPrimL f) = HsFloatPrim f
278 cvtLit (DoublePrimL f) = HsDoublePrim f
279 cvtLit (CharL c) = HsChar c
280 cvtLit (StringL s) = HsString (mkFastString s)
282 cvtlp :: TH.Pat -> Hs.LPat RdrName
283 cvtlp pat = noLoc (cvtp pat)
285 cvtp :: TH.Pat -> Hs.Pat RdrName
287 | overloadedLit l = NPatIn (cvtOverLit l) Nothing -- Not right for negative
288 -- patterns; need to think
290 | otherwise = Hs.LitPat (cvtLit l)
291 cvtp (TH.VarP s) = Hs.VarPat(vName s)
292 cvtp (TupP [p]) = cvtp p
293 cvtp (TupP ps) = TuplePat (map cvtlp ps) Boxed
294 cvtp (ConP s ps) = ConPatIn (noLoc (cName s)) (PrefixCon (map cvtlp ps))
295 cvtp (TildeP p) = LazyPat (cvtlp p)
296 cvtp (TH.AsP s p) = AsPat (noLoc (vName s)) (cvtlp p)
297 cvtp TH.WildP = WildPat void
298 cvtp (RecP c fs) = ConPatIn (noLoc (cName c)) $ Hs.RecCon (map (\(s,p) -> (noLoc (vName s),cvtlp p)) fs)
299 cvtp (ListP ps) = ListPat (map cvtlp ps) void
301 -----------------------------------------------------------
302 -- Types and type variables
304 cvt_tvs :: [TH.Name] -> [LHsTyVarBndr RdrName]
305 cvt_tvs tvs = map (noLoc . UserTyVar . tName) tvs
307 cvt_context :: Cxt -> LHsContext RdrName
308 cvt_context tys = noLoc (map cvt_pred tys)
310 cvt_pred :: TH.Type -> LHsPred RdrName
311 cvt_pred ty = case split_ty_app ty of
312 (ConT tc, tys) -> noLoc (HsClassP (tconName tc) (map cvtType tys))
313 (VarT tv, tys) -> noLoc (HsClassP (tName tv) (map cvtType tys))
314 other -> cvtPanic "Malformed predicate" (text (show (TH.ppr ty)))
316 convertToHsType = cvtType
318 cvtType :: TH.Type -> LHsType RdrName
319 cvtType ty = trans (root ty [])
320 where root (AppT a b) zs = root a (cvtType b : zs)
323 trans (TupleT n,args)
324 | length args == n = noLoc (HsTupleTy Boxed args)
325 | n == 0 = foldl nlHsAppTy (nlHsTyVar (getRdrName unitTyCon)) args
326 | otherwise = foldl nlHsAppTy (nlHsTyVar (getRdrName (tupleTyCon Boxed n))) args
327 trans (ArrowT, [x,y]) = nlHsFunTy x y
328 trans (ListT, [x]) = noLoc (HsListTy x)
330 trans (VarT nm, args) = foldl nlHsAppTy (nlHsTyVar (tName nm)) args
331 trans (ConT tc, args) = foldl nlHsAppTy (nlHsTyVar (tconName tc)) args
333 trans (ForallT tvs cxt ty, []) = noLoc $ mkExplicitHsForAllTy
334 (cvt_tvs tvs) (cvt_context cxt) (cvtType ty)
336 split_ty_app :: TH.Type -> (TH.Type, [TH.Type])
337 split_ty_app ty = go ty []
339 go (AppT f a) as = go f (a:as)
342 -----------------------------------------------------------
344 sigP (TH.SigD _ _) = True
348 -----------------------------------------------------------
349 cvtPanic :: String -> SDoc -> b
350 cvtPanic herald thing
351 = pprPanic herald (thing $$ ptext SLIT("When splicing generated code into the program"))
353 -----------------------------------------------------------
354 -- some useful things
356 truePat = nlConPat (getRdrName trueDataCon) []
357 falsePat = nlConPat (getRdrName falseDataCon) []
359 overloadedLit :: Lit -> Bool
360 -- True for literals that Haskell treats as overloaded
361 overloadedLit (IntegerL l) = True
362 overloadedLit (RationalL l) = True
363 overloadedLit l = False
366 void = placeHolderType
369 loc0 = srcLocSpan generatedSrcLoc
371 --------------------------------------------------------------------
372 -- Turning Name back into RdrName
373 --------------------------------------------------------------------
376 vName :: TH.Name -> RdrName
377 vName = thRdrName OccName.varName
379 -- Constructor function names; this is Haskell source, hence srcDataName
380 cName :: TH.Name -> RdrName
381 cName = thRdrName OccName.srcDataName
383 -- Type variable names
384 tName :: TH.Name -> RdrName
385 tName = thRdrName OccName.tvName
387 -- Type Constructor names
388 tconName = thRdrName OccName.tcName
390 thRdrName :: OccName.NameSpace -> TH.Name -> RdrName
391 -- This turns a Name into a RdrName
392 -- The last case is slightly interesting. It constructs a
393 -- unique name from the unique in the TH thingy, so that the renamer
394 -- won't mess about. I hope. (Another possiblity would be to generate
395 -- "x_77" etc, but that could conceivably clash.)
397 thRdrName ns (TH.Name occ (TH.NameG ns' mod)) = mkOrig (mk_mod mod) (mk_occ ns occ)
398 thRdrName ns (TH.Name occ TH.NameS) = mkRdrUnqual (mk_occ ns occ)
399 thRdrName ns (TH.Name occ (TH.NameU uniq)) = nameRdrName (mkInternalName (mk_uniq uniq) (mk_occ ns occ) noSrcLoc)
401 mk_uniq :: Int# -> Unique
402 mk_uniq u = mkUniqueGrimily (I# u)
404 -- The packing and unpacking is rather turgid :-(
405 mk_occ :: OccName.NameSpace -> TH.OccName -> OccName.OccName
406 mk_occ ns occ = OccName.mkOccFS ns (mkFastString (TH.occString occ))
408 mk_mod :: TH.ModName -> ModuleName
409 mk_mod mod = mkModuleName (TH.modString mod)