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 hiding (sigP)
14 import Language.Haskell.TH.Syntax as TH
17 import qualified Class (FunDep)
18 import RdrName ( RdrName, mkRdrUnqual, mkRdrQual, mkOrig, nameRdrName, getRdrName )
19 import Module ( ModuleName, mkModuleName )
20 import RdrHsSyn ( mkHsIntegral, mkHsFractional, mkClassDecl, mkTyData )
21 import Name ( mkInternalName )
22 import qualified OccName
23 import SrcLoc ( SrcLoc, generatedSrcLoc, noLoc, unLoc, Located(..),
24 noSrcSpan, SrcSpan, srcLocSpan, noSrcLoc )
26 import TysWiredIn ( unitTyCon, tupleTyCon, trueDataCon, falseDataCon )
27 import BasicTypes( Boxity(..), RecFlag(Recursive) )
28 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
30 import HsDecls ( CImportSpec(..), ForeignImport(..), ForeignExport(..),
32 import FastString( FastString, mkFastString, nilFS )
33 import Char ( ord, isAscii, isAlphaNum, isAlpha )
34 import List ( partition )
35 import Unique ( Unique, mkUniqueGrimily )
36 import ErrUtils (Message)
37 import GLAEXTS ( Int#, Int(..) )
38 import Bag ( emptyBag, consBag )
42 -------------------------------------------------------------------
43 convertToHsDecls :: [TH.Dec] -> [Either (LHsDecl RdrName) Message]
44 convertToHsDecls ds = map cvt_ltop ds
46 mk_con con = L loc0 $ mk_nlcon con
48 mk_nlcon con = case con of
50 -> ConDecl (noLoc (cName c)) noExistentials noContext
51 (PrefixCon (map mk_arg strtys))
53 -> ConDecl (noLoc (cName c)) noExistentials noContext
54 (RecCon (map mk_id_arg varstrtys))
56 -> ConDecl (noLoc (cName c)) noExistentials noContext
57 (InfixCon (mk_arg st1) (mk_arg st2))
58 ForallC tvs ctxt (ForallC tvs' ctxt' con')
59 -> mk_nlcon (ForallC (tvs ++ tvs') (ctxt ++ ctxt') con')
60 ForallC tvs ctxt con' -> case mk_nlcon con' of
61 ConDecl l [] (L _ []) x ->
62 ConDecl l (cvt_tvs tvs) (cvt_context ctxt) x
63 c -> panic "ForallC: Can't happen"
64 mk_arg (IsStrict, ty) = noLoc $ HsBangTy HsStrict (cvtType ty)
65 mk_arg (NotStrict, ty) = cvtType ty
67 mk_id_arg (i, IsStrict, ty)
68 = (noLoc (vName i), noLoc $ HsBangTy HsStrict (cvtType ty))
69 mk_id_arg (i, NotStrict, ty)
70 = (noLoc (vName i), cvtType ty)
72 mk_derivs [] = Nothing
73 mk_derivs cs = Just [noLoc $ HsPredTy $ HsClassP (tconName c) [] | c <- cs]
75 cvt_ltop :: TH.Dec -> Either (LHsDecl RdrName) Message
76 cvt_ltop d = case cvt_top d of
77 Left d -> Left (L loc0 d)
80 cvt_top :: TH.Dec -> Either (HsDecl RdrName) Message
81 cvt_top d@(TH.ValD _ _ _) = Left $ Hs.ValD (unLoc (cvtd d))
82 cvt_top d@(TH.FunD _ _) = Left $ Hs.ValD (unLoc (cvtd d))
84 cvt_top (TySynD tc tvs rhs)
85 = Left $ TyClD (TySynonym (noLoc (tconName tc)) (cvt_tvs tvs) (cvtType rhs))
87 cvt_top (DataD ctxt tc tvs constrs derivs)
88 = Left $ TyClD (mkTyData DataType
89 (noLoc (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs))
90 Nothing (map mk_con constrs)
93 cvt_top (NewtypeD ctxt tc tvs constr derivs)
94 = Left $ TyClD (mkTyData NewType
95 (noLoc (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs))
96 Nothing [mk_con constr]
99 cvt_top (ClassD ctxt cl tvs fds decs)
100 = Left $ TyClD $ mkClassDecl (cvt_context ctxt,
103 (map (noLoc . cvt_fundep) fds)
107 (binds,sigs) = cvtBindsAndSigs decs
109 cvt_top (InstanceD tys ty decs)
110 = Left $ InstD (InstDecl (noLoc inst_ty) binds sigs)
112 (binds, sigs) = cvtBindsAndSigs decs
113 inst_ty = mkImplicitHsForAllTy (cvt_context tys) (noLoc (HsPredTy (cvt_pred ty)))
115 cvt_top (TH.SigD nm typ) = Left $ Hs.SigD (Sig (noLoc (vName nm)) (cvtType typ))
117 cvt_top (ForeignD (ImportF callconv safety from nm typ))
119 Just (c_header, cis) ->
120 let i = CImport callconv' safety' c_header nilFS cis
121 in Left $ ForD (ForeignImport (noLoc (vName nm)) (cvtType typ) i False)
122 Nothing -> Right $ text (show from)
123 <+> ptext SLIT("is not a valid ccall impent")
124 where callconv' = case callconv of
126 StdCall -> StdCallConv
127 safety' = case safety of
129 Safe -> PlaySafe False
130 Threadsafe -> PlaySafe True
131 parsed = parse_ccall_impent (TH.nameBase nm) from
133 cvt_top (ForeignD (ExportF callconv as nm typ))
134 = let e = CExport (CExportStatic (mkFastString as) callconv')
135 in Left $ ForD (ForeignExport (noLoc (vName nm)) (cvtType typ) e False)
136 where callconv' = case callconv of
138 StdCall -> StdCallConv
140 cvt_fundep :: FunDep -> Class.FunDep RdrName
141 cvt_fundep (FunDep xs ys) = (map tName xs, map tName ys)
143 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
144 parse_ccall_impent nm s
145 = case lex_ccall_impent s of
146 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
147 Just ["wrapper"] -> Just (nilFS, CWrapper)
148 Just ("static":ts) -> parse_ccall_impent_static nm ts
149 Just ts -> parse_ccall_impent_static nm ts
152 parse_ccall_impent_static :: String
154 -> Maybe (FastString, CImportSpec)
155 parse_ccall_impent_static nm ts
156 = let ts' = case ts of
157 [ "&", cid] -> [ cid]
158 [fname, "&" ] -> [fname ]
159 [fname, "&", cid] -> [fname, cid]
162 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
163 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
164 [ ] -> Just (nilFS, mk_cid nm)
165 [fname ] -> Just (mkFastString fname, mk_cid nm)
167 where is_cid :: String -> Bool
168 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
169 mk_cid :: String -> CImportSpec
170 mk_cid = CFunction . StaticTarget . mkFastString
172 lex_ccall_impent :: String -> Maybe [String]
173 lex_ccall_impent "" = Just []
174 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
175 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
176 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
177 lex_ccall_impent xs = case span is_valid xs of
179 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
180 where is_valid :: Char -> Bool
181 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
186 -------------------------------------------------------------------
187 convertToHsExpr :: TH.Exp -> LHsExpr RdrName
188 convertToHsExpr = cvtl
190 cvtl e = noLoc (cvt e)
192 cvt (VarE s) = HsVar (vName s)
193 cvt (ConE s) = HsVar (cName s)
195 | overloadedLit l = HsOverLit (cvtOverLit l)
196 | otherwise = HsLit (cvtLit l)
198 cvt (AppE x y) = HsApp (cvtl x) (cvtl y)
199 cvt (LamE ps e) = HsLam (mkMatchGroup [mkSimpleMatch (map cvtlp ps) (cvtl e)])
200 cvt (TupE [e]) = cvt e
201 cvt (TupE es) = ExplicitTuple(map cvtl es) Boxed
202 cvt (CondE x y z) = HsIf (cvtl x) (cvtl y) (cvtl z)
203 cvt (LetE ds e) = HsLet (cvtdecs ds) (cvtl e)
204 cvt (CaseE e ms) = HsCase (cvtl e) (mkMatchGroup (map cvtm ms))
205 cvt (DoE ss) = HsDo DoExpr (cvtstmts ss) [] void
206 cvt (CompE ss) = HsDo ListComp (cvtstmts ss) [] void
207 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
208 cvt (ListE xs) = ExplicitList void (map cvtl xs)
209 cvt (InfixE (Just x) s (Just y))
210 = HsPar (noLoc $ OpApp (cvtl x) (cvtl s) undefined (cvtl y))
211 cvt (InfixE Nothing s (Just y)) = SectionR (cvtl s) (cvtl y)
212 cvt (InfixE (Just x) s Nothing ) = SectionL (cvtl x) (cvtl s)
213 cvt (InfixE Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
214 cvt (SigE e t) = ExprWithTySig (cvtl e) (cvtType t)
215 cvt (RecConE c flds) = RecordCon (noLoc (cName c)) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
216 cvt (RecUpdE e flds) = RecordUpd (cvtl e) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
218 cvtdecs :: [TH.Dec] -> [HsBindGroup RdrName]
220 cvtdecs ds = [HsBindGroup binds sigs Recursive]
222 (binds, sigs) = cvtBindsAndSigs ds
225 = (cvtds non_sigs, map cvtSig sigs)
227 (sigs, non_sigs) = partition sigP ds
229 cvtSig (TH.SigD nm typ) = noLoc (Hs.Sig (noLoc (vName nm)) (cvtType typ))
231 cvtds :: [TH.Dec] -> LHsBinds RdrName
233 cvtds (d:ds) = cvtd d `consBag` cvtds ds
235 cvtd :: TH.Dec -> LHsBind RdrName
236 -- Used only for declarations in a 'let/where' clause,
237 -- not for top level decls
238 cvtd (TH.ValD (TH.VarP s) body ds)
239 = noLoc $ FunBind (noLoc (vName s)) False (mkMatchGroup [cvtclause (Clause [] body ds)])
241 = noLoc $ FunBind (noLoc (vName nm)) False (mkMatchGroup (map cvtclause cls))
242 cvtd (TH.ValD p body ds)
243 = noLoc $ PatBind (cvtlp p) (GRHSs (cvtguard body) (cvtdecs ds)) void
245 cvtd d = cvtPanic "Illegal kind of declaration in where clause"
249 cvtclause :: TH.Clause -> Hs.LMatch RdrName
250 cvtclause (Clause ps body wheres)
251 = noLoc $ Hs.Match (map cvtlp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres))
255 cvtdd :: Range -> ArithSeqInfo RdrName
256 cvtdd (FromR x) = (From (cvtl x))
257 cvtdd (FromThenR x y) = (FromThen (cvtl x) (cvtl y))
258 cvtdd (FromToR x y) = (FromTo (cvtl x) (cvtl y))
259 cvtdd (FromThenToR x y z) = (FromThenTo (cvtl x) (cvtl y) (cvtl z))
262 cvtstmts :: [TH.Stmt] -> [Hs.LStmt RdrName]
263 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
264 cvtstmts [NoBindS e] = [nlResultStmt (cvtl e)] -- when its the last element use ResultStmt
265 cvtstmts (NoBindS e : ss) = nlExprStmt (cvtl e) : cvtstmts ss
266 cvtstmts (TH.BindS p e : ss) = nlBindStmt (cvtlp p) (cvtl e) : cvtstmts ss
267 cvtstmts (TH.LetS ds : ss) = nlLetStmt (cvtdecs ds) : cvtstmts ss
268 cvtstmts (TH.ParS dss : ss) = nlParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
270 cvtm :: TH.Match -> Hs.LMatch RdrName
271 cvtm (TH.Match p body wheres)
272 = noLoc (Hs.Match [cvtlp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres)))
274 cvtguard :: TH.Body -> [LGRHS RdrName]
275 cvtguard (GuardedB pairs) = map cvtpair pairs
276 cvtguard (NormalB e) = [noLoc (GRHS [ nlResultStmt (cvtl e) ])]
278 cvtpair :: (TH.Guard,TH.Exp) -> LGRHS RdrName
279 cvtpair (NormalG x,y) = noLoc (GRHS [nlBindStmt truePat (cvtl x),
280 nlResultStmt (cvtl y)])
281 cvtpair (PatG x,y) = noLoc (GRHS (cvtstmts x ++ [nlResultStmt (cvtl y)]))
283 cvtOverLit :: Lit -> HsOverLit
284 cvtOverLit (IntegerL i) = mkHsIntegral i
285 cvtOverLit (RationalL r) = mkHsFractional r
286 -- An Integer is like an an (overloaded) '3' in a Haskell source program
287 -- Similarly 3.5 for fractionals
289 cvtLit :: Lit -> HsLit
290 cvtLit (IntPrimL i) = HsIntPrim i
291 cvtLit (FloatPrimL f) = HsFloatPrim f
292 cvtLit (DoublePrimL f) = HsDoublePrim f
293 cvtLit (CharL c) = HsChar c
294 cvtLit (StringL s) = HsString (mkFastString s)
296 cvtlp :: TH.Pat -> Hs.LPat RdrName
297 cvtlp pat = noLoc (cvtp pat)
299 cvtp :: TH.Pat -> Hs.Pat RdrName
301 | overloadedLit l = NPatIn (cvtOverLit l) Nothing -- Not right for negative
302 -- patterns; need to think
304 | otherwise = Hs.LitPat (cvtLit l)
305 cvtp (TH.VarP s) = Hs.VarPat(vName s)
306 cvtp (TupP [p]) = cvtp p
307 cvtp (TupP ps) = TuplePat (map cvtlp ps) Boxed
308 cvtp (ConP s ps) = ConPatIn (noLoc (cName s)) (PrefixCon (map cvtlp ps))
309 cvtp (InfixP p1 s p2)
310 = ConPatIn (noLoc (cName s)) (InfixCon (cvtlp p1) (cvtlp p2))
311 cvtp (TildeP p) = LazyPat (cvtlp p)
312 cvtp (TH.AsP s p) = AsPat (noLoc (vName s)) (cvtlp p)
313 cvtp TH.WildP = WildPat void
314 cvtp (RecP c fs) = ConPatIn (noLoc (cName c)) $ Hs.RecCon (map (\(s,p) -> (noLoc (vName s),cvtlp p)) fs)
315 cvtp (ListP ps) = ListPat (map cvtlp ps) void
316 cvtp (SigP p t) = SigPatIn (cvtlp p) (cvtType t)
318 -----------------------------------------------------------
319 -- Types and type variables
321 cvt_tvs :: [TH.Name] -> [LHsTyVarBndr RdrName]
322 cvt_tvs tvs = map (noLoc . UserTyVar . tName) tvs
324 cvt_context :: Cxt -> LHsContext RdrName
325 cvt_context tys = noLoc (map (noLoc . cvt_pred) tys)
327 cvt_pred :: TH.Type -> HsPred RdrName
328 cvt_pred ty = case split_ty_app ty of
329 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
330 (VarT tv, tys) -> HsClassP (tName tv) (map cvtType tys)
331 other -> cvtPanic "Malformed predicate" (text (TH.pprint ty))
333 convertToHsType = cvtType
335 cvtType :: TH.Type -> LHsType RdrName
336 cvtType ty = trans (root ty [])
337 where root (AppT a b) zs = root a (cvtType b : zs)
340 trans (TupleT n,args)
341 | length args == n = noLoc (HsTupleTy Boxed args)
342 | n == 0 = foldl nlHsAppTy (nlHsTyVar (getRdrName unitTyCon)) args
343 | otherwise = foldl nlHsAppTy (nlHsTyVar (getRdrName (tupleTyCon Boxed n))) args
344 trans (ArrowT, [x,y]) = nlHsFunTy x y
345 trans (ListT, [x]) = noLoc (HsListTy x)
347 trans (VarT nm, args) = foldl nlHsAppTy (nlHsTyVar (tName nm)) args
348 trans (ConT tc, args) = foldl nlHsAppTy (nlHsTyVar (tconName tc)) args
350 trans (ForallT tvs cxt ty, []) = noLoc $ mkExplicitHsForAllTy
351 (cvt_tvs tvs) (cvt_context cxt) (cvtType ty)
353 split_ty_app :: TH.Type -> (TH.Type, [TH.Type])
354 split_ty_app ty = go ty []
356 go (AppT f a) as = go f (a:as)
359 -----------------------------------------------------------
361 sigP (TH.SigD _ _) = True
365 -----------------------------------------------------------
366 cvtPanic :: String -> SDoc -> b
367 cvtPanic herald thing
368 = pprPanic herald (thing $$ ptext SLIT("When splicing generated code into the program"))
370 -----------------------------------------------------------
371 -- some useful things
373 truePat = nlConPat (getRdrName trueDataCon) []
374 falsePat = nlConPat (getRdrName falseDataCon) []
376 overloadedLit :: Lit -> Bool
377 -- True for literals that Haskell treats as overloaded
378 overloadedLit (IntegerL l) = True
379 overloadedLit (RationalL l) = True
380 overloadedLit l = False
383 void = placeHolderType
386 loc0 = srcLocSpan generatedSrcLoc
388 --------------------------------------------------------------------
389 -- Turning Name back into RdrName
390 --------------------------------------------------------------------
393 vName :: TH.Name -> RdrName
394 vName = thRdrName OccName.varName
396 -- Constructor function names; this is Haskell source, hence srcDataName
397 cName :: TH.Name -> RdrName
398 cName = thRdrName OccName.srcDataName
400 -- Type variable names
401 tName :: TH.Name -> RdrName
402 tName = thRdrName OccName.tvName
404 -- Type Constructor names
405 tconName = thRdrName OccName.tcName
407 thRdrName :: OccName.NameSpace -> TH.Name -> RdrName
408 -- This turns a Name into a RdrName
409 -- The last case is slightly interesting. It constructs a
410 -- unique name from the unique in the TH thingy, so that the renamer
411 -- won't mess about. I hope. (Another possiblity would be to generate
412 -- "x_77" etc, but that could conceivably clash.)
414 thRdrName ns (TH.Name occ (TH.NameG ns' mod)) = mkOrig (mk_mod mod) (mk_occ ns occ)
415 thRdrName ns (TH.Name occ TH.NameS) = mkDynName ns occ
416 thRdrName ns (TH.Name occ (TH.NameU uniq)) = nameRdrName (mkInternalName (mk_uniq uniq) (mk_occ ns occ) noSrcLoc)
418 mk_uniq :: Int# -> Unique
419 mk_uniq u = mkUniqueGrimily (I# u)
421 -- The packing and unpacking is rather turgid :-(
422 mk_occ :: OccName.NameSpace -> TH.OccName -> OccName.OccName
423 mk_occ ns occ = OccName.mkOccFS ns (mkFastString (TH.occString occ))
425 mk_mod :: TH.ModName -> ModuleName
426 mk_mod mod = mkModuleName (TH.modString mod)
428 mkDynName :: OccName.NameSpace -> TH.OccName -> RdrName
429 -- Parse the string to see if it has a "." in it
430 -- so we know whether to generate a qualified or unqualified name
431 -- It's a bit tricky because we need to parse
432 -- Foo.Baz.x as Qual Foo.Baz x
433 -- So we parse it from back to front
436 = split [] (reverse (TH.occString th_occ))
438 split occ [] = mkRdrUnqual (mk_occ occ)
439 split occ ('.':rev) = mkRdrQual (mk_mod (reverse rev)) (mk_occ occ)
440 split occ (c:rev) = split (c:occ) rev
442 mk_occ occ = OccName.mkOccFS ns (mkFastString occ)
443 mk_mod mod = mkModuleName mod