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