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, getRdrName )
19 import Module ( Module, mkModule )
20 import RdrHsSyn ( mkClassDecl, mkTyData )
21 import qualified OccName
22 import SrcLoc ( generatedSrcLoc, noLoc, unLoc, Located(..),
25 import TysWiredIn ( unitTyCon, tupleTyCon, trueDataCon )
26 import BasicTypes( Boxity(..), RecFlag(Recursive) )
27 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
29 import Char ( isAscii, isAlphaNum, isAlpha )
30 import List ( partition )
31 import Unique ( mkUniqueGrimily )
32 import ErrUtils (Message)
33 import GLAEXTS ( Int(..) )
34 import Bag ( emptyBag, consBag )
39 -------------------------------------------------------------------
40 convertToHsDecls :: [TH.Dec] -> [Either (LHsDecl RdrName) Message]
41 convertToHsDecls ds = map cvt_ltop ds
43 mk_con con = L loc0 $ mk_nlcon con
45 mk_nlcon con = 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))
55 ForallC tvs ctxt (ForallC tvs' ctxt' con')
56 -> mk_nlcon (ForallC (tvs ++ tvs') (ctxt ++ ctxt') con')
57 ForallC tvs ctxt con' -> case mk_nlcon con' of
58 ConDecl l [] (L _ []) x ->
59 ConDecl l (cvt_tvs tvs) (cvt_context ctxt) x
60 c -> panic "ForallC: Can't happen"
61 mk_arg (IsStrict, ty) = noLoc $ HsBangTy HsStrict (cvtType ty)
62 mk_arg (NotStrict, ty) = cvtType ty
64 mk_id_arg (i, IsStrict, ty)
65 = (noLoc (vName i), noLoc $ HsBangTy HsStrict (cvtType ty))
66 mk_id_arg (i, NotStrict, ty)
67 = (noLoc (vName i), cvtType ty)
69 mk_derivs [] = Nothing
70 mk_derivs cs = Just [noLoc $ HsPredTy $ HsClassP (tconName c) [] | c <- cs]
72 cvt_ltop :: TH.Dec -> Either (LHsDecl RdrName) Message
73 cvt_ltop d = case cvt_top d of
74 Left d -> Left (L loc0 d)
77 cvt_top :: TH.Dec -> Either (HsDecl RdrName) Message
78 cvt_top d@(TH.ValD _ _ _) = Left $ Hs.ValD (unLoc (cvtd d))
79 cvt_top d@(TH.FunD _ _) = Left $ Hs.ValD (unLoc (cvtd d))
81 cvt_top (TySynD tc tvs rhs)
82 = Left $ TyClD (TySynonym (noLoc (tconName tc)) (cvt_tvs tvs) (cvtType rhs))
84 cvt_top (DataD ctxt tc tvs constrs derivs)
85 = Left $ TyClD (mkTyData DataType
86 (noLoc (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs))
87 Nothing (map mk_con constrs)
90 cvt_top (NewtypeD ctxt tc tvs constr derivs)
91 = Left $ TyClD (mkTyData NewType
92 (noLoc (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs))
93 Nothing [mk_con constr]
96 cvt_top (ClassD ctxt cl tvs fds decs)
97 = Left $ TyClD $ mkClassDecl (cvt_context ctxt,
100 (map (noLoc . cvt_fundep) fds)
104 (binds,sigs) = cvtBindsAndSigs decs
106 cvt_top (InstanceD tys ty decs)
107 = Left $ InstD (InstDecl (noLoc inst_ty) binds sigs)
109 (binds, sigs) = cvtBindsAndSigs decs
110 inst_ty = mkImplicitHsForAllTy (cvt_context tys) (noLoc (HsPredTy (cvt_pred ty)))
112 cvt_top (TH.SigD nm typ) = Left $ Hs.SigD (Sig (noLoc (vName nm)) (cvtType typ))
114 cvt_top (ForeignD (ImportF callconv safety from nm typ))
116 Just (c_header, cis) ->
117 let i = CImport callconv' safety' c_header nilFS cis
118 in Left $ ForD (ForeignImport (noLoc (vName nm)) (cvtType typ) i False)
119 Nothing -> Right $ text (show from)
120 <+> ptext SLIT("is not a valid ccall impent")
121 where callconv' = case callconv of
123 StdCall -> StdCallConv
124 safety' = case safety of
126 Safe -> PlaySafe False
127 Threadsafe -> PlaySafe True
128 parsed = parse_ccall_impent (TH.nameBase nm) from
130 cvt_top (ForeignD (ExportF callconv as nm typ))
131 = let e = CExport (CExportStatic (mkFastString as) callconv')
132 in Left $ ForD (ForeignExport (noLoc (vName nm)) (cvtType typ) e False)
133 where callconv' = case callconv of
135 StdCall -> StdCallConv
137 cvt_fundep :: FunDep -> Class.FunDep RdrName
138 cvt_fundep (FunDep xs ys) = (map tName xs, map tName ys)
140 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
141 parse_ccall_impent nm s
142 = case lex_ccall_impent s of
143 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
144 Just ["wrapper"] -> Just (nilFS, CWrapper)
145 Just ("static":ts) -> parse_ccall_impent_static nm ts
146 Just ts -> parse_ccall_impent_static nm ts
149 parse_ccall_impent_static :: String
151 -> Maybe (FastString, CImportSpec)
152 parse_ccall_impent_static nm ts
153 = let ts' = case ts of
154 [ "&", cid] -> [ cid]
155 [fname, "&" ] -> [fname ]
156 [fname, "&", cid] -> [fname, cid]
159 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
160 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
161 [ ] -> Just (nilFS, mk_cid nm)
162 [fname ] -> Just (mkFastString fname, mk_cid nm)
164 where is_cid :: String -> Bool
165 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
166 mk_cid :: String -> CImportSpec
167 mk_cid = CFunction . StaticTarget . mkFastString
169 lex_ccall_impent :: String -> Maybe [String]
170 lex_ccall_impent "" = Just []
171 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
172 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
173 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
174 lex_ccall_impent xs = case span is_valid xs of
176 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
177 where is_valid :: Char -> Bool
178 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
183 -------------------------------------------------------------------
184 convertToHsExpr :: TH.Exp -> LHsExpr RdrName
185 convertToHsExpr = cvtl
187 cvtl e = noLoc (cvt e)
189 cvt (VarE s) = HsVar (vName s)
190 cvt (ConE s) = HsVar (cName s)
192 | overloadedLit l = HsOverLit (cvtOverLit l)
193 | otherwise = HsLit (cvtLit l)
195 cvt (AppE x y) = HsApp (cvtl x) (cvtl y)
196 cvt (LamE ps e) = HsLam (mkMatchGroup [mkSimpleMatch (map cvtlp ps) (cvtl e)])
197 cvt (TupE [e]) = cvt e
198 cvt (TupE es) = ExplicitTuple(map cvtl es) Boxed
199 cvt (CondE x y z) = HsIf (cvtl x) (cvtl y) (cvtl z)
200 cvt (LetE ds e) = HsLet (cvtdecs ds) (cvtl e)
201 cvt (CaseE e ms) = HsCase (cvtl e) (mkMatchGroup (map cvtm ms))
202 cvt (DoE ss) = HsDo DoExpr (cvtstmts ss) [] void
203 cvt (CompE ss) = HsDo ListComp (cvtstmts ss) [] void
204 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
205 cvt (ListE xs) = ExplicitList void (map cvtl xs)
206 cvt (InfixE (Just x) s (Just y))
207 = HsPar (noLoc $ OpApp (cvtl x) (cvtl s) undefined (cvtl y))
208 cvt (InfixE Nothing s (Just y)) = SectionR (cvtl s) (cvtl y)
209 cvt (InfixE (Just x) s Nothing ) = SectionL (cvtl x) (cvtl s)
210 cvt (InfixE Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
211 cvt (SigE e t) = ExprWithTySig (cvtl e) (cvtType t)
212 cvt (RecConE c flds) = RecordCon (noLoc (cName c)) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
213 cvt (RecUpdE e flds) = RecordUpd (cvtl e) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
215 cvtdecs :: [TH.Dec] -> [HsBindGroup RdrName]
217 cvtdecs ds = [HsBindGroup binds sigs Recursive]
219 (binds, sigs) = cvtBindsAndSigs ds
222 = (cvtds non_sigs, map cvtSig sigs)
224 (sigs, non_sigs) = partition sigP ds
226 cvtSig (TH.SigD nm typ) = noLoc (Hs.Sig (noLoc (vName nm)) (cvtType typ))
228 cvtds :: [TH.Dec] -> LHsBinds RdrName
230 cvtds (d:ds) = cvtd d `consBag` cvtds ds
232 cvtd :: TH.Dec -> LHsBind RdrName
233 -- Used only for declarations in a 'let/where' clause,
234 -- not for top level decls
235 cvtd (TH.ValD (TH.VarP s) body ds)
236 = noLoc $ FunBind (noLoc (vName s)) False (mkMatchGroup [cvtclause (Clause [] body ds)])
238 = noLoc $ FunBind (noLoc (vName nm)) False (mkMatchGroup (map cvtclause cls))
239 cvtd (TH.ValD p body ds)
240 = noLoc $ PatBind (cvtlp p) (GRHSs (cvtguard body) (cvtdecs ds)) void
242 cvtd d = cvtPanic "Illegal kind of declaration in where clause"
246 cvtclause :: TH.Clause -> Hs.LMatch RdrName
247 cvtclause (Clause ps body wheres)
248 = noLoc $ Hs.Match (map cvtlp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres))
252 cvtdd :: Range -> ArithSeqInfo RdrName
253 cvtdd (FromR x) = (From (cvtl x))
254 cvtdd (FromThenR x y) = (FromThen (cvtl x) (cvtl y))
255 cvtdd (FromToR x y) = (FromTo (cvtl x) (cvtl y))
256 cvtdd (FromThenToR x y z) = (FromThenTo (cvtl x) (cvtl y) (cvtl z))
259 cvtstmts :: [TH.Stmt] -> [Hs.LStmt RdrName]
260 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
261 cvtstmts [NoBindS e] = [nlResultStmt (cvtl e)] -- when its the last element use ResultStmt
262 cvtstmts (NoBindS e : ss) = nlExprStmt (cvtl e) : cvtstmts ss
263 cvtstmts (TH.BindS p e : ss) = nlBindStmt (cvtlp p) (cvtl e) : cvtstmts ss
264 cvtstmts (TH.LetS ds : ss) = nlLetStmt (cvtdecs ds) : cvtstmts ss
265 cvtstmts (TH.ParS dss : ss) = nlParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
267 cvtm :: TH.Match -> Hs.LMatch RdrName
268 cvtm (TH.Match p body wheres)
269 = noLoc (Hs.Match [cvtlp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres)))
271 cvtguard :: TH.Body -> [LGRHS RdrName]
272 cvtguard (GuardedB pairs) = map cvtpair pairs
273 cvtguard (NormalB e) = [noLoc (GRHS [ nlResultStmt (cvtl e) ])]
275 cvtpair :: (TH.Guard,TH.Exp) -> LGRHS RdrName
276 cvtpair (NormalG x,y) = noLoc (GRHS [nlBindStmt truePat (cvtl x),
277 nlResultStmt (cvtl y)])
278 cvtpair (PatG x,y) = noLoc (GRHS (cvtstmts x ++ [nlResultStmt (cvtl y)]))
280 cvtOverLit :: Lit -> HsOverLit
281 cvtOverLit (IntegerL i) = mkHsIntegral i
282 cvtOverLit (RationalL r) = mkHsFractional r
283 -- An Integer is like an an (overloaded) '3' in a Haskell source program
284 -- Similarly 3.5 for fractionals
286 cvtLit :: Lit -> HsLit
287 cvtLit (IntPrimL i) = HsIntPrim i
288 cvtLit (FloatPrimL f) = HsFloatPrim f
289 cvtLit (DoublePrimL f) = HsDoublePrim f
290 cvtLit (CharL c) = HsChar c
291 cvtLit (StringL s) = HsString (mkFastString s)
293 cvtlp :: TH.Pat -> Hs.LPat RdrName
294 cvtlp pat = noLoc (cvtp pat)
296 cvtp :: TH.Pat -> Hs.Pat RdrName
298 | overloadedLit l = NPatIn (cvtOverLit l) Nothing -- Not right for negative
299 -- patterns; need to think
301 | otherwise = Hs.LitPat (cvtLit l)
302 cvtp (TH.VarP s) = Hs.VarPat(vName s)
303 cvtp (TupP [p]) = cvtp p
304 cvtp (TupP ps) = TuplePat (map cvtlp ps) Boxed
305 cvtp (ConP s ps) = ConPatIn (noLoc (cName s)) (PrefixCon (map cvtlp ps))
306 cvtp (InfixP p1 s p2)
307 = ConPatIn (noLoc (cName s)) (InfixCon (cvtlp p1) (cvtlp p2))
308 cvtp (TildeP p) = LazyPat (cvtlp p)
309 cvtp (TH.AsP s p) = AsPat (noLoc (vName s)) (cvtlp p)
310 cvtp TH.WildP = WildPat void
311 cvtp (RecP c fs) = ConPatIn (noLoc (cName c)) $ Hs.RecCon (map (\(s,p) -> (noLoc (vName s),cvtlp p)) fs)
312 cvtp (ListP ps) = ListPat (map cvtlp ps) void
313 cvtp (SigP p t) = SigPatIn (cvtlp p) (cvtType t)
315 -----------------------------------------------------------
316 -- Types and type variables
318 cvt_tvs :: [TH.Name] -> [LHsTyVarBndr RdrName]
319 cvt_tvs tvs = map (noLoc . UserTyVar . tName) tvs
321 cvt_context :: Cxt -> LHsContext RdrName
322 cvt_context tys = noLoc (map (noLoc . cvt_pred) tys)
324 cvt_pred :: TH.Type -> HsPred RdrName
325 cvt_pred ty = case split_ty_app ty of
326 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
327 (VarT tv, tys) -> HsClassP (tName tv) (map cvtType tys)
328 other -> cvtPanic "Malformed predicate" (text (TH.pprint ty))
330 convertToHsType = cvtType
332 cvtType :: TH.Type -> LHsType RdrName
333 cvtType ty = trans (root ty [])
334 where root (AppT a b) zs = root a (cvtType b : zs)
337 trans (TupleT n,args)
338 | length args == n = noLoc (HsTupleTy Boxed args)
339 | n == 0 = foldl nlHsAppTy (nlHsTyVar (getRdrName unitTyCon)) args
340 | otherwise = foldl nlHsAppTy (nlHsTyVar (getRdrName (tupleTyCon Boxed n))) args
341 trans (ArrowT, [x,y]) = nlHsFunTy x y
342 trans (ListT, [x]) = noLoc (HsListTy x)
344 trans (VarT nm, args) = foldl nlHsAppTy (nlHsTyVar (tName nm)) args
345 trans (ConT tc, args) = foldl nlHsAppTy (nlHsTyVar (tconName tc)) args
347 trans (ForallT tvs cxt ty, []) = noLoc $ mkExplicitHsForAllTy
348 (cvt_tvs tvs) (cvt_context cxt) (cvtType ty)
350 split_ty_app :: TH.Type -> (TH.Type, [TH.Type])
351 split_ty_app ty = go ty []
353 go (AppT f a) as = go f (a:as)
356 -----------------------------------------------------------
358 sigP (TH.SigD _ _) = True
362 -----------------------------------------------------------
363 cvtPanic :: String -> SDoc -> b
364 cvtPanic herald thing
365 = pprPanic herald (thing $$ ptext SLIT("When splicing generated code into the program"))
367 -----------------------------------------------------------
368 -- some useful things
370 truePat = nlConPat (getRdrName trueDataCon) []
372 overloadedLit :: Lit -> Bool
373 -- True for literals that Haskell treats as overloaded
374 overloadedLit (IntegerL l) = True
375 overloadedLit (RationalL l) = True
376 overloadedLit l = False
379 void = placeHolderType
382 loc0 = srcLocSpan generatedSrcLoc
384 --------------------------------------------------------------------
385 -- Turning Name back into RdrName
386 --------------------------------------------------------------------
389 vName :: TH.Name -> RdrName
390 vName = thRdrName OccName.varName
392 -- Constructor function names; this is Haskell source, hence srcDataName
393 cName :: TH.Name -> RdrName
394 cName = thRdrName OccName.srcDataName
396 -- Type variable names
397 tName :: TH.Name -> RdrName
398 tName = thRdrName OccName.tvName
400 -- Type Constructor names
401 tconName = thRdrName OccName.tcName
403 thRdrName :: OccName.NameSpace -> TH.Name -> RdrName
404 -- This turns a Name into a RdrName
406 thRdrName ns (TH.Name occ (TH.NameG ns' mod)) = mkOrig (mk_mod mod) (mk_occ ns occ)
407 thRdrName ns (TH.Name occ TH.NameS) = mkDynName ns occ
408 thRdrName ns (TH.Name occ (TH.NameU uniq))
409 = mkRdrUnqual (OccName.mkOccName ns uniq_str)
411 uniq_str = TH.occString occ ++ '[' : shows (mkUniqueGrimily (I# uniq)) "]"
412 -- The idea here is to make a name that
413 -- a) the user could not possibly write, and
414 -- b) cannot clash with another NameU
415 -- Previously I generated an Exact RdrName with mkInternalName.
416 -- This works fine for local binders, but does not work at all for
417 -- top-level binders, which must have External Names, since they are
418 -- rapidly baked into data constructors and the like. Baling out
419 -- and generating an unqualified RdrName here is the simple solution
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 -> Module
426 mk_mod mod = mkModule (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 = mkModule mod