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