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(..), HsBang(..),
18 Match(..), GRHSs(..), GRHS(..), HsPred(..),
19 HsDecl(..), TyClDecl(..), InstDecl(..), ConDecl(..),
20 Stmt(..), HsBinds(..), MonoBinds(..), Sig(..),
21 Pat(..), HsConDetails(..), HsOverLit, BangType(..),
22 placeHolderType, HsType(..),
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 )
33 import BasicTypes( Boxity(..), RecFlag(Recursive), NewOrData(..) )
34 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
36 import HsDecls ( CImportSpec(..), ForeignImport(..), ForeignExport(..),
38 import FastString( FastString, mkFastString, nilFS )
39 import Char ( ord, isAscii, isAlphaNum, isAlpha )
40 import List ( partition )
41 import ErrUtils (Message)
45 -------------------------------------------------------------------
46 convertToHsDecls :: [Meta.Dec] -> [Either (HsDecl RdrName) Message]
47 convertToHsDecls ds = map cvt_top ds
49 mk_con con = case con of
51 -> ConDecl (cName c) noExistentials noContext
52 (PrefixCon (map mk_arg strtys)) loc0
54 -> ConDecl (cName c) noExistentials noContext
55 (RecCon (map mk_id_arg varstrtys)) loc0
57 -> ConDecl (cName c) noExistentials noContext
58 (InfixCon (mk_arg st1) (mk_arg st2)) loc0
60 mk_arg (IsStrict, ty) = BangType HsStrict (cvtType ty)
61 mk_arg (NotStrict, ty) = BangType HsNoBang (cvtType ty)
63 mk_id_arg (i, IsStrict, ty)
64 = (vName i, BangType HsStrict (cvtType ty))
65 mk_id_arg (i, NotStrict, ty)
66 = (vName i, BangType HsNoBang (cvtType ty))
68 mk_derivs [] = Nothing
69 mk_derivs cs = Just [HsClassP (tconName c) [] | c <- cs]
71 cvt_top :: Meta.Dec -> Either (HsDecl RdrName) Message
72 cvt_top d@(Meta.ValD _ _ _) = Left $ Hs.ValD (cvtd d)
73 cvt_top d@(Meta.FunD _ _) = Left $ Hs.ValD (cvtd d)
75 cvt_top (TySynD tc tvs rhs)
76 = Left $ TyClD (TySynonym (tconName tc) (cvt_tvs tvs) (cvtType rhs) loc0)
78 cvt_top (DataD ctxt tc tvs constrs derivs)
79 = Left $ TyClD (mkTyData DataType
80 (cvt_context ctxt, tconName tc, cvt_tvs tvs)
82 (mk_derivs derivs) loc0)
84 cvt_top (NewtypeD ctxt tc tvs constr derivs)
85 = Left $ TyClD (mkTyData NewType
86 (cvt_context ctxt, tconName tc, cvt_tvs tvs)
88 (mk_derivs derivs) loc0)
90 cvt_top (ClassD ctxt cl tvs decs)
91 = Left $ TyClD (mkClassDecl (cvt_context ctxt, tconName cl, cvt_tvs tvs)
95 (binds,sigs) = cvtBindsAndSigs decs
97 cvt_top (InstanceD tys ty decs)
98 = Left $ InstD (InstDecl inst_ty binds sigs loc0)
100 (binds, sigs) = cvtBindsAndSigs decs
101 inst_ty = HsForAllTy Nothing
103 (HsPredTy (cvt_pred ty))
105 cvt_top (Meta.SigD nm typ) = Left $ Hs.SigD (Sig (vName nm) (cvtType typ) loc0)
107 cvt_top (ForeignD (ImportF callconv safety from nm typ))
109 Just (c_header, cis) ->
110 let i = CImport callconv' safety' c_header nilFS cis
111 in Left $ ForD (ForeignImport (vName nm) (cvtType typ) i False loc0)
112 Nothing -> Right $ text (show from)
113 <+> ptext SLIT("is not a valid ccall impent")
114 where callconv' = case callconv of
116 StdCall -> StdCallConv
117 safety' = case safety of
119 Safe -> PlaySafe False
120 Threadsafe -> PlaySafe True
121 parsed = parse_ccall_impent nm from
123 cvt_top (ForeignD (ExportF callconv as nm typ))
124 = let e = CExport (CExportStatic (mkFastString as) callconv')
125 in Left $ ForD (ForeignExport (vName nm) (cvtType typ) e False loc0)
126 where callconv' = case callconv of
128 StdCall -> StdCallConv
130 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
131 parse_ccall_impent nm s
132 = case lex_ccall_impent s of
133 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
134 Just ["wrapper"] -> Just (nilFS, CWrapper)
135 Just ("static":ts) -> parse_ccall_impent_static nm ts
136 Just ts -> parse_ccall_impent_static nm ts
139 parse_ccall_impent_static :: String
141 -> Maybe (FastString, CImportSpec)
142 parse_ccall_impent_static nm ts
143 = let ts' = case ts of
144 [ "&", cid] -> [ cid]
145 [fname, "&" ] -> [fname ]
146 [fname, "&", cid] -> [fname, cid]
149 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
150 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
151 [ ] -> Just (nilFS, mk_cid nm)
152 [fname ] -> Just (mkFastString fname, mk_cid nm)
154 where is_cid :: String -> Bool
155 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
156 mk_cid :: String -> CImportSpec
157 mk_cid = CFunction . StaticTarget . mkFastString
159 lex_ccall_impent :: String -> Maybe [String]
160 lex_ccall_impent "" = Just []
161 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
162 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
163 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
164 lex_ccall_impent xs = case span is_valid xs of
166 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
167 where is_valid :: Char -> Bool
168 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
174 -------------------------------------------------------------------
175 convertToHsExpr :: Meta.Exp -> HsExpr RdrName
176 convertToHsExpr = cvt
178 cvt (VarE s) = HsVar (vName s)
179 cvt (ConE s) = HsVar (cName s)
181 | overloadedLit l = HsOverLit (cvtOverLit l)
182 | otherwise = HsLit (cvtLit l)
184 cvt (AppE x y) = HsApp (cvt x) (cvt y)
185 cvt (LamE ps e) = HsLam (mkSimpleMatch (map cvtp ps) (cvt e) void loc0)
186 cvt (TupE [e]) = cvt e
187 cvt (TupE es) = ExplicitTuple(map cvt es) Boxed
188 cvt (CondE x y z) = HsIf (cvt x) (cvt y) (cvt z) loc0
189 cvt (LetE ds e) = HsLet (cvtdecs ds) (cvt e)
190 cvt (CaseE e ms) = HsCase (cvt e) (map cvtm ms) loc0
191 cvt (DoE ss) = HsDo DoExpr (cvtstmts ss) [] void loc0
192 cvt (CompE ss) = HsDo ListComp (cvtstmts ss) [] void loc0
193 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
194 cvt (ListE xs) = ExplicitList void (map cvt xs)
195 cvt (InfixE (Just x) s (Just y))
196 = HsPar (OpApp (cvt x) (cvt s) undefined (cvt y))
197 cvt (InfixE Nothing s (Just y)) = SectionR (cvt s) (cvt y)
198 cvt (InfixE (Just x) s Nothing ) = SectionL (cvt x) (cvt s)
199 cvt (InfixE Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
200 cvt (SigE e t) = ExprWithTySig (cvt e) (cvtType t)
201 cvt (RecConE c flds) = RecordCon (cName c) (map (\(x,y) -> (vName x, cvt y)) flds)
202 cvt (RecUpdE e flds) = RecordUpd (cvt e) (map (\(x,y) -> (vName x, cvt y)) flds)
204 cvtdecs :: [Meta.Dec] -> HsBinds RdrName
205 cvtdecs [] = EmptyBinds
206 cvtdecs ds = MonoBind binds sigs Recursive
208 (binds, sigs) = cvtBindsAndSigs ds
211 = (cvtds non_sigs, map cvtSig sigs)
213 (sigs, non_sigs) = partition sigP ds
215 cvtSig (Meta.SigD nm typ) = Hs.Sig (vName nm) (cvtType typ) loc0
217 cvtds :: [Meta.Dec] -> MonoBinds RdrName
218 cvtds [] = EmptyMonoBinds
219 cvtds (d:ds) = AndMonoBinds (cvtd d) (cvtds ds)
221 cvtd :: Meta.Dec -> MonoBinds RdrName
222 -- Used only for declarations in a 'let/where' clause,
223 -- not for top level decls
224 cvtd (Meta.ValD (Meta.VarP s) body ds) = FunMonoBind (vName s) False
225 [cvtclause (Clause [] body ds)] loc0
226 cvtd (FunD nm cls) = FunMonoBind (vName nm) False (map cvtclause cls) loc0
227 cvtd (Meta.ValD p body ds) = PatMonoBind (cvtp p) (GRHSs (cvtguard body)
230 cvtd x = panic "Illegal kind of declaration in where clause"
233 cvtclause :: Meta.Clause -> Hs.Match RdrName
234 cvtclause (Clause ps body wheres)
235 = Hs.Match (map cvtp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
239 cvtdd :: Range -> ArithSeqInfo RdrName
240 cvtdd (FromR x) = (From (cvt x))
241 cvtdd (FromThenR x y) = (FromThen (cvt x) (cvt y))
242 cvtdd (FromToR x y) = (FromTo (cvt x) (cvt y))
243 cvtdd (FromThenToR x y z) = (FromThenTo (cvt x) (cvt y) (cvt z))
246 cvtstmts :: [Meta.Stmt] -> [Hs.Stmt RdrName]
247 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
248 cvtstmts [NoBindS e] = [ResultStmt (cvt e) loc0] -- when its the last element use ResultStmt
249 cvtstmts (NoBindS e : ss) = ExprStmt (cvt e) void loc0 : cvtstmts ss
250 cvtstmts (Meta.BindS p e : ss) = BindStmt (cvtp p) (cvt e) loc0 : cvtstmts ss
251 cvtstmts (Meta.LetS ds : ss) = LetStmt (cvtdecs ds) : cvtstmts ss
252 cvtstmts (Meta.ParS dss : ss) = ParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
254 cvtm :: Meta.Match -> Hs.Match RdrName
255 cvtm (Meta.Match p body wheres)
256 = Hs.Match [cvtp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
258 cvtguard :: Meta.Body -> [GRHS RdrName]
259 cvtguard (GuardedB pairs) = map cvtpair pairs
260 cvtguard (NormalB e) = [GRHS [ ResultStmt (cvt e) loc0 ] loc0]
262 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
263 cvtpair (x,y) = GRHS [Hs.BindStmt truePat (cvt x) loc0,
264 ResultStmt (cvt y) loc0] loc0
266 cvtOverLit :: Lit -> HsOverLit
267 cvtOverLit (IntegerL i) = mkHsIntegral i
268 cvtOverLit (RationalL r) = mkHsFractional r
269 -- An Integer is like an an (overloaded) '3' in a Haskell source program
270 -- Similarly 3.5 for fractionals
272 cvtLit :: Lit -> HsLit
273 cvtLit (IntPrimL i) = HsIntPrim i
274 cvtLit (FloatPrimL f) = HsFloatPrim f
275 cvtLit (DoublePrimL f) = HsDoublePrim f
276 cvtLit (CharL c) = HsChar (ord c)
277 cvtLit (StringL s) = HsString (mkFastString s)
279 cvtp :: Meta.Pat -> Hs.Pat RdrName
281 | overloadedLit l = NPatIn (cvtOverLit l) Nothing -- Not right for negative
282 -- patterns; need to think
284 | otherwise = Hs.LitPat (cvtLit l)
285 cvtp (Meta.VarP s) = Hs.VarPat(vName s)
286 cvtp (TupP [p]) = cvtp p
287 cvtp (TupP ps) = TuplePat (map cvtp ps) Boxed
288 cvtp (ConP s ps) = ConPatIn (cName s) (PrefixCon (map cvtp ps))
289 cvtp (TildeP p) = LazyPat (cvtp p)
290 cvtp (Meta.AsP s p) = AsPat (vName s) (cvtp p)
291 cvtp Meta.WildP = WildPat void
292 cvtp (RecP c fs) = ConPatIn (cName c) $ Hs.RecCon (map (\(s,p) -> (vName s,cvtp p)) fs)
293 cvtp (ListP ps) = ListPat (map cvtp ps) void
295 -----------------------------------------------------------
296 -- Types and type variables
298 cvt_tvs :: [String] -> [HsTyVarBndr RdrName]
299 cvt_tvs tvs = map (UserTyVar . tName) tvs
301 cvt_context :: Cxt -> HsContext RdrName
302 cvt_context tys = map cvt_pred tys
304 cvt_pred :: Meta.Type -> HsPred RdrName
305 cvt_pred ty = case split_ty_app ty of
306 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
307 other -> panic "Malformed predicate"
309 cvtType :: Meta.Type -> HsType RdrName
310 cvtType ty = trans (root ty [])
311 where root (AppT a b) zs = root a (cvtType b : zs)
314 trans (TupleT n,args)
315 | length args == n = HsTupleTy Boxed args
316 | n == 0 = foldl HsAppTy (HsTyVar (tconName "()")) args
317 | otherwise = foldl HsAppTy (HsTyVar (tconName ("(" ++ replicate (n-1) ',' ++ ")"))) args
318 trans (ArrowT, [x,y]) = HsFunTy x y
319 trans (ListT, [x]) = HsListTy x
321 trans (VarT nm, args) = foldl HsAppTy (HsTyVar (tName nm)) args
322 trans (ConT tc, args) = foldl HsAppTy (HsTyVar (tconName tc)) args
324 trans (ForallT tvs cxt ty, []) = mkHsForAllTy (Just (cvt_tvs tvs))
328 split_ty_app :: Meta.Type -> (Meta.Type, [Meta.Type])
329 split_ty_app ty = go ty []
331 go (AppT f a) as = go f (a:as)
334 -----------------------------------------------------------
336 sigP (Meta.SigD _ _) = True
340 -----------------------------------------------------------
341 -- some useful things
343 truePat = ConPatIn (cName "True") (PrefixCon [])
344 falsePat = ConPatIn (cName "False") (PrefixCon [])
346 overloadedLit :: Lit -> Bool
347 -- True for literals that Haskell treats as overloaded
348 overloadedLit (IntegerL l) = True
349 overloadedLit (RationalL l) = True
350 overloadedLit l = False
353 void = placeHolderType
356 loc0 = generatedSrcLoc
359 vName :: String -> RdrName
360 vName = mkName varName
362 -- Constructor function names; this is Haskell source, hence srcDataName
363 cName :: String -> RdrName
364 cName = mkName srcDataName
366 -- Type variable names
367 tName :: String -> RdrName
368 tName = mkName tvName
370 -- Type Constructor names
371 tconName = mkName tcName
373 mkName :: NameSpace -> String -> RdrName
374 -- Parse the string to see if it has a "." or ":" in it
375 -- so we know whether to generate a qualified or original name
376 -- It's a bit tricky because we need to parse
377 -- Foo.Baz.x as Qual Foo.Baz x
378 -- So we parse it from back to front
381 = split [] (reverse str)
383 split occ [] = mkRdrUnqual (mk_occ occ)
384 split occ (c:d:rev) -- 'd' is the last char before the separator
385 | is_sep c -- E.g. Fo.x d='o'
386 && isAlphaNum d -- Fo.+: d='+' perhaps
387 = mk_qual (reverse (d:rev)) c occ
388 split occ (c:rev) = split (c:occ) rev
390 mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
391 mk_qual mod ':' occ = mkOrig (mk_mod mod) (mk_occ occ)
393 mk_occ occ = mkOccFS ns (mkFastString occ)
394 mk_mod mod = mkModuleName mod