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