[project @ 2003-06-24 07:58:18 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(..), 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         NormalC c strtys
51          -> ConDecl (cName c) noExistentials noContext
52                   (PrefixCon (map mk_arg strtys)) loc0
53         RecC c varstrtys
54          -> ConDecl (cName c) noExistentials noContext
55                   (RecCon (map mk_id_arg varstrtys)) loc0
56         InfixC st1 c st2
57          -> ConDecl (cName c) noExistentials noContext
58                   (InfixCon (mk_arg st1) (mk_arg st2)) loc0
59   where
60     mk_arg (IsStrict, ty) = BangType MarkedUserStrict (cvtType ty)
61     mk_arg (NotStrict, ty) = BangType NotMarkedStrict (cvtType ty)
62
63     mk_id_arg (i, IsStrict, ty)
64         = (vName i, BangType MarkedUserStrict (cvtType ty))
65     mk_id_arg (i, NotStrict, 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@(Meta.ValD _ _ _) = Left $ Hs.ValD (cvtd d)
73 cvt_top d@(Meta.FunD _ _)   = Left $ Hs.ValD (cvtd d)
74  
75 cvt_top (TySynD tc tvs rhs)
76   = Left $ TyClD (TySynonym (tconName tc) (cvt_tvs tvs) (cvtType rhs) loc0)
77
78 cvt_top (DataD 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 (NewtypeD 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 (ClassD 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 (InstanceD 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 (Meta.SigD nm typ) = Left $ Hs.SigD (Sig (vName nm) (cvtType typ) loc0)
106
107 cvt_top (ForeignD (ImportF 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 (VarE s)      = HsVar (vName s)
172 cvt (ConE s)      = HsVar (cName s)
173 cvt (LitE l) 
174   | overloadedLit l = HsOverLit (cvtOverLit l)
175   | otherwise       = HsLit (cvtLit l)
176
177 cvt (AppE x y)     = HsApp (cvt x) (cvt y)
178 cvt (LamE ps e)    = HsLam (mkSimpleMatch (map cvtp ps) (cvt e) void loc0)
179 cvt (TupE [e])    = cvt e
180 cvt (TupE es)     = ExplicitTuple(map cvt es) Boxed
181 cvt (CondE x y z)  = HsIf (cvt x) (cvt y) (cvt z) loc0
182 cvt (LetE ds e)   = HsLet (cvtdecs ds) (cvt e)
183 cvt (CaseE e ms)   = HsCase (cvt e) (map cvtm ms) loc0
184 cvt (DoE ss)      = HsDo DoExpr (cvtstmts ss) [] void loc0
185 cvt (CompE ss)     = HsDo ListComp (cvtstmts ss) [] void loc0
186 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
187 cvt (ListE xs)  = ExplicitList void (map cvt xs)
188 cvt (InfixE (Just x) s (Just y))
189     = HsPar (OpApp (cvt x) (cvt s) undefined (cvt y))
190 cvt (InfixE Nothing  s (Just y)) = SectionR (cvt s) (cvt y)
191 cvt (InfixE (Just x) s Nothing ) = SectionL (cvt x) (cvt s)
192 cvt (InfixE Nothing  s Nothing ) = cvt s        -- Can I indicate this is an infix thing?
193 cvt (SigE e t)          = ExprWithTySig (cvt e) (cvtType t)
194 cvt (RecConE c flds) = RecordCon (cName c) (map (\(x,y) -> (vName x, cvt y)) flds)
195 cvt (RecUpdE 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 (Meta.SigD nm typ) = Hs.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 (Meta.ValD (Meta.VarP s) body ds) = FunMonoBind (vName s) False 
218                                           [cvtclause (Clause [] body ds)] loc0
219 cvtd (FunD nm cls)          = FunMonoBind (vName nm) False (map cvtclause cls) loc0
220 cvtd (Meta.ValD 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 :: Range -> ArithSeqInfo RdrName
233 cvtdd (FromR x)               = (From (cvt x))
234 cvtdd (FromThenR x y)     = (FromThen (cvt x) (cvt y))
235 cvtdd (FromToR x y)           = (FromTo (cvt x) (cvt y))
236 cvtdd (FromThenToR x y z) = (FromThenTo (cvt x) (cvt y) (cvt z))
237
238
239 cvtstmts :: [Meta.Stmt] -> [Hs.Stmt RdrName]
240 cvtstmts []                    = [] -- this is probably an error as every [stmt] should end with ResultStmt
241 cvtstmts [NoBindS e]           = [ResultStmt (cvt e) loc0]      -- when its the last element use ResultStmt
242 cvtstmts (NoBindS e : ss)      = ExprStmt (cvt e) void loc0     : cvtstmts ss
243 cvtstmts (Meta.BindS p e : ss) = BindStmt (cvtp p) (cvt e) loc0 : cvtstmts ss
244 cvtstmts (Meta.LetS ds : ss)   = LetStmt (cvtdecs ds)       : cvtstmts ss
245 cvtstmts (Meta.ParS dss : ss)  = ParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
246
247 cvtm :: Meta.Match -> Hs.Match RdrName
248 cvtm (Meta.Match p body wheres)
249     = Hs.Match [cvtp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
250                              
251 cvtguard :: Meta.Body -> [GRHS RdrName]
252 cvtguard (GuardedB pairs) = map cvtpair pairs
253 cvtguard (NormalB e)     = [GRHS [  ResultStmt (cvt e) loc0 ] loc0]
254
255 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
256 cvtpair (x,y) = GRHS [Hs.BindStmt truePat (cvt x) loc0,
257                       ResultStmt (cvt y) loc0] loc0
258
259 cvtOverLit :: Lit -> HsOverLit
260 cvtOverLit (IntegerL i)  = mkHsIntegral i
261 cvtOverLit (RationalL r) = mkHsFractional r
262 -- An Integer is like an an (overloaded) '3' in a Haskell source program
263 -- Similarly 3.5 for fractionals
264
265 cvtLit :: Lit -> HsLit
266 cvtLit (IntPrimL i)    = HsIntPrim i
267 cvtLit (FloatPrimL f)  = HsFloatPrim f
268 cvtLit (DoublePrimL f) = HsDoublePrim f
269 cvtLit (CharL c)       = HsChar (ord c)
270 cvtLit (StringL s)     = HsString (mkFastString s)
271
272 cvtp :: Meta.Pat -> Hs.Pat RdrName
273 cvtp (Meta.LitP l)
274   | overloadedLit l = NPatIn (cvtOverLit l) Nothing     -- Not right for negative
275                                                         -- patterns; need to think
276                                                         -- about that!
277   | otherwise       = Hs.LitPat (cvtLit l)
278 cvtp (Meta.VarP s)     = Hs.VarPat(vName s)
279 cvtp (TupP [p])   = cvtp p
280 cvtp (TupP ps)    = TuplePat (map cvtp ps) Boxed
281 cvtp (ConP s ps)  = ConPatIn (cName s) (PrefixCon (map cvtp ps))
282 cvtp (TildeP p)   = LazyPat (cvtp p)
283 cvtp (Meta.AsP s p) = AsPat (vName s) (cvtp p)
284 cvtp Meta.WildP   = WildPat void
285 cvtp (RecP c fs)  = ConPatIn (cName c) $ Hs.RecCon (map (\(s,p) -> (vName s,cvtp p)) fs)
286 cvtp (ListP ps)   = ListPat (map cvtp ps) void
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 :: Meta.Type -> HsPred RdrName
298 cvt_pred ty = case split_ty_app ty of
299                 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
300                 other -> panic "Malformed predicate"
301
302 cvtType :: Meta.Type -> HsType RdrName
303 cvtType ty = trans (root ty [])
304   where root (AppT a b) zs = root a (cvtType b : zs)
305         root t zs          = (t,zs)
306
307         trans (TupleT n,args)
308             | length args == n = HsTupleTy (HsTupCon Boxed n) args
309             | n == 0 = foldl HsAppTy (HsTyVar (tconName "()")) args
310             | otherwise = foldl HsAppTy (HsTyVar (tconName ("(" ++ replicate (n-1) ',' ++ ")"))) args
311         trans (ArrowT,   [x,y]) = HsFunTy x y
312         trans (ListT,    [x])   = HsListTy x
313
314         trans (VarT nm, args)       = foldl HsAppTy (HsTyVar (tName nm)) args
315         trans (ConT tc, args)       = foldl HsAppTy (HsTyVar (tconName tc)) args
316
317         trans (ForallT tvs cxt ty, []) = mkHsForAllTy (Just (cvt_tvs tvs))
318                                                       (cvt_context cxt)
319                                                       (cvtType ty)
320
321 split_ty_app :: Meta.Type -> (Meta.Type, [Meta.Type])
322 split_ty_app ty = go ty []
323   where
324     go (AppT f a) as = go f (a:as)
325     go f as          = (f,as)
326
327 -----------------------------------------------------------
328 sigP :: Dec -> Bool
329 sigP (Meta.SigD _ _) = True
330 sigP other       = False
331
332
333 -----------------------------------------------------------
334 -- some useful things
335
336 truePat  = ConPatIn (cName "True") (PrefixCon [])
337 falsePat = ConPatIn (cName "False") (PrefixCon [])
338
339 overloadedLit :: Lit -> Bool
340 -- True for literals that Haskell treats as overloaded
341 overloadedLit (IntegerL  l) = True
342 overloadedLit (RationalL l) = True
343 overloadedLit l             = False
344
345 void :: Type.Type
346 void = placeHolderType
347
348 loc0 :: SrcLoc
349 loc0 = generatedSrcLoc
350
351 -- variable names
352 vName :: String -> RdrName
353 vName = mkName varName
354
355 -- Constructor function names; this is Haskell source, hence srcDataName
356 cName :: String -> RdrName
357 cName = mkName srcDataName
358
359 -- Type variable names
360 tName :: String -> RdrName
361 tName = mkName tvName
362
363 -- Type Constructor names
364 tconName = mkName tcName
365
366 mkName :: NameSpace -> String -> RdrName
367 -- Parse the string to see if it has a "." or ":" in it
368 -- so we know whether to generate a qualified or original name
369 -- It's a bit tricky because we need to parse 
370 --      Foo.Baz.x as Qual Foo.Baz x
371 -- So we parse it from back to front
372
373 mkName ns str
374   = split [] (reverse str)
375   where
376     split occ [] = mkRdrUnqual (mk_occ occ)
377     split occ (c:d:rev)         -- 'd' is the last char before the separator
378         |  is_sep c             -- E.g.         Fo.x    d='o'
379         && isAlphaNum d         --              Fo.+:   d='+' perhaps
380         = mk_qual (reverse (d:rev)) c occ
381     split occ (c:rev) = split (c:occ) rev
382
383     mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
384     mk_qual mod ':' occ = mkOrig    (mk_mod mod) (mk_occ occ)
385
386     mk_occ occ = mkOccFS ns (mkFastString occ)
387     mk_mod mod = mkModuleName mod
388
389     is_sep '.'   = True
390     is_sep ':'   = True
391     is_sep other = False
392 \end{code}
393