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, thRdrName ) 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, nameRdrName )
19 import Name ( mkInternalName )
20 import Module ( Module, mkModule )
21 import RdrHsSyn ( mkClassDecl, mkTyData )
22 import qualified OccName
23 import SrcLoc ( generatedSrcLoc, noLoc, unLoc, Located(..),
26 import TysWiredIn ( unitTyCon, tupleTyCon, trueDataCon )
27 import BasicTypes( Boxity(..), RecFlag(Recursive) )
28 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
30 import Char ( isAscii, isAlphaNum, isAlpha )
31 import List ( partition )
32 import Unique ( Unique, mkUniqueGrimily )
33 import ErrUtils (Message)
34 import GLAEXTS ( Int(..), Int# )
35 import SrcLoc ( noSrcLoc )
36 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 $ mk_nlcon con
47 mk_nlcon con = case con of
49 -> ConDecl (noLoc (cName c)) noExistentials noContext
50 (PrefixCon (map mk_arg strtys))
52 -> ConDecl (noLoc (cName c)) noExistentials noContext
53 (RecCon (map mk_id_arg varstrtys))
55 -> ConDecl (noLoc (cName c)) noExistentials noContext
56 (InfixCon (mk_arg st1) (mk_arg st2))
57 ForallC tvs ctxt (ForallC tvs' ctxt' con')
58 -> mk_nlcon (ForallC (tvs ++ tvs') (ctxt ++ ctxt') con')
59 ForallC tvs ctxt con' -> case mk_nlcon con' of
60 ConDecl l [] (L _ []) x ->
61 ConDecl l (cvt_tvs tvs) (cvt_context ctxt) x
62 c -> panic "ForallC: Can't happen"
63 mk_arg (IsStrict, ty) = noLoc $ HsBangTy HsStrict (cvtType ty)
64 mk_arg (NotStrict, ty) = cvtType ty
66 mk_id_arg (i, IsStrict, ty)
67 = (noLoc (vName i), noLoc $ HsBangTy HsStrict (cvtType ty))
68 mk_id_arg (i, NotStrict, ty)
69 = (noLoc (vName i), cvtType ty)
71 mk_derivs [] = Nothing
72 mk_derivs cs = Just [noLoc $ HsPredTy $ HsClassP (tconName c) [] | c <- cs]
74 cvt_ltop :: TH.Dec -> Either (LHsDecl RdrName) Message
75 cvt_ltop d = case cvt_top d of
76 Left d -> Left (L loc0 d)
79 cvt_top :: TH.Dec -> Either (HsDecl RdrName) Message
80 cvt_top d@(TH.ValD _ _ _) = Left $ Hs.ValD (unLoc (cvtd d))
81 cvt_top d@(TH.FunD _ _) = Left $ Hs.ValD (unLoc (cvtd d))
83 cvt_top (TySynD tc tvs rhs)
84 = Left $ TyClD (TySynonym (noLoc (tconName tc)) (cvt_tvs tvs) (cvtType rhs))
86 cvt_top (DataD ctxt tc tvs constrs derivs)
87 = Left $ TyClD (mkTyData DataType
88 (noLoc (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs))
89 Nothing (map mk_con constrs)
92 cvt_top (NewtypeD ctxt tc tvs constr derivs)
93 = Left $ TyClD (mkTyData NewType
94 (noLoc (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs))
95 Nothing [mk_con constr]
98 cvt_top (ClassD ctxt cl tvs fds decs)
99 = Left $ TyClD $ mkClassDecl (cvt_context ctxt,
102 (map (noLoc . cvt_fundep) fds)
106 (binds,sigs) = cvtBindsAndSigs decs
108 cvt_top (InstanceD tys ty decs)
109 = Left $ InstD (InstDecl (noLoc inst_ty) binds sigs)
111 (binds, sigs) = cvtBindsAndSigs decs
112 inst_ty = mkImplicitHsForAllTy (cvt_context tys) (noLoc (HsPredTy (cvt_pred ty)))
114 cvt_top (TH.SigD nm typ) = Left $ Hs.SigD (Sig (noLoc (vName nm)) (cvtType typ))
116 cvt_top (ForeignD (ImportF callconv safety from nm typ))
118 Just (c_header, cis) ->
119 let i = CImport callconv' safety' c_header nilFS cis
120 in Left $ ForD (ForeignImport (noLoc (vName nm)) (cvtType typ) i False)
121 Nothing -> Right $ text (show from)
122 <+> ptext SLIT("is not a valid ccall impent")
123 where callconv' = case callconv of
125 StdCall -> StdCallConv
126 safety' = case safety of
128 Safe -> PlaySafe False
129 Threadsafe -> PlaySafe True
130 parsed = parse_ccall_impent (TH.nameBase nm) from
132 cvt_top (ForeignD (ExportF callconv as nm typ))
133 = let e = CExport (CExportStatic (mkFastString as) callconv')
134 in Left $ ForD (ForeignExport (noLoc (vName nm)) (cvtType typ) e False)
135 where callconv' = case callconv of
137 StdCall -> StdCallConv
139 cvt_fundep :: FunDep -> Class.FunDep RdrName
140 cvt_fundep (FunDep xs ys) = (map tName xs, map tName ys)
142 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
143 parse_ccall_impent nm s
144 = case lex_ccall_impent s of
145 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
146 Just ["wrapper"] -> Just (nilFS, CWrapper)
147 Just ("static":ts) -> parse_ccall_impent_static nm ts
148 Just ts -> parse_ccall_impent_static nm ts
151 parse_ccall_impent_static :: String
153 -> Maybe (FastString, CImportSpec)
154 parse_ccall_impent_static nm ts
155 = let ts' = case ts of
156 [ "&", cid] -> [ cid]
157 [fname, "&" ] -> [fname ]
158 [fname, "&", cid] -> [fname, cid]
161 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
162 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
163 [ ] -> Just (nilFS, mk_cid nm)
164 [fname ] -> Just (mkFastString fname, mk_cid nm)
166 where is_cid :: String -> Bool
167 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
168 mk_cid :: String -> CImportSpec
169 mk_cid = CFunction . StaticTarget . mkFastString
171 lex_ccall_impent :: String -> Maybe [String]
172 lex_ccall_impent "" = Just []
173 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
174 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
175 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
176 lex_ccall_impent xs = case span is_valid xs of
178 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
179 where is_valid :: Char -> Bool
180 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
185 -------------------------------------------------------------------
186 convertToHsExpr :: TH.Exp -> LHsExpr RdrName
187 convertToHsExpr = cvtl
189 cvtl e = noLoc (cvt e)
191 cvt (VarE s) = HsVar (vName s)
192 cvt (ConE s) = HsVar (cName s)
194 | overloadedLit l = HsOverLit (cvtOverLit l)
195 | otherwise = HsLit (cvtLit l)
197 cvt (AppE x y) = HsApp (cvtl x) (cvtl y)
198 cvt (LamE ps e) = HsLam (mkMatchGroup [mkSimpleMatch (map cvtlp ps) (cvtl e)])
199 cvt (TupE [e]) = cvt e
200 cvt (TupE es) = ExplicitTuple(map cvtl es) Boxed
201 cvt (CondE x y z) = HsIf (cvtl x) (cvtl y) (cvtl z)
202 cvt (LetE ds e) = HsLet (cvtdecs ds) (cvtl e)
203 cvt (CaseE e ms) = HsCase (cvtl e) (mkMatchGroup (map cvtm ms))
204 cvt (DoE ss) = HsDo DoExpr (cvtstmts ss) [] void
205 cvt (CompE ss) = HsDo ListComp (cvtstmts ss) [] void
206 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
207 cvt (ListE xs) = ExplicitList void (map cvtl xs)
208 cvt (InfixE (Just x) s (Just y))
209 = HsPar (noLoc $ OpApp (cvtl x) (cvtl s) undefined (cvtl y))
210 cvt (InfixE Nothing s (Just y)) = SectionR (cvtl s) (cvtl y)
211 cvt (InfixE (Just x) s Nothing ) = SectionL (cvtl x) (cvtl s)
212 cvt (InfixE Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
213 cvt (SigE e t) = ExprWithTySig (cvtl e) (cvtType t)
214 cvt (RecConE c flds) = RecordCon (noLoc (cName c)) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
215 cvt (RecUpdE e flds) = RecordUpd (cvtl e) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
217 cvtdecs :: [TH.Dec] -> [HsBindGroup RdrName]
219 cvtdecs ds = [HsBindGroup binds sigs Recursive]
221 (binds, sigs) = cvtBindsAndSigs ds
224 = (cvtds non_sigs, map cvtSig sigs)
226 (sigs, non_sigs) = partition sigP ds
228 cvtSig (TH.SigD nm typ) = noLoc (Hs.Sig (noLoc (vName nm)) (cvtType typ))
230 cvtds :: [TH.Dec] -> LHsBinds RdrName
232 cvtds (d:ds) = cvtd d `consBag` cvtds ds
234 cvtd :: TH.Dec -> LHsBind RdrName
235 -- Used only for declarations in a 'let/where' clause,
236 -- not for top level decls
237 cvtd (TH.ValD (TH.VarP s) body ds)
238 = noLoc $ FunBind (noLoc (vName s)) False (mkMatchGroup [cvtclause (Clause [] body ds)])
240 = noLoc $ FunBind (noLoc (vName nm)) False (mkMatchGroup (map cvtclause cls))
241 cvtd (TH.ValD p body ds)
242 = noLoc $ PatBind (cvtlp p) (GRHSs (cvtguard body) (cvtdecs ds)) void
244 cvtd d = cvtPanic "Illegal kind of declaration in where clause"
248 cvtclause :: TH.Clause -> Hs.LMatch RdrName
249 cvtclause (Clause ps body wheres)
250 = noLoc $ Hs.Match (map cvtlp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres))
254 cvtdd :: Range -> ArithSeqInfo RdrName
255 cvtdd (FromR x) = (From (cvtl x))
256 cvtdd (FromThenR x y) = (FromThen (cvtl x) (cvtl y))
257 cvtdd (FromToR x y) = (FromTo (cvtl x) (cvtl y))
258 cvtdd (FromThenToR x y z) = (FromThenTo (cvtl x) (cvtl y) (cvtl z))
261 cvtstmts :: [TH.Stmt] -> [Hs.LStmt RdrName]
262 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
263 cvtstmts [NoBindS e] = [nlResultStmt (cvtl e)] -- when its the last element use ResultStmt
264 cvtstmts (NoBindS e : ss) = nlExprStmt (cvtl e) : cvtstmts ss
265 cvtstmts (TH.BindS p e : ss) = nlBindStmt (cvtlp p) (cvtl e) : cvtstmts ss
266 cvtstmts (TH.LetS ds : ss) = nlLetStmt (cvtdecs ds) : cvtstmts ss
267 cvtstmts (TH.ParS dss : ss) = nlParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
269 cvtm :: TH.Match -> Hs.LMatch RdrName
270 cvtm (TH.Match p body wheres)
271 = noLoc (Hs.Match [cvtlp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres)))
273 cvtguard :: TH.Body -> [LGRHS RdrName]
274 cvtguard (GuardedB pairs) = map cvtpair pairs
275 cvtguard (NormalB e) = [noLoc (GRHS [ nlResultStmt (cvtl e) ])]
277 cvtpair :: (TH.Guard,TH.Exp) -> LGRHS RdrName
278 cvtpair (NormalG x,y) = noLoc (GRHS [nlBindStmt truePat (cvtl x),
279 nlResultStmt (cvtl y)])
280 cvtpair (PatG x,y) = noLoc (GRHS (cvtstmts x ++ [nlResultStmt (cvtl y)]))
282 cvtOverLit :: Lit -> HsOverLit
283 cvtOverLit (IntegerL i) = mkHsIntegral i
284 cvtOverLit (RationalL r) = mkHsFractional r
285 -- An Integer is like an an (overloaded) '3' in a Haskell source program
286 -- Similarly 3.5 for fractionals
288 cvtLit :: Lit -> HsLit
289 cvtLit (IntPrimL i) = HsIntPrim i
290 cvtLit (FloatPrimL f) = HsFloatPrim f
291 cvtLit (DoublePrimL f) = HsDoublePrim f
292 cvtLit (CharL c) = HsChar c
293 cvtLit (StringL s) = HsString (mkFastString s)
295 cvtlp :: TH.Pat -> Hs.LPat RdrName
296 cvtlp pat = noLoc (cvtp pat)
298 cvtp :: TH.Pat -> Hs.Pat RdrName
300 | overloadedLit l = NPatIn (cvtOverLit l) Nothing -- Not right for negative
301 -- patterns; need to think
303 | otherwise = Hs.LitPat (cvtLit l)
304 cvtp (TH.VarP s) = Hs.VarPat(vName s)
305 cvtp (TupP [p]) = cvtp p
306 cvtp (TupP ps) = TuplePat (map cvtlp ps) Boxed
307 cvtp (ConP s ps) = ConPatIn (noLoc (cName s)) (PrefixCon (map cvtlp ps))
308 cvtp (InfixP p1 s p2)
309 = ConPatIn (noLoc (cName s)) (InfixCon (cvtlp p1) (cvtlp p2))
310 cvtp (TildeP p) = LazyPat (cvtlp p)
311 cvtp (TH.AsP s p) = AsPat (noLoc (vName s)) (cvtlp p)
312 cvtp TH.WildP = WildPat void
313 cvtp (RecP c fs) = ConPatIn (noLoc (cName c)) $ Hs.RecCon (map (\(s,p) -> (noLoc (vName s),cvtlp p)) fs)
314 cvtp (ListP ps) = ListPat (map cvtlp ps) void
315 cvtp (SigP p t) = SigPatIn (cvtlp p) (cvtType t)
317 -----------------------------------------------------------
318 -- Types and type variables
320 cvt_tvs :: [TH.Name] -> [LHsTyVarBndr RdrName]
321 cvt_tvs tvs = map (noLoc . UserTyVar . tName) tvs
323 cvt_context :: Cxt -> LHsContext RdrName
324 cvt_context tys = noLoc (map (noLoc . cvt_pred) tys)
326 cvt_pred :: TH.Type -> HsPred RdrName
327 cvt_pred ty = case split_ty_app ty of
328 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
329 (VarT tv, tys) -> HsClassP (tName tv) (map cvtType tys)
330 other -> cvtPanic "Malformed predicate" (text (TH.pprint ty))
332 convertToHsType = cvtType
334 cvtType :: TH.Type -> LHsType RdrName
335 cvtType ty = trans (root ty [])
336 where root (AppT a b) zs = root a (cvtType b : zs)
339 trans (TupleT n,args)
340 | length args == n = noLoc (HsTupleTy Boxed args)
341 | n == 0 = foldl nlHsAppTy (nlHsTyVar (getRdrName unitTyCon)) args
342 | otherwise = foldl nlHsAppTy (nlHsTyVar (getRdrName (tupleTyCon Boxed n))) args
343 trans (ArrowT, [x,y]) = nlHsFunTy x y
344 trans (ListT, [x]) = noLoc (HsListTy x)
346 trans (VarT nm, args) = foldl nlHsAppTy (nlHsTyVar (tName nm)) args
347 trans (ConT tc, args) = foldl nlHsAppTy (nlHsTyVar (tconName tc)) args
349 trans (ForallT tvs cxt ty, []) = noLoc $ mkExplicitHsForAllTy
350 (cvt_tvs tvs) (cvt_context cxt) (cvtType ty)
352 split_ty_app :: TH.Type -> (TH.Type, [TH.Type])
353 split_ty_app ty = go ty []
355 go (AppT f a) as = go f (a:as)
358 -----------------------------------------------------------
360 sigP (TH.SigD _ _) = True
364 -----------------------------------------------------------
365 cvtPanic :: String -> SDoc -> b
366 cvtPanic herald thing
367 = pprPanic herald (thing $$ ptext SLIT("When splicing generated code into the program"))
369 -----------------------------------------------------------
370 -- some useful things
372 truePat = nlConPat (getRdrName trueDataCon) []
374 overloadedLit :: Lit -> Bool
375 -- True for literals that Haskell treats as overloaded
376 overloadedLit (IntegerL l) = True
377 overloadedLit (RationalL l) = True
378 overloadedLit l = False
381 void = placeHolderType
384 loc0 = srcLocSpan generatedSrcLoc
386 --------------------------------------------------------------------
387 -- Turning Name back into RdrName
388 --------------------------------------------------------------------
391 vName :: TH.Name -> RdrName
392 vName = thRdrName OccName.varName
394 -- Constructor function names; this is Haskell source, hence srcDataName
395 cName :: TH.Name -> RdrName
396 cName = thRdrName OccName.srcDataName
398 -- Type variable names
399 tName :: TH.Name -> RdrName
400 tName = thRdrName OccName.tvName
402 -- Type Constructor names
403 tconName = thRdrName OccName.tcName
405 thRdrName :: OccName.NameSpace -> TH.Name -> RdrName
406 -- This turns a Name into a RdrName
407 -- The passed-in name space tells what the context is expecting;
408 -- use it unless the TH name knows what name-space it comes
409 -- from, in which case use the latter
410 thRdrName ctxt_ns (TH.Name occ (TH.NameG th_ns mod)) = mkOrig (mk_mod mod) (mk_occ (mk_ghc_ns th_ns) occ)
411 thRdrName ctxt_ns (TH.Name occ (TH.NameL uniq)) = nameRdrName (mkInternalName (mk_uniq uniq) (mk_occ ctxt_ns occ) noSrcLoc)
412 thRdrName ctxt_ns (TH.Name occ (TH.NameQ mod)) = mkRdrQual (mk_mod mod) (mk_occ ctxt_ns occ)
413 thRdrName ctxt_ns (TH.Name occ TH.NameS) = mkRdrUnqual (mk_occ ctxt_ns occ)
414 thRdrName ctxt_ns (TH.Name occ (TH.NameU uniq)) = mkRdrUnqual (mk_uniq_occ ctxt_ns occ uniq)
416 mk_uniq_occ :: OccName.NameSpace -> TH.OccName -> Int# -> OccName.OccName
417 mk_uniq_occ ns occ uniq
418 = OccName.mkOccName ns (TH.occString occ ++ '[' : shows (mk_uniq uniq) "]")
419 -- The idea here is to make a name that
420 -- a) the user could not possibly write, and
421 -- b) cannot clash with another NameU
422 -- Previously I generated an Exact RdrName with mkInternalName.
423 -- This works fine for local binders, but does not work at all for
424 -- top-level binders, which must have External Names, since they are
425 -- rapidly baked into data constructors and the like. Baling out
426 -- and generating an unqualified RdrName here is the simple solution
428 mk_ghc_ns :: TH.NameSpace -> OccName.NameSpace
429 mk_ghc_ns DataName = OccName.dataName
430 mk_ghc_ns TH.TcClsName = OccName.tcClsName
431 mk_ghc_ns TH.VarName = OccName.varName
433 -- The packing and unpacking is rather turgid :-(
434 mk_occ :: OccName.NameSpace -> TH.OccName -> OccName.OccName
435 mk_occ ns occ = OccName.mkOccFS ns (mkFastString (TH.occString occ))
437 mk_mod :: TH.ModName -> Module
438 mk_mod mod = mkModule (TH.modString mod)
440 mk_uniq :: Int# -> Unique
441 mk_uniq u = mkUniqueGrimily (I# u)