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