[project @ 2003-05-04 13:21:48 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
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 ctxt tc tvs constrs derivs)
58   = Left $ TyClD (mkTyData DataType 
59                            (cvt_context ctxt, 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                   (Hs.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 cvt (Meta.RecCon c flds) = RecordCon (cName c) (map (\(x,y) -> (vName x, cvt y)) flds)
189 cvt (RecUpd e flds) = RecordUpd (cvt e) (map (\(x,y) -> (vName x, cvt y)) flds)
190
191 cvtdecs :: [Meta.Dec] -> HsBinds RdrName
192 cvtdecs [] = EmptyBinds
193 cvtdecs ds = MonoBind binds sigs Recursive
194            where
195              (binds, sigs) = cvtBindsAndSigs ds
196
197 cvtBindsAndSigs ds 
198   = (cvtds non_sigs, map cvtSig sigs)
199   where 
200     (sigs, non_sigs) = partition sigP ds
201
202 cvtSig (Proto nm typ) = Sig (vName nm) (cvtType typ) loc0
203
204 cvtds :: [Meta.Dec] -> MonoBinds RdrName
205 cvtds []     = EmptyMonoBinds
206 cvtds (d:ds) = AndMonoBinds (cvtd d) (cvtds ds)
207
208 cvtd :: Meta.Dec -> MonoBinds RdrName
209 -- Used only for declarations in a 'let/where' clause,
210 -- not for top level decls
211 cvtd (Val (Pvar s) body ds) = FunMonoBind (vName s) False 
212                                           [cvtclause (Clause [] body ds)] loc0
213 cvtd (Fun nm cls)           = FunMonoBind (vName nm) False (map cvtclause cls) loc0
214 cvtd (Val p body ds)        = PatMonoBind (cvtp p) (GRHSs (cvtguard body) 
215                                                           (cvtdecs ds) 
216                                                           void) loc0
217 cvtd x = panic "Illegal kind of declaration in where clause" 
218
219
220 cvtclause :: Meta.Clause -> Hs.Match RdrName
221 cvtclause (Clause ps body wheres)
222     = Hs.Match (map cvtp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
223
224
225
226 cvtdd :: Meta.DotDot -> ArithSeqInfo RdrName
227 cvtdd (Meta.From x)           = (Hs.From (cvt x))
228 cvtdd (Meta.FromThen x y)     = (Hs.FromThen (cvt x) (cvt y))
229 cvtdd (Meta.FromTo x y)       = (Hs.FromTo (cvt x) (cvt y))
230 cvtdd (Meta.FromThenTo x y z) = (Hs.FromThenTo (cvt x) (cvt y) (cvt z))
231
232
233 cvtstmts :: [Meta.Statement] -> [Hs.Stmt RdrName]
234 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
235 cvtstmts [NoBindSt e]      = [ResultStmt (cvt e) loc0]      -- when its the last element use ResultStmt
236 cvtstmts (NoBindSt e : ss) = ExprStmt (cvt e) void loc0     : cvtstmts ss
237 cvtstmts (BindSt p e : ss) = BindStmt (cvtp p) (cvt e) loc0 : cvtstmts ss
238 cvtstmts (LetSt ds : ss)   = LetStmt (cvtdecs ds)           : cvtstmts ss
239 cvtstmts (ParSt dss : ss)  = ParStmt(map cvtstmts dss)      : cvtstmts ss
240
241
242 cvtm :: Meta.Match -> Hs.Match RdrName
243 cvtm (Meta.Match p body wheres)
244     = Hs.Match [cvtp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
245                              
246 cvtguard :: Meta.RightHandSide -> [GRHS RdrName]
247 cvtguard (Guarded pairs) = map cvtpair pairs
248 cvtguard (Normal e)      = [GRHS [  ResultStmt (cvt e) loc0 ] loc0]
249
250 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
251 cvtpair (x,y) = GRHS [BindStmt truePat (cvt x) loc0,
252                       ResultStmt (cvt y) loc0] loc0
253
254 cvtOverLit :: Lit -> HsOverLit
255 cvtOverLit (Integer i)  = mkHsIntegral i
256 cvtOverLit (Rational r) = mkHsFractional r
257 -- An Integer is like an an (overloaded) '3' in a Haskell source program
258 -- Similarly 3.5 for fractionals
259
260 cvtLit :: Lit -> HsLit
261 cvtLit (IntPrim i)    = HsIntPrim i
262 cvtLit (FloatPrim f)  = HsFloatPrim f
263 cvtLit (DoublePrim f) = HsDoublePrim f
264 cvtLit (Char c)       = HsChar (ord c)
265 cvtLit (String s)     = HsString (mkFastString s)
266
267 cvtp :: Meta.Pat -> Hs.Pat RdrName
268 cvtp (Plit l)
269   | overloadedLit l = NPatIn (cvtOverLit l) Nothing     -- Not right for negative
270                                                         -- patterns; need to think
271                                                         -- about that!
272   | otherwise       = LitPat (cvtLit l)
273 cvtp (Pvar s)     = VarPat(vName s)
274 cvtp (Ptup [p])   = cvtp p
275 cvtp (Ptup ps)    = TuplePat (map cvtp ps) Boxed
276 cvtp (Pcon s ps)  = ConPatIn (cName s) (PrefixCon (map cvtp ps))
277 cvtp (Ptilde p)   = LazyPat (cvtp p)
278 cvtp (Paspat s p) = AsPat (vName s) (cvtp p)
279 cvtp Pwild        = WildPat void
280 cvtp (Prec c fs)  = ConPatIn (cName c) $ Hs.RecCon (map (\(s,p) -> (vName s,cvtp p)) fs)
281
282 -----------------------------------------------------------
283 --      Types and type variables
284
285 cvt_tvs :: [String] -> [HsTyVarBndr RdrName]
286 cvt_tvs tvs = map (UserTyVar . tName) tvs
287
288 cvt_context :: Cxt -> HsContext RdrName 
289 cvt_context tys = map cvt_pred tys
290
291 cvt_pred :: Typ -> HsPred RdrName
292 cvt_pred ty = case split_ty_app ty of
293                 (Tcon (TconName tc), tys) -> HsClassP (tconName tc) (map cvtType tys)
294                 other -> panic "Malformed predicate"
295
296 cvtType :: Meta.Typ -> HsType RdrName
297 cvtType ty = trans (root ty [])
298   where root (Tapp a b) zs = root a (cvtType b : zs)
299         root t zs          = (t,zs)
300
301         trans (Tcon (Tuple n),args) | length args == n
302                                     = HsTupleTy (HsTupCon Boxed n) args
303         trans (Tcon Arrow,   [x,y]) = HsFunTy x y
304         trans (Tcon List,    [x])   = HsListTy x
305
306         trans (Tvar nm, args)       = foldl HsAppTy (HsTyVar (tName nm)) args
307         trans (Tcon tc, args)       = foldl HsAppTy (HsTyVar (tc_name tc)) args
308
309         trans (TForall tvs cxt ty, []) = mkHsForAllTy (Just (cvt_tvs tvs))
310                                                       (cvt_context cxt)
311                                                       (cvtType ty)
312
313         tc_name (TconName nm) = tconName nm
314         tc_name Arrow         = tconName "->"
315         tc_name List          = tconName "[]"
316         tc_name (Tuple 0)     = tconName "()"
317         tc_name (Tuple n)     = tconName ("(" ++ replicate (n-1) ',' ++ ")")
318
319 split_ty_app :: Typ -> (Typ, [Typ])
320 split_ty_app ty = go ty []
321   where
322     go (Tapp f a) as = go f (a:as)
323     go f as          = (f,as)
324
325 -----------------------------------------------------------
326 sigP :: Dec -> Bool
327 sigP (Proto _ _) = True
328 sigP other       = False
329
330
331 -----------------------------------------------------------
332 -- some useful things
333
334 truePat  = ConPatIn (cName "True") (PrefixCon [])
335 falsePat = ConPatIn (cName "False") (PrefixCon [])
336
337 overloadedLit :: Lit -> Bool
338 -- True for literals that Haskell treats as overloaded
339 overloadedLit (Integer  l) = True
340 overloadedLit (Rational l) = True
341 overloadedLit l            = False
342
343 void :: Type.Type
344 void = placeHolderType
345
346 loc0 :: SrcLoc
347 loc0 = generatedSrcLoc
348
349 -- variable names
350 vName :: String -> RdrName
351 vName = mkName varName
352
353 -- Constructor function names; this is Haskell source, hence srcDataName
354 cName :: String -> RdrName
355 cName = mkName srcDataName
356
357 -- Type variable names
358 tName :: String -> RdrName
359 tName = mkName tvName
360
361 -- Type Constructor names
362 tconName = mkName tcName
363
364 mkName :: NameSpace -> String -> RdrName
365 -- Parse the string to see if it has a "." or ":" in it
366 -- so we know whether to generate a qualified or original name
367 -- It's a bit tricky because we need to parse 
368 --      Foo.Baz.x as Qual Foo.Baz x
369 -- So we parse it from back to front
370
371 mkName ns str
372   = split [] (reverse str)
373   where
374     split occ [] = mkRdrUnqual (mk_occ occ)
375     split occ (c:d:rev)         -- 'd' is the last char before the separator
376         |  is_sep c             -- E.g.         Fo.x    d='o'
377         && isAlphaNum d         --              Fo.+:   d='+' perhaps
378         = mk_qual (reverse (d:rev)) c occ
379     split occ (c:rev) = split (c:occ) rev
380
381     mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
382     mk_qual mod ':' occ = mkOrig    (mk_mod mod) (mk_occ occ)
383
384     mk_occ occ = mkOccFS ns (mkFastString occ)
385     mk_mod mod = mkModuleName mod
386
387     is_sep '.'   = True
388     is_sep ':'   = True
389     is_sep other = False
390 \end{code}