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(..), HsExplicitForAll(..),
23 HsTyVarBndr(..), HsContext,
24 mkSimpleMatch, mkImplicitHsForAllTy, mkExplicitHsForAllTy
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 = mkImplicitHsForAllTy (cvt_context tys) (HsPredTy (cvt_pred ty))
103 cvt_top (Meta.SigD nm typ) = Left $ Hs.SigD (Sig (vName nm) (cvtType typ) loc0)
105 cvt_top (ForeignD (ImportF callconv safety from nm typ))
107 Just (c_header, cis) ->
108 let i = CImport callconv' safety' c_header nilFS cis
109 in Left $ ForD (ForeignImport (vName nm) (cvtType typ) i False loc0)
110 Nothing -> Right $ text (show from)
111 <+> ptext SLIT("is not a valid ccall impent")
112 where callconv' = case callconv of
114 StdCall -> StdCallConv
115 safety' = case safety of
117 Safe -> PlaySafe False
118 Threadsafe -> PlaySafe True
119 parsed = parse_ccall_impent nm from
121 cvt_top (ForeignD (ExportF callconv as nm typ))
122 = let e = CExport (CExportStatic (mkFastString as) callconv')
123 in Left $ ForD (ForeignExport (vName nm) (cvtType typ) e False loc0)
124 where callconv' = case callconv of
126 StdCall -> StdCallConv
128 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
129 parse_ccall_impent nm s
130 = case lex_ccall_impent s of
131 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
132 Just ["wrapper"] -> Just (nilFS, CWrapper)
133 Just ("static":ts) -> parse_ccall_impent_static nm ts
134 Just ts -> parse_ccall_impent_static nm ts
137 parse_ccall_impent_static :: String
139 -> Maybe (FastString, CImportSpec)
140 parse_ccall_impent_static nm ts
141 = let ts' = case ts of
142 [ "&", cid] -> [ cid]
143 [fname, "&" ] -> [fname ]
144 [fname, "&", cid] -> [fname, cid]
147 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
148 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
149 [ ] -> Just (nilFS, mk_cid nm)
150 [fname ] -> Just (mkFastString fname, mk_cid nm)
152 where is_cid :: String -> Bool
153 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
154 mk_cid :: String -> CImportSpec
155 mk_cid = CFunction . StaticTarget . mkFastString
157 lex_ccall_impent :: String -> Maybe [String]
158 lex_ccall_impent "" = Just []
159 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
160 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
161 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
162 lex_ccall_impent xs = case span is_valid xs of
164 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
165 where is_valid :: Char -> Bool
166 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
172 -------------------------------------------------------------------
173 convertToHsExpr :: Meta.Exp -> HsExpr RdrName
174 convertToHsExpr = cvt
176 cvt (VarE s) = HsVar (vName s)
177 cvt (ConE s) = HsVar (cName s)
179 | overloadedLit l = HsOverLit (cvtOverLit l)
180 | otherwise = HsLit (cvtLit l)
182 cvt (AppE x y) = HsApp (cvt x) (cvt y)
183 cvt (LamE ps e) = HsLam (mkSimpleMatch (map cvtp ps) (cvt e) void loc0)
184 cvt (TupE [e]) = cvt e
185 cvt (TupE es) = ExplicitTuple(map cvt es) Boxed
186 cvt (CondE x y z) = HsIf (cvt x) (cvt y) (cvt z) loc0
187 cvt (LetE ds e) = HsLet (cvtdecs ds) (cvt e)
188 cvt (CaseE e ms) = HsCase (cvt e) (map cvtm ms) loc0
189 cvt (DoE ss) = HsDo DoExpr (cvtstmts ss) [] void loc0
190 cvt (CompE ss) = HsDo ListComp (cvtstmts ss) [] void loc0
191 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
192 cvt (ListE xs) = ExplicitList void (map cvt xs)
193 cvt (InfixE (Just x) s (Just y))
194 = HsPar (OpApp (cvt x) (cvt s) undefined (cvt y))
195 cvt (InfixE Nothing s (Just y)) = SectionR (cvt s) (cvt y)
196 cvt (InfixE (Just x) s Nothing ) = SectionL (cvt x) (cvt s)
197 cvt (InfixE Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
198 cvt (SigE e t) = ExprWithTySig (cvt e) (cvtType t)
199 cvt (RecConE c flds) = RecordCon (cName c) (map (\(x,y) -> (vName x, cvt y)) flds)
200 cvt (RecUpdE e flds) = RecordUpd (cvt e) (map (\(x,y) -> (vName x, cvt y)) flds)
202 cvtdecs :: [Meta.Dec] -> HsBinds RdrName
203 cvtdecs [] = EmptyBinds
204 cvtdecs ds = MonoBind binds sigs Recursive
206 (binds, sigs) = cvtBindsAndSigs ds
209 = (cvtds non_sigs, map cvtSig sigs)
211 (sigs, non_sigs) = partition sigP ds
213 cvtSig (Meta.SigD nm typ) = Hs.Sig (vName nm) (cvtType typ) loc0
215 cvtds :: [Meta.Dec] -> MonoBinds RdrName
216 cvtds [] = EmptyMonoBinds
217 cvtds (d:ds) = AndMonoBinds (cvtd d) (cvtds ds)
219 cvtd :: Meta.Dec -> MonoBinds RdrName
220 -- Used only for declarations in a 'let/where' clause,
221 -- not for top level decls
222 cvtd (Meta.ValD (Meta.VarP s) body ds) = FunMonoBind (vName s) False
223 [cvtclause (Clause [] body ds)] loc0
224 cvtd (FunD nm cls) = FunMonoBind (vName nm) False (map cvtclause cls) loc0
225 cvtd (Meta.ValD p body ds) = PatMonoBind (cvtp p) (GRHSs (cvtguard body)
228 cvtd x = panic "Illegal kind of declaration in where clause"
231 cvtclause :: Meta.Clause -> Hs.Match RdrName
232 cvtclause (Clause ps body wheres)
233 = Hs.Match (map cvtp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
237 cvtdd :: Range -> ArithSeqInfo RdrName
238 cvtdd (FromR x) = (From (cvt x))
239 cvtdd (FromThenR x y) = (FromThen (cvt x) (cvt y))
240 cvtdd (FromToR x y) = (FromTo (cvt x) (cvt y))
241 cvtdd (FromThenToR x y z) = (FromThenTo (cvt x) (cvt y) (cvt z))
244 cvtstmts :: [Meta.Stmt] -> [Hs.Stmt RdrName]
245 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
246 cvtstmts [NoBindS e] = [ResultStmt (cvt e) loc0] -- when its the last element use ResultStmt
247 cvtstmts (NoBindS e : ss) = ExprStmt (cvt e) void loc0 : cvtstmts ss
248 cvtstmts (Meta.BindS p e : ss) = BindStmt (cvtp p) (cvt e) loc0 : cvtstmts ss
249 cvtstmts (Meta.LetS ds : ss) = LetStmt (cvtdecs ds) : cvtstmts ss
250 cvtstmts (Meta.ParS dss : ss) = ParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
252 cvtm :: Meta.Match -> Hs.Match RdrName
253 cvtm (Meta.Match p body wheres)
254 = Hs.Match [cvtp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
256 cvtguard :: Meta.Body -> [GRHS RdrName]
257 cvtguard (GuardedB pairs) = map cvtpair pairs
258 cvtguard (NormalB e) = [GRHS [ ResultStmt (cvt e) loc0 ] loc0]
260 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
261 cvtpair (x,y) = GRHS [Hs.BindStmt truePat (cvt x) loc0,
262 ResultStmt (cvt y) loc0] loc0
264 cvtOverLit :: Lit -> HsOverLit
265 cvtOverLit (IntegerL i) = mkHsIntegral i
266 cvtOverLit (RationalL r) = mkHsFractional r
267 -- An Integer is like an an (overloaded) '3' in a Haskell source program
268 -- Similarly 3.5 for fractionals
270 cvtLit :: Lit -> HsLit
271 cvtLit (IntPrimL i) = HsIntPrim i
272 cvtLit (FloatPrimL f) = HsFloatPrim f
273 cvtLit (DoublePrimL f) = HsDoublePrim f
274 cvtLit (CharL c) = HsChar (ord c)
275 cvtLit (StringL s) = HsString (mkFastString s)
277 cvtp :: Meta.Pat -> Hs.Pat RdrName
279 | overloadedLit l = NPatIn (cvtOverLit l) Nothing -- Not right for negative
280 -- patterns; need to think
282 | otherwise = Hs.LitPat (cvtLit l)
283 cvtp (Meta.VarP s) = Hs.VarPat(vName s)
284 cvtp (TupP [p]) = cvtp p
285 cvtp (TupP ps) = TuplePat (map cvtp ps) Boxed
286 cvtp (ConP s ps) = ConPatIn (cName s) (PrefixCon (map cvtp ps))
287 cvtp (TildeP p) = LazyPat (cvtp p)
288 cvtp (Meta.AsP s p) = AsPat (vName s) (cvtp p)
289 cvtp Meta.WildP = WildPat void
290 cvtp (RecP c fs) = ConPatIn (cName c) $ Hs.RecCon (map (\(s,p) -> (vName s,cvtp p)) fs)
291 cvtp (ListP ps) = ListPat (map cvtp ps) void
293 -----------------------------------------------------------
294 -- Types and type variables
296 cvt_tvs :: [String] -> [HsTyVarBndr RdrName]
297 cvt_tvs tvs = map (UserTyVar . tName) tvs
299 cvt_context :: Cxt -> HsContext RdrName
300 cvt_context tys = map cvt_pred tys
302 cvt_pred :: Meta.Type -> HsPred RdrName
303 cvt_pred ty = case split_ty_app ty of
304 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
305 other -> pprPanic "Malformed predicate" (ppr ty)
307 cvtType :: Meta.Type -> HsType RdrName
308 cvtType ty = trans (root ty [])
309 where root (AppT a b) zs = root a (cvtType b : zs)
312 trans (TupleT n,args)
313 | length args == n = HsTupleTy Boxed args
314 | n == 0 = foldl HsAppTy (HsTyVar (tconName "()")) args
315 | otherwise = foldl HsAppTy (HsTyVar (tconName ("(" ++ replicate (n-1) ',' ++ ")"))) args
316 trans (ArrowT, [x,y]) = HsFunTy x y
317 trans (ListT, [x]) = HsListTy x
319 trans (VarT nm, args) = foldl HsAppTy (HsTyVar (tName nm)) args
320 trans (ConT tc, args) = foldl HsAppTy (HsTyVar (tconName tc)) args
322 trans (ForallT tvs cxt ty, []) = mkExplicitHsForAllTy
323 (cvt_tvs tvs) (cvt_context cxt) (cvtType ty)
325 split_ty_app :: Meta.Type -> (Meta.Type, [Meta.Type])
326 split_ty_app ty = go ty []
328 go (AppT f a) as = go f (a:as)
331 -----------------------------------------------------------
333 sigP (Meta.SigD _ _) = True
337 -----------------------------------------------------------
338 -- some useful things
340 truePat = ConPatIn (cName "True") (PrefixCon [])
341 falsePat = ConPatIn (cName "False") (PrefixCon [])
343 overloadedLit :: Lit -> Bool
344 -- True for literals that Haskell treats as overloaded
345 overloadedLit (IntegerL l) = True
346 overloadedLit (RationalL l) = True
347 overloadedLit l = False
350 void = placeHolderType
353 loc0 = generatedSrcLoc
356 vName :: String -> RdrName
357 vName = mkName varName
359 -- Constructor function names; this is Haskell source, hence srcDataName
360 cName :: String -> RdrName
361 cName = mkName srcDataName
363 -- Type variable names
364 tName :: String -> RdrName
365 tName = mkName tvName
367 -- Type Constructor names
368 tconName = mkName tcName
370 mkName :: NameSpace -> String -> RdrName
371 -- Parse the string to see if it has a "." or ":" in it
372 -- so we know whether to generate a qualified or original name
373 -- It's a bit tricky because we need to parse
374 -- Foo.Baz.x as Qual Foo.Baz x
375 -- So we parse it from back to front
378 = split [] (reverse str)
380 split occ [] = mkRdrUnqual (mk_occ occ)
381 split occ (c:d:rev) -- 'd' is the last char before the separator
382 | is_sep c -- E.g. Fo.x d='o'
383 && isAlphaNum d -- Fo.+: d='+' perhaps
384 = mk_qual (reverse (d:rev)) c occ
385 split occ (c:rev) = split (c:occ) rev
387 mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
388 mk_qual mod ':' occ = mkOrig (mk_mod mod) (mk_occ occ)
390 mk_occ occ = mkOccFS ns (mkFastString occ)
391 mk_mod mod = mkModuleName mod