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(..),
18 Match(..), GRHSs(..), GRHS(..), HsPred(..),
19 HsDecl(..), InstDecl(..), ConDecl(..),
20 Stmt(..), HsBinds(..), MonoBinds(..), Sig(..),
21 Pat(..), HsConDetails(..), HsOverLit, BangType(..),
22 placeHolderType, HsType(..), HsTupCon(..),
23 HsTyVarBndr(..), HsContext,
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(..) )
37 import HsDecls ( CImportSpec(..), ForeignImport(..), ForeignDecl(..) )
38 import FastString( mkFastString, nilFS )
39 import Char ( ord, isAlphaNum )
40 import List ( partition )
44 -------------------------------------------------------------------
45 convertToHsDecls :: [Meta.Dec] -> [HsDecl RdrName]
46 convertToHsDecls ds = map cvt_top ds
49 cvt_top d@(Val _ _ _) = ValD (cvtd d)
50 cvt_top d@(Fun _ _) = ValD (cvtd d)
52 cvt_top (Data tc tvs constrs derivs)
53 = TyClD (mkTyData DataType
54 (noContext, tconName tc, cvt_tvs tvs)
55 (DataCons (map mk_con constrs))
56 (mk_derivs derivs) loc0)
59 = ConDecl (cName c) noExistentials noContext
60 (PrefixCon (map mk_arg tys)) loc0
62 mk_arg ty = BangType NotMarkedStrict (cvtType ty)
64 mk_derivs [] = Nothing
65 mk_derivs cs = Just [HsClassP (tconName c) [] | c <- cs]
67 cvt_top (Class ctxt cl tvs decs)
68 = TyClD (mkClassDecl (cvt_context ctxt, tconName cl, cvt_tvs tvs)
70 sigs (Just binds) loc0)
72 (binds,sigs) = cvtBindsAndSigs decs
74 cvt_top (Instance tys ty decs)
75 = InstD (InstDecl inst_ty binds sigs Nothing loc0)
77 (binds, sigs) = cvtBindsAndSigs decs
78 inst_ty = HsForAllTy Nothing
80 (HsPredTy (cvt_pred ty))
82 cvt_top (Proto nm typ) = SigD (Sig (vName nm) (cvtType typ) loc0)
84 cvt_top (Foreign (Import callconv safety from nm typ))
85 = ForD (ForeignImport (vName nm) (cvtType typ) fi False loc0)
86 where fi = CImport callconv' safety' c_header nilFS cis
87 callconv' = case callconv of
89 StdCall -> StdCallConv
90 safety' = case safety of
92 Safe -> PlaySafe False
93 Threadsafe -> PlaySafe True
94 (c_header', c_func') = break (== ' ') from
95 c_header = mkFastString c_header'
97 cis = CFunction (StaticTarget (mkFastString c_func))
103 -------------------------------------------------------------------
104 convertToHsExpr :: Meta.Exp -> HsExpr RdrName
105 convertToHsExpr = cvt
107 cvt (Var s) = HsVar(vName s)
108 cvt (Con s) = HsVar(cName s)
110 | overloadedLit l = HsOverLit (cvtOverLit l)
111 | otherwise = HsLit (cvtLit l)
113 cvt (App x y) = HsApp (cvt x) (cvt y)
114 cvt (Lam ps e) = HsLam (mkSimpleMatch (map cvtp ps) (cvt e) void loc0)
115 cvt (Tup es) = ExplicitTuple(map cvt es) Boxed
116 cvt (Cond x y z) = HsIf (cvt x) (cvt y) (cvt z) loc0
117 cvt (Let ds e) = HsLet (cvtdecs ds) (cvt e)
118 cvt (Case e ms) = HsCase (cvt e) (map cvtm ms) loc0
119 cvt (Do ss) = HsDo DoExpr (cvtstmts ss) [] void loc0
120 cvt (Comp ss) = HsDo ListComp (cvtstmts ss) [] void loc0
121 cvt (ArithSeq dd) = ArithSeqIn (cvtdd dd)
122 cvt (ListExp xs) = ExplicitList void (map cvt xs)
123 cvt (Infix (Just x) s (Just y)) = OpApp (cvt x) (HsVar(vName s)) undefined (cvt y)
124 cvt (Infix Nothing s (Just y)) = SectionR (HsVar(vName s)) (cvt y)
125 cvt (Infix (Just x) s Nothing ) = SectionL (cvt x) (HsVar(vName s))
126 cvt (Infix Nothing s Nothing ) = HsVar(vName s) -- Can I indicate this is an infix thing?
127 cvt (SigExp e t) = ExprWithTySig (cvt e) (cvtType t)
129 cvtdecs :: [Meta.Dec] -> HsBinds RdrName
130 cvtdecs [] = EmptyBinds
131 cvtdecs ds = MonoBind binds sigs Recursive
133 (binds, sigs) = cvtBindsAndSigs ds
136 = (cvtds non_sigs, map cvtSig sigs)
138 (sigs, non_sigs) = partition sigP ds
140 cvtSig (Proto nm typ) = Sig (vName nm) (cvtType typ) loc0
142 cvtds :: [Meta.Dec] -> MonoBinds RdrName
143 cvtds [] = EmptyMonoBinds
144 cvtds (d:ds) = AndMonoBinds (cvtd d) (cvtds ds)
146 cvtd :: Meta.Dec -> MonoBinds RdrName
147 -- Used only for declarations in a 'let/where' clause,
148 -- not for top level decls
149 cvtd (Val (Pvar s) body ds) = FunMonoBind (vName s) False
150 (panic "what now?") loc0
151 cvtd (Fun nm cls) = FunMonoBind (vName nm) False (map cvtclause cls) loc0
152 cvtd (Val p body ds) = PatMonoBind (cvtp p) (GRHSs (cvtguard body)
155 cvtd x = panic "Illegal kind of declaration in where clause"
158 cvtclause :: Meta.Clause (Meta.Pat) (Meta.Exp) (Meta.Dec) -> Hs.Match RdrName
159 cvtclause (ps,body,wheres) = Match (map cvtp ps) Nothing
160 (GRHSs (cvtguard body) (cvtdecs wheres) void)
164 cvtdd :: Meta.DDt -> ArithSeqInfo RdrName
165 cvtdd (Meta.From x) = (Hs.From (cvt x))
166 cvtdd (Meta.FromThen x y) = (Hs.FromThen (cvt x) (cvt y))
167 cvtdd (Meta.FromTo x y) = (Hs.FromTo (cvt x) (cvt y))
168 cvtdd (Meta.FromThenTo x y z) = (Hs.FromThenTo (cvt x) (cvt y) (cvt z))
171 cvtstmts :: [Meta.Stm] -> [Hs.Stmt RdrName]
172 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
173 cvtstmts [NoBindSt e] = [ResultStmt (cvt e) loc0] -- when its the last element use ResultStmt
174 cvtstmts (NoBindSt e : ss) = ExprStmt (cvt e) void loc0 : cvtstmts ss
175 cvtstmts (BindSt p e : ss) = BindStmt (cvtp p) (cvt e) loc0 : cvtstmts ss
176 cvtstmts (LetSt ds : ss) = LetStmt (cvtdecs ds) : cvtstmts ss
177 cvtstmts (ParSt dss : ss) = ParStmt(map cvtstmts dss) : cvtstmts ss
180 cvtm :: Meta.Mat -> Hs.Match RdrName
181 cvtm (p,body,wheres) = Match [cvtp p] Nothing
182 (GRHSs (cvtguard body) (cvtdecs wheres) void)
184 cvtguard :: Meta.Rhs -> [GRHS RdrName]
185 cvtguard (Guarded pairs) = map cvtpair pairs
186 cvtguard (Normal e) = [GRHS [ ResultStmt (cvt e) loc0 ] loc0]
188 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
189 cvtpair (x,y) = GRHS [BindStmt truePat (cvt x) loc0,
190 ResultStmt (cvt y) loc0] loc0
192 cvtOverLit :: Lit -> HsOverLit
193 cvtOverLit (Integer i) = mkHsIntegral i
194 cvtOverLit (Rational r) = mkHsFractional r
195 -- An Integer is like an an (overloaded) '3' in a Haskell source program
196 -- Similarly 3.5 for fractionals
198 cvtLit :: Lit -> HsLit
199 cvtLit (Char c) = HsChar (ord c)
200 cvtLit (String s) = HsString (mkFastString s)
202 cvtp :: Meta.Pat -> Hs.Pat RdrName
204 | overloadedLit l = NPatIn (cvtOverLit l) Nothing -- Not right for negative
205 -- patterns; need to think
207 | otherwise = LitPat (cvtLit l)
208 cvtp (Pvar s) = VarPat(vName s)
209 cvtp (Ptup ps) = TuplePat (map cvtp ps) Boxed
210 cvtp (Pcon s ps) = ConPatIn (cName s) (PrefixCon (map cvtp ps))
211 cvtp (Ptilde p) = LazyPat (cvtp p)
212 cvtp (Paspat s p) = AsPat (vName s) (cvtp p)
213 cvtp Pwild = WildPat void
215 -----------------------------------------------------------
216 -- Types and type variables
218 cvt_tvs :: [String] -> [HsTyVarBndr RdrName]
219 cvt_tvs tvs = map (UserTyVar . tName) tvs
221 cvt_context :: Cxt -> HsContext RdrName
222 cvt_context tys = map cvt_pred tys
224 cvt_pred :: Typ -> HsPred RdrName
225 cvt_pred ty = case split_ty_app ty of
226 (Tvar tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
227 other -> panic "Malformed predicate"
229 cvtType :: Meta.Typ -> HsType RdrName
230 cvtType ty = trans (root ty [])
231 where root (Tapp a b) zs = root a (cvtType b : zs)
234 trans (Tcon (Tuple n),args) | length args == n
235 = HsTupleTy (HsTupCon Boxed n) args
236 trans (Tcon Arrow, [x,y]) = HsFunTy x y
237 trans (Tcon List, [x]) = HsListTy x
239 trans (Tvar nm, args) = foldl HsAppTy (HsTyVar (tName nm)) args
240 trans (Tcon tc, args) = foldl HsAppTy (HsTyVar (tc_name tc)) args
242 tc_name (TconName nm) = tconName nm
243 tc_name Arrow = tconName "->"
244 tc_name List = tconName "[]"
245 tc_name (Tuple 0) = tconName "()"
246 tc_name (Tuple n) = tconName ("(" ++ replicate (n-1) ',' ++ ")")
248 split_ty_app :: Typ -> (Typ, [Typ])
249 split_ty_app ty = go ty []
251 go (Tapp f a) as = go f (a:as)
254 -----------------------------------------------------------
256 sigP (Proto _ _) = True
260 -----------------------------------------------------------
261 -- some useful things
263 truePat = ConPatIn (cName "True") (PrefixCon [])
264 falsePat = ConPatIn (cName "False") (PrefixCon [])
266 overloadedLit :: Lit -> Bool
267 -- True for literals that Haskell treats as overloaded
268 overloadedLit (Integer l) = True
269 overloadedLit (Rational l) = True
270 overloadedLit l = False
273 void = placeHolderType
276 loc0 = generatedSrcLoc
279 vName :: String -> RdrName
280 vName = mkName varName
282 -- Constructor function names
283 cName :: String -> RdrName
284 cName = mkName dataName
286 -- Type variable names
287 tName :: String -> RdrName
288 tName = mkName tvName
290 -- Type Constructor names
291 tconName = mkName tcName
293 mkName :: NameSpace -> String -> RdrName
294 -- Parse the string to see if it has a "." or ":" in it
295 -- so we know whether to generate a qualified or original name
296 -- It's a bit tricky because we need to parse
297 -- Foo.Baz.x as Qual Foo.Baz x
298 -- So we parse it from back to front
301 = split [] (reverse str)
303 split occ [] = mkRdrUnqual (mk_occ occ)
304 split occ (c:d:rev) -- 'd' is the last char before the separator
305 | is_sep c -- E.g. Fo.x d='o'
306 && isAlphaNum d -- Fo.+: d='+' perhaps
307 = mk_qual (reverse (d:rev)) c occ
308 split occ (c:rev) = split (c:occ) rev
310 mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
311 mk_qual mod ':' occ = mkOrig (mk_mod mod) (mk_occ occ)
313 mk_occ occ = mkOccFS ns (mkFastString occ)
314 mk_mod mod = mkModuleName mod