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