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