[project @ 2002-11-08 09:01:06 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 callconv' safety' c_header nilFS cis
87           callconv' = case callconv of
88                           CCall -> CCallConv
89                           StdCall -> StdCallConv
90           safety' = case safety of
91                         Unsafe     -> PlayRisky
92                         Safe       -> PlaySafe False
93                         Threadsafe -> PlaySafe True
94           (c_header', c_func') = break (== ' ') from
95           c_header = mkFastString c_header'
96           c_func = tail c_func'
97           cis = CFunction (StaticTarget (mkFastString c_func))
98
99 noContext      = []
100 noExistentials = []
101 noFunDeps      = []
102
103 -------------------------------------------------------------------
104 convertToHsExpr :: Meta.Exp -> HsExpr RdrName
105 convertToHsExpr = cvt
106
107 cvt (Var s)       = HsVar(vName s)
108 cvt (Con s)       = HsVar(cName s)
109 cvt (Lit l) 
110   | overloadedLit l = HsOverLit (cvtOverLit l)
111   | otherwise       = HsLit (cvtLit l)
112
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)
128
129 cvtdecs :: [Meta.Dec] -> HsBinds RdrName
130 cvtdecs [] = EmptyBinds
131 cvtdecs ds = MonoBind binds sigs Recursive
132            where
133              (binds, sigs) = cvtBindsAndSigs ds
134
135 cvtBindsAndSigs ds 
136   = (cvtds non_sigs, map cvtSig sigs)
137   where 
138     (sigs, non_sigs) = partition sigP ds
139
140 cvtSig (Proto nm typ) = Sig (vName nm) (cvtType typ) loc0
141
142 cvtds :: [Meta.Dec] -> MonoBinds RdrName
143 cvtds []     = EmptyMonoBinds
144 cvtds (d:ds) = AndMonoBinds (cvtd d) (cvtds ds)
145
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) 
153                                                           (cvtdecs ds) 
154                                                           void) loc0
155 cvtd x = panic "Illegal kind of declaration in where clause" 
156
157
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)
161
162
163
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))
169
170
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
178
179
180 cvtm :: Meta.Mat -> Hs.Match RdrName
181 cvtm (p,body,wheres) = Match [cvtp p] Nothing 
182                              (GRHSs (cvtguard body) (cvtdecs wheres) void)
183                              
184 cvtguard :: Meta.Rhs -> [GRHS RdrName]
185 cvtguard (Guarded pairs) = map cvtpair pairs
186 cvtguard (Normal e)      = [GRHS [  ResultStmt (cvt e) loc0 ] loc0]
187
188 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
189 cvtpair (x,y) = GRHS [BindStmt truePat (cvt x) loc0,
190                       ResultStmt (cvt y) loc0] loc0
191
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
197
198 cvtLit :: Lit -> HsLit
199 cvtLit (Char c)   = HsChar (ord c)
200 cvtLit (String s) = HsString (mkFastString s)
201
202 cvtp :: Meta.Pat -> Hs.Pat RdrName
203 cvtp (Plit l)
204   | overloadedLit l = NPatIn (cvtOverLit l) Nothing     -- Not right for negative
205                                                         -- patterns; need to think
206                                                         -- about that!
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
214
215 -----------------------------------------------------------
216 --      Types and type variables
217
218 cvt_tvs :: [String] -> [HsTyVarBndr RdrName]
219 cvt_tvs tvs = map (UserTyVar . tName) tvs
220
221 cvt_context :: Cxt -> HsContext RdrName 
222 cvt_context tys = map cvt_pred tys
223
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"
228
229 cvtType :: Meta.Typ -> HsType RdrName
230 cvtType ty = trans (root ty [])
231   where root (Tapp a b) zs = root a (cvtType b : zs)
232         root t zs          = (t,zs)
233
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
238
239         trans (Tvar nm, args)       = foldl HsAppTy (HsTyVar (tName nm)) args
240         trans (Tcon tc, args)       = foldl HsAppTy (HsTyVar (tc_name tc)) args
241
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) ',' ++ ")")
247
248 split_ty_app :: Typ -> (Typ, [Typ])
249 split_ty_app ty = go ty []
250   where
251     go (Tapp f a) as = go f (a:as)
252     go f as          = (f,as)
253
254 -----------------------------------------------------------
255 sigP :: Dec -> Bool
256 sigP (Proto _ _) = True
257 sigP other       = False
258
259
260 -----------------------------------------------------------
261 -- some useful things
262
263 truePat  = ConPatIn (cName "True") (PrefixCon [])
264 falsePat = ConPatIn (cName "False") (PrefixCon [])
265
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
271
272 void :: Type.Type
273 void = placeHolderType
274
275 loc0 :: SrcLoc
276 loc0 = generatedSrcLoc
277
278 -- variable names
279 vName :: String -> RdrName
280 vName = mkName varName
281
282 -- Constructor function names
283 cName :: String -> RdrName
284 cName = mkName dataName
285
286 -- Type variable names
287 tName :: String -> RdrName
288 tName = mkName tvName
289
290 -- Type Constructor names
291 tconName = mkName tcName
292
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
299
300 mkName ns str
301   = split [] (reverse str)
302   where
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
309
310     mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
311     mk_qual mod ':' occ = mkOrig    (mk_mod mod) (mk_occ occ)
312
313     mk_occ occ = mkOccFS ns (mkFastString occ)
314     mk_mod mod = mkModuleName mod
315
316     is_sep '.'   = True
317     is_sep ':'   = True
318     is_sep other = False
319 \end{code}