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