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