41018f7edcbacc69d4c2a0774bb23910773db181
[ghc-hetmet.git] / ghc / compiler / hsSyn / Convert.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4
5 This module converts Template Haskell syntax into HsSyn
6
7
8 \begin{code}
9 module Convert( convertToHsExpr, convertToHsDecls ) where
10
11 #include "HsVersions.h"
12
13 import Language.Haskell.THSyntax as Meta
14
15 import HsSyn as Hs
16         (       HsExpr(..), HsLit(..), ArithSeqInfo(..), 
17                 HsStmtContext(..), 
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,
24                 mkSimpleMatch
25         ) 
26
27 import RdrName  ( RdrName, mkRdrUnqual, mkRdrQual, mkOrig )
28 import Module   ( mkModuleName )
29 import RdrHsSyn ( mkHsIntegral, mkClassDecl, mkTyData )
30 import OccName
31 import SrcLoc   ( SrcLoc, generatedSrcLoc )
32 import TyCon    ( DataConDetails(..) )
33 import Type     ( Type )
34 import BasicTypes( Boxity(..), RecFlag(Recursive), 
35                    NewOrData(..), StrictnessMark(..) )
36 import FastString( mkFastString )
37 import Char     ( ord, isAlphaNum )
38 import List     ( partition )
39 import Outputable
40
41
42 -------------------------------------------------------------------
43 convertToHsDecls :: [Meta.Dec] -> [HsDecl RdrName]
44 convertToHsDecls ds = map cvt_top ds
45
46
47 cvt_top d@(Val _ _ _) = ValD (cvtd d)
48 cvt_top d@(Fun _ _)   = ValD (cvtd d)
49  
50 cvt_top (Data tc tvs constrs derivs)
51   = TyClD (mkTyData DataType 
52                     (noContext, tconName tc, cvt_tvs tvs)
53                     (DataCons (map mk_con constrs))
54                     (mk_derivs derivs) loc0)
55   where
56     mk_con (Constr c tys)
57         = ConDecl (cName c) noExistentials noContext
58                     (PrefixCon (map mk_arg tys)) loc0
59
60     mk_arg ty = BangType NotMarkedStrict (cvtType ty)
61
62     mk_derivs [] = Nothing
63     mk_derivs cs = Just [HsClassP (tconName c) [] | c <- cs]
64
65 cvt_top (Class ctxt cl tvs decs)
66   = TyClD (mkClassDecl (cvt_context ctxt, tconName cl, cvt_tvs tvs)
67                        noFunDeps
68                        sigs (Just binds) loc0)
69   where
70     (binds,sigs) = cvtBindsAndSigs decs
71
72 cvt_top (Instance tys ty decs)
73   = InstD (InstDecl inst_ty binds sigs Nothing loc0)
74   where
75     (binds, sigs) = cvtBindsAndSigs decs
76     inst_ty = HsForAllTy Nothing 
77                          (cvt_context tys) 
78                          (HsPredTy (cvt_pred ty))
79
80 cvt_top (Proto nm typ) = SigD (Sig (vName nm) (cvtType typ) loc0)
81
82 noContext      = []
83 noExistentials = []
84 noFunDeps      = []
85
86 -------------------------------------------------------------------
87 convertToHsExpr :: Meta.Exp -> HsExpr RdrName
88 convertToHsExpr = cvt
89
90 cvt (Var s)       = HsVar(vName s)
91 cvt (Con s)       = HsVar(cName s)
92 cvt (Lit l) 
93   | overloadedLit l = HsOverLit (cvtOverLit l)
94   | otherwise       = HsLit (cvtLit l)
95
96 cvt (App x y)     = HsApp (cvt x) (cvt y)
97 cvt (Lam ps e)    = HsLam (mkSimpleMatch (map cvtp ps) (cvt e) void loc0)
98 cvt (Tup es)      = ExplicitTuple(map cvt es) Boxed
99 cvt (Cond x y z)  = HsIf (cvt x) (cvt y) (cvt z) loc0
100 cvt (Let ds e)    = HsLet (cvtdecs ds) (cvt e)
101 cvt (Case e ms)   = HsCase (cvt e) (map cvtm ms) loc0
102 cvt (Do ss)       = HsDo DoExpr (cvtstmts ss) [] void loc0
103 cvt (Comp ss)     = HsDo ListComp (cvtstmts ss) [] void loc0
104 cvt (ArithSeq dd) = ArithSeqIn (cvtdd dd)
105 cvt (ListExp xs)  = ExplicitList void (map cvt xs)
106 cvt (Infix (Just x) s (Just y)) = OpApp (cvt x) (HsVar(vName s)) undefined (cvt y)
107 cvt (Infix Nothing  s (Just y)) = SectionR (HsVar(vName s)) (cvt y)
108 cvt (Infix (Just x) s Nothing ) = SectionL (cvt x) (HsVar(vName s))
109 cvt (Infix Nothing  s Nothing ) = HsVar(vName s) -- Can I indicate this is an infix thing?
110
111
112 cvtdecs :: [Meta.Dec] -> HsBinds RdrName
113 cvtdecs [] = EmptyBinds
114 cvtdecs ds = MonoBind binds sigs Recursive
115            where
116              (binds, sigs) = cvtBindsAndSigs ds
117
118 cvtBindsAndSigs ds 
119   = (cvtds non_sigs, map cvtSig sigs)
120   where 
121     (sigs, non_sigs) = partition sigP ds
122
123 cvtSig (Proto nm typ) = Sig (vName nm) (cvtType typ) loc0
124
125 cvtds :: [Meta.Dec] -> MonoBinds RdrName
126 cvtds []     = EmptyMonoBinds
127 cvtds (d:ds) = AndMonoBinds (cvtd d) (cvtds ds)
128
129 cvtd :: Meta.Dec -> MonoBinds RdrName
130 -- Used only for declarations in a 'let/where' clause,
131 -- not for top level decls
132 cvtd (Val (Pvar s) body ds) = FunMonoBind (vName s) False 
133                                           (panic "what now?") loc0
134 cvtd (Fun nm cls)           = FunMonoBind (vName nm) False (map cvtclause cls) loc0
135 cvtd (Val p body ds)        = PatMonoBind (cvtp p) (GRHSs (cvtguard body) 
136                                                           (cvtdecs ds) 
137                                                           void) loc0
138 cvtd x = panic "Illegal kind of declaration in where clause" 
139
140
141 cvtclause :: Meta.Clause (Meta.Pat) (Meta.Exp) (Meta.Dec) -> Hs.Match RdrName
142 cvtclause (ps,body,wheres) = Match (map cvtp ps) Nothing 
143                              (GRHSs (cvtguard body) (cvtdecs wheres) void)
144
145
146
147 cvtdd :: Meta.DDt -> ArithSeqInfo RdrName
148 cvtdd (Meta.From x)           = (Hs.From (cvt x))
149 cvtdd (Meta.FromThen x y)     = (Hs.FromThen (cvt x) (cvt y))
150 cvtdd (Meta.FromTo x y)       = (Hs.FromTo (cvt x) (cvt y))
151 cvtdd (Meta.FromThenTo x y z) = (Hs.FromThenTo (cvt x) (cvt y) (cvt z))
152
153
154 cvtstmts :: [Meta.Stm] -> [Hs.Stmt RdrName]
155 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
156 cvtstmts [NoBindSt e]      = [ResultStmt (cvt e) loc0]      -- when its the last element use ResultStmt
157 cvtstmts (NoBindSt e : ss) = ExprStmt (cvt e) void loc0     : cvtstmts ss
158 cvtstmts (BindSt p e : ss) = BindStmt (cvtp p) (cvt e) loc0 : cvtstmts ss
159 cvtstmts (LetSt ds : ss)   = LetStmt (cvtdecs ds)           : cvtstmts ss
160 cvtstmts (ParSt dss : ss)  = ParStmt(map cvtstmts dss)      : cvtstmts ss
161
162
163 cvtm :: Meta.Mat -> Hs.Match RdrName
164 cvtm (p,body,wheres) = Match [cvtp p] Nothing 
165                              (GRHSs (cvtguard body) (cvtdecs wheres) void)
166                              
167 cvtguard :: Meta.Rhs -> [GRHS RdrName]
168 cvtguard (Guarded pairs) = map cvtpair pairs
169 cvtguard (Normal e)      = [GRHS [  ResultStmt (cvt e) loc0 ] loc0]
170
171 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
172 cvtpair (x,y) = GRHS [BindStmt truePat (cvt x) loc0,
173                       ResultStmt (cvt y) loc0] loc0
174
175 cvtOverLit :: Lit -> HsOverLit
176 cvtOverLit (Int i) = mkHsIntegral (fromInt i)
177 -- An Int is like an an (overloaded) '3' in a Haskell source program
178
179 cvtLit :: Lit -> HsLit
180 cvtLit (Char c)       = HsChar (ord c)
181 cvtLit (CrossStage s) = error "What do we do about crossStage constants?"
182
183 cvtp :: Meta.Pat -> Hs.Pat RdrName
184 cvtp (Plit l)
185   | overloadedLit l = NPatIn (cvtOverLit l) Nothing     -- Not right for negative
186                                                         -- patterns; need to think
187                                                         -- about that!
188   | otherwise       = LitPat (cvtLit l)
189 cvtp (Pvar s)     = VarPat(vName s)
190 cvtp (Ptup ps)    = TuplePat (map cvtp ps) Boxed
191 cvtp (Pcon s ps)  = ConPatIn (cName s) (PrefixCon (map cvtp ps))
192 cvtp (Ptilde p)   = LazyPat (cvtp p)
193 cvtp (Paspat s p) = AsPat (vName s) (cvtp p)
194 cvtp Pwild        = WildPat void
195
196 -----------------------------------------------------------
197 --      Types and type variables
198
199 cvt_tvs :: [String] -> [HsTyVarBndr RdrName]
200 cvt_tvs tvs = map (UserTyVar . tName) tvs
201
202 cvt_context :: Cxt -> HsContext RdrName 
203 cvt_context tys = map cvt_pred tys
204
205 cvt_pred :: Typ -> HsPred RdrName
206 cvt_pred ty = case split_ty_app ty of
207                 (Tvar tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
208                 other -> panic "Malformed predicate"
209
210 cvtType :: Meta.Typ -> HsType RdrName
211 cvtType ty = trans (root ty [])
212   where root (Tapp a b) zs = root a (cvtType b : zs)
213         root t zs          = (t,zs)
214
215         trans (Tcon (Tuple n),args) | length args == n
216                                     = HsTupleTy (HsTupCon Boxed n) args
217         trans (Tcon Arrow,   [x,y]) = HsFunTy x y
218         trans (Tcon List,    [x])   = HsListTy x
219
220         trans (Tvar nm, args)       = foldl HsAppTy (HsTyVar (tName nm)) args
221         trans (Tcon tc, args)       = foldl HsAppTy (HsTyVar (tc_name tc)) args
222
223         tc_name (TconName nm) = tconName nm
224         tc_name Arrow         = tconName "->"
225         tc_name List          = tconName "[]"
226         tc_name (Tuple 0)     = tconName "()"
227         tc_name (Tuple n)     = tconName ("(" ++ replicate (n-1) ',' ++ ")")
228
229 split_ty_app :: Typ -> (Typ, [Typ])
230 split_ty_app ty = go ty []
231   where
232     go (Tapp f a) as = go f (a:as)
233     go f as          = (f,as)
234
235 -----------------------------------------------------------
236 sigP :: Dec -> Bool
237 sigP (Proto _ _) = True
238 sigP other       = False
239
240
241 -----------------------------------------------------------
242 -- some useful things
243
244 truePat  = ConPatIn (cName "True") (PrefixCon [])
245 falsePat = ConPatIn (cName "False") (PrefixCon [])
246
247 overloadedLit :: Lit -> Bool
248 -- True for literals that Haskell treats as overloaded
249 overloadedLit (Int l) = True
250 overloadedLit l       = False
251
252 void :: Type.Type
253 void = placeHolderType
254
255 loc0 :: SrcLoc
256 loc0 = generatedSrcLoc
257
258 fromInt :: Int -> Integer
259 fromInt x = toInteger x
260
261 -- variable names
262 vName :: String -> RdrName
263 vName = mkName varName
264
265 -- Constructor function names
266 cName :: String -> RdrName
267 cName = mkName dataName
268
269 -- Type variable names
270 tName :: String -> RdrName
271 tName = mkName tvName
272
273 -- Type Constructor names
274 tconName = mkName tcName
275
276 mkName :: NameSpace -> String -> RdrName
277 -- Parse the string to see if it has a "." or ":" in it
278 -- so we know whether to generate a qualified or original name
279 -- It's a bit tricky because we need to parse 
280 --      Foo.Baz.x as Qual Foo.Baz x
281 -- So we parse it from back to front
282
283 mkName ns str
284   = split [] (reverse str)
285   where
286     split occ [] = mkRdrUnqual (mk_occ occ)
287     split occ (c:d:rev)         -- 'd' is the last char before the separator
288         |  is_sep c             -- E.g.         Fo.x    d='o'
289         && isAlphaNum d         --              Fo.+:   d='+' perhaps
290         = mk_qual (reverse (d:rev)) c occ
291     split occ (c:rev) = split (c:occ) rev
292
293     mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
294     mk_qual mod ':' occ = mkOrig    (mk_mod mod) (mk_occ occ)
295
296     mk_occ occ = mkOccFS ns (mkFastString occ)
297     mk_mod mod = mkModuleName mod
298
299     is_sep '.'   = True
300     is_sep ':'   = True
301     is_sep other = False
302 \end{code}