2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 This module converts Template Haskell syntax into HsSyn
9 module Convert( convertToHsExpr, convertToHsDecls ) where
11 #include "HsVersions.h"
13 import Language.Haskell.THSyntax as Meta
16 ( HsExpr(..), HsLit(..), ArithSeqInfo(..),
17 HsStmtContext(..), TyClDecl(..),
18 Match(..), GRHSs(..), GRHS(..), HsPred(..),
19 HsDecl(..), TyClDecl(..), InstDecl(..), ConDecl(..),
20 Stmt(..), HsBinds(..), MonoBinds(..), Sig(..),
21 Pat(..), HsConDetails(..), HsOverLit, BangType(..),
22 placeHolderType, HsType(..), HsTupCon(..),
23 HsTyVarBndr(..), HsContext,
24 mkSimpleMatch, mkHsForAllTy
27 import RdrName ( RdrName, mkRdrUnqual, mkRdrQual, mkOrig )
28 import Module ( mkModuleName )
29 import RdrHsSyn ( mkHsIntegral, mkHsFractional, mkClassDecl, mkTyData )
31 import SrcLoc ( SrcLoc, generatedSrcLoc )
32 import TyCon ( DataConDetails(..) )
34 import BasicTypes( Boxity(..), RecFlag(Recursive),
35 NewOrData(..), StrictnessMark(..) )
36 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
38 import HsDecls ( CImportSpec(..), ForeignImport(..), ForeignExport(..),
40 import FastString( FastString, mkFastString, nilFS )
41 import Char ( ord, isAscii, isAlphaNum, isAlpha )
42 import List ( partition )
43 import ErrUtils (Message)
47 -------------------------------------------------------------------
48 convertToHsDecls :: [Meta.Dec] -> [Either (HsDecl RdrName) Message]
49 convertToHsDecls ds = map cvt_top ds
51 mk_con con = case con of
53 -> ConDecl (cName c) noExistentials noContext
54 (PrefixCon (map mk_arg strtys)) loc0
56 -> ConDecl (cName c) noExistentials noContext
57 (RecCon (map mk_id_arg varstrtys)) loc0
59 -> ConDecl (cName c) noExistentials noContext
60 (InfixCon (mk_arg st1) (mk_arg st2)) loc0
62 mk_arg (IsStrict, ty) = BangType MarkedUserStrict (cvtType ty)
63 mk_arg (NotStrict, ty) = BangType NotMarkedStrict (cvtType ty)
65 mk_id_arg (i, IsStrict, ty)
66 = (vName i, BangType MarkedUserStrict (cvtType ty))
67 mk_id_arg (i, NotStrict, ty)
68 = (vName i, BangType NotMarkedStrict (cvtType ty))
70 mk_derivs [] = Nothing
71 mk_derivs cs = Just [HsClassP (tconName c) [] | c <- cs]
73 cvt_top :: Meta.Dec -> Either (HsDecl RdrName) Message
74 cvt_top d@(Meta.ValD _ _ _) = Left $ Hs.ValD (cvtd d)
75 cvt_top d@(Meta.FunD _ _) = Left $ Hs.ValD (cvtd d)
77 cvt_top (TySynD tc tvs rhs)
78 = Left $ TyClD (TySynonym (tconName tc) (cvt_tvs tvs) (cvtType rhs) loc0)
80 cvt_top (DataD ctxt tc tvs constrs derivs)
81 = Left $ TyClD (mkTyData DataType
82 (cvt_context ctxt, tconName tc, cvt_tvs tvs)
83 (DataCons (map mk_con constrs))
84 (mk_derivs derivs) loc0)
86 cvt_top (NewtypeD ctxt tc tvs constr derivs)
87 = Left $ TyClD (mkTyData NewType
88 (cvt_context ctxt, tconName tc, cvt_tvs tvs)
89 (DataCons [mk_con constr])
90 (mk_derivs derivs) loc0)
92 cvt_top (ClassD ctxt cl tvs decs)
93 = Left $ TyClD (mkClassDecl (cvt_context ctxt, tconName cl, cvt_tvs tvs)
97 (binds,sigs) = cvtBindsAndSigs decs
99 cvt_top (InstanceD tys ty decs)
100 = Left $ InstD (InstDecl inst_ty binds sigs Nothing loc0)
102 (binds, sigs) = cvtBindsAndSigs decs
103 inst_ty = HsForAllTy Nothing
105 (HsPredTy (cvt_pred ty))
107 cvt_top (Meta.SigD nm typ) = Left $ Hs.SigD (Sig (vName nm) (cvtType typ) loc0)
109 cvt_top (ForeignD (ImportF callconv safety from nm typ))
111 Just (c_header, cis) ->
112 let i = CImport callconv' safety' c_header nilFS cis
113 in Left $ ForD (ForeignImport (vName nm) (cvtType typ) i False loc0)
114 Nothing -> Right $ text (show from)
115 <+> ptext SLIT("is not a valid ccall impent")
116 where callconv' = case callconv of
118 StdCall -> StdCallConv
119 safety' = case safety of
121 Safe -> PlaySafe False
122 Threadsafe -> PlaySafe True
123 parsed = parse_ccall_impent nm from
125 cvt_top (ForeignD (ExportF callconv as nm typ))
126 = let e = CExport (CExportStatic (mkFastString as) callconv')
127 in Left $ ForD (ForeignExport (vName nm) (cvtType typ) e False loc0)
128 where callconv' = case callconv of
130 StdCall -> StdCallConv
132 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
133 parse_ccall_impent nm s
134 = case lex_ccall_impent s of
135 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
136 Just ["wrapper"] -> Just (nilFS, CWrapper)
137 Just ("static":ts) -> parse_ccall_impent_static nm ts
138 Just ts -> parse_ccall_impent_static nm ts
141 parse_ccall_impent_static :: String
143 -> Maybe (FastString, CImportSpec)
144 parse_ccall_impent_static nm ts
145 = let ts' = case ts of
146 [ "&", cid] -> [ cid]
147 [fname, "&" ] -> [fname ]
148 [fname, "&", cid] -> [fname, cid]
151 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
152 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
153 [ ] -> Just (nilFS, mk_cid nm)
154 [fname ] -> Just (mkFastString fname, mk_cid nm)
156 where is_cid :: String -> Bool
157 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
158 mk_cid :: String -> CImportSpec
159 mk_cid = CFunction . StaticTarget . mkFastString
161 lex_ccall_impent :: String -> Maybe [String]
162 lex_ccall_impent "" = Just []
163 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
164 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
165 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
166 lex_ccall_impent xs = case span is_valid xs of
168 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
169 where is_valid :: Char -> Bool
170 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
176 -------------------------------------------------------------------
177 convertToHsExpr :: Meta.Exp -> HsExpr RdrName
178 convertToHsExpr = cvt
180 cvt (VarE s) = HsVar (vName s)
181 cvt (ConE s) = HsVar (cName s)
183 | overloadedLit l = HsOverLit (cvtOverLit l)
184 | otherwise = HsLit (cvtLit l)
186 cvt (AppE x y) = HsApp (cvt x) (cvt y)
187 cvt (LamE ps e) = HsLam (mkSimpleMatch (map cvtp ps) (cvt e) void loc0)
188 cvt (TupE [e]) = cvt e
189 cvt (TupE es) = ExplicitTuple(map cvt es) Boxed
190 cvt (CondE x y z) = HsIf (cvt x) (cvt y) (cvt z) loc0
191 cvt (LetE ds e) = HsLet (cvtdecs ds) (cvt e)
192 cvt (CaseE e ms) = HsCase (cvt e) (map cvtm ms) loc0
193 cvt (DoE ss) = HsDo DoExpr (cvtstmts ss) [] void loc0
194 cvt (CompE ss) = HsDo ListComp (cvtstmts ss) [] void loc0
195 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
196 cvt (ListE xs) = ExplicitList void (map cvt xs)
197 cvt (InfixE (Just x) s (Just y))
198 = HsPar (OpApp (cvt x) (cvt s) undefined (cvt y))
199 cvt (InfixE Nothing s (Just y)) = SectionR (cvt s) (cvt y)
200 cvt (InfixE (Just x) s Nothing ) = SectionL (cvt x) (cvt s)
201 cvt (InfixE Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
202 cvt (SigE e t) = ExprWithTySig (cvt e) (cvtType t)
203 cvt (RecConE c flds) = RecordCon (cName c) (map (\(x,y) -> (vName x, cvt y)) flds)
204 cvt (RecUpdE e flds) = RecordUpd (cvt e) (map (\(x,y) -> (vName x, cvt y)) flds)
206 cvtdecs :: [Meta.Dec] -> HsBinds RdrName
207 cvtdecs [] = EmptyBinds
208 cvtdecs ds = MonoBind binds sigs Recursive
210 (binds, sigs) = cvtBindsAndSigs ds
213 = (cvtds non_sigs, map cvtSig sigs)
215 (sigs, non_sigs) = partition sigP ds
217 cvtSig (Meta.SigD nm typ) = Hs.Sig (vName nm) (cvtType typ) loc0
219 cvtds :: [Meta.Dec] -> MonoBinds RdrName
220 cvtds [] = EmptyMonoBinds
221 cvtds (d:ds) = AndMonoBinds (cvtd d) (cvtds ds)
223 cvtd :: Meta.Dec -> MonoBinds RdrName
224 -- Used only for declarations in a 'let/where' clause,
225 -- not for top level decls
226 cvtd (Meta.ValD (Meta.VarP s) body ds) = FunMonoBind (vName s) False
227 [cvtclause (Clause [] body ds)] loc0
228 cvtd (FunD nm cls) = FunMonoBind (vName nm) False (map cvtclause cls) loc0
229 cvtd (Meta.ValD p body ds) = PatMonoBind (cvtp p) (GRHSs (cvtguard body)
232 cvtd x = panic "Illegal kind of declaration in where clause"
235 cvtclause :: Meta.Clause -> Hs.Match RdrName
236 cvtclause (Clause ps body wheres)
237 = Hs.Match (map cvtp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
241 cvtdd :: Range -> ArithSeqInfo RdrName
242 cvtdd (FromR x) = (From (cvt x))
243 cvtdd (FromThenR x y) = (FromThen (cvt x) (cvt y))
244 cvtdd (FromToR x y) = (FromTo (cvt x) (cvt y))
245 cvtdd (FromThenToR x y z) = (FromThenTo (cvt x) (cvt y) (cvt z))
248 cvtstmts :: [Meta.Stmt] -> [Hs.Stmt RdrName]
249 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
250 cvtstmts [NoBindS e] = [ResultStmt (cvt e) loc0] -- when its the last element use ResultStmt
251 cvtstmts (NoBindS e : ss) = ExprStmt (cvt e) void loc0 : cvtstmts ss
252 cvtstmts (Meta.BindS p e : ss) = BindStmt (cvtp p) (cvt e) loc0 : cvtstmts ss
253 cvtstmts (Meta.LetS ds : ss) = LetStmt (cvtdecs ds) : cvtstmts ss
254 cvtstmts (Meta.ParS dss : ss) = ParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
256 cvtm :: Meta.Match -> Hs.Match RdrName
257 cvtm (Meta.Match p body wheres)
258 = Hs.Match [cvtp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
260 cvtguard :: Meta.Body -> [GRHS RdrName]
261 cvtguard (GuardedB pairs) = map cvtpair pairs
262 cvtguard (NormalB e) = [GRHS [ ResultStmt (cvt e) loc0 ] loc0]
264 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
265 cvtpair (x,y) = GRHS [Hs.BindStmt truePat (cvt x) loc0,
266 ResultStmt (cvt y) loc0] loc0
268 cvtOverLit :: Lit -> HsOverLit
269 cvtOverLit (IntegerL i) = mkHsIntegral i
270 cvtOverLit (RationalL r) = mkHsFractional r
271 -- An Integer is like an an (overloaded) '3' in a Haskell source program
272 -- Similarly 3.5 for fractionals
274 cvtLit :: Lit -> HsLit
275 cvtLit (IntPrimL i) = HsIntPrim i
276 cvtLit (FloatPrimL f) = HsFloatPrim f
277 cvtLit (DoublePrimL f) = HsDoublePrim f
278 cvtLit (CharL c) = HsChar (ord c)
279 cvtLit (StringL s) = HsString (mkFastString s)
281 cvtp :: Meta.Pat -> Hs.Pat RdrName
283 | overloadedLit l = NPatIn (cvtOverLit l) Nothing -- Not right for negative
284 -- patterns; need to think
286 | otherwise = Hs.LitPat (cvtLit l)
287 cvtp (Meta.VarP s) = Hs.VarPat(vName s)
288 cvtp (TupP [p]) = cvtp p
289 cvtp (TupP ps) = TuplePat (map cvtp ps) Boxed
290 cvtp (ConP s ps) = ConPatIn (cName s) (PrefixCon (map cvtp ps))
291 cvtp (TildeP p) = LazyPat (cvtp p)
292 cvtp (Meta.AsP s p) = AsPat (vName s) (cvtp p)
293 cvtp Meta.WildP = WildPat void
294 cvtp (RecP c fs) = ConPatIn (cName c) $ Hs.RecCon (map (\(s,p) -> (vName s,cvtp p)) fs)
295 cvtp (ListP ps) = ListPat (map cvtp ps) void
297 -----------------------------------------------------------
298 -- Types and type variables
300 cvt_tvs :: [String] -> [HsTyVarBndr RdrName]
301 cvt_tvs tvs = map (UserTyVar . tName) tvs
303 cvt_context :: Cxt -> HsContext RdrName
304 cvt_context tys = map cvt_pred tys
306 cvt_pred :: Meta.Type -> HsPred RdrName
307 cvt_pred ty = case split_ty_app ty of
308 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
309 other -> panic "Malformed predicate"
311 cvtType :: Meta.Type -> HsType RdrName
312 cvtType ty = trans (root ty [])
313 where root (AppT a b) zs = root a (cvtType b : zs)
316 trans (TupleT n,args)
317 | length args == n = HsTupleTy (HsTupCon Boxed n) args
318 | n == 0 = foldl HsAppTy (HsTyVar (tconName "()")) args
319 | otherwise = foldl HsAppTy (HsTyVar (tconName ("(" ++ replicate (n-1) ',' ++ ")"))) args
320 trans (ArrowT, [x,y]) = HsFunTy x y
321 trans (ListT, [x]) = HsListTy x
323 trans (VarT nm, args) = foldl HsAppTy (HsTyVar (tName nm)) args
324 trans (ConT tc, args) = foldl HsAppTy (HsTyVar (tconName tc)) args
326 trans (ForallT tvs cxt ty, []) = mkHsForAllTy (Just (cvt_tvs tvs))
330 split_ty_app :: Meta.Type -> (Meta.Type, [Meta.Type])
331 split_ty_app ty = go ty []
333 go (AppT f a) as = go f (a:as)
336 -----------------------------------------------------------
338 sigP (Meta.SigD _ _) = True
342 -----------------------------------------------------------
343 -- some useful things
345 truePat = ConPatIn (cName "True") (PrefixCon [])
346 falsePat = ConPatIn (cName "False") (PrefixCon [])
348 overloadedLit :: Lit -> Bool
349 -- True for literals that Haskell treats as overloaded
350 overloadedLit (IntegerL l) = True
351 overloadedLit (RationalL l) = True
352 overloadedLit l = False
355 void = placeHolderType
358 loc0 = generatedSrcLoc
361 vName :: String -> RdrName
362 vName = mkName varName
364 -- Constructor function names; this is Haskell source, hence srcDataName
365 cName :: String -> RdrName
366 cName = mkName srcDataName
368 -- Type variable names
369 tName :: String -> RdrName
370 tName = mkName tvName
372 -- Type Constructor names
373 tconName = mkName tcName
375 mkName :: NameSpace -> String -> RdrName
376 -- Parse the string to see if it has a "." or ":" in it
377 -- so we know whether to generate a qualified or original name
378 -- It's a bit tricky because we need to parse
379 -- Foo.Baz.x as Qual Foo.Baz x
380 -- So we parse it from back to front
383 = split [] (reverse str)
385 split occ [] = mkRdrUnqual (mk_occ occ)
386 split occ (c:d:rev) -- 'd' is the last char before the separator
387 | is_sep c -- E.g. Fo.x d='o'
388 && isAlphaNum d -- Fo.+: d='+' perhaps
389 = mk_qual (reverse (d:rev)) c occ
390 split occ (c:rev) = split (c:occ) rev
392 mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
393 mk_qual mod ':' occ = mkOrig (mk_mod mod) (mk_occ occ)
395 mk_occ occ = mkOccFS ns (mkFastString occ)
396 mk_mod mod = mkModuleName mod