[project @ 2002-12-11 14:02:28 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 es)      = ExplicitTuple(map cvt es) Boxed
162 cvt (Cond x y z)  = HsIf (cvt x) (cvt y) (cvt z) loc0
163 cvt (Let ds e)    = HsLet (cvtdecs ds) (cvt e)
164 cvt (Case e ms)   = HsCase (cvt e) (map cvtm ms) loc0
165 cvt (Do ss)       = HsDo DoExpr (cvtstmts ss) [] void loc0
166 cvt (Comp ss)     = HsDo ListComp (cvtstmts ss) [] void loc0
167 cvt (ArithSeq dd) = ArithSeqIn (cvtdd dd)
168 cvt (ListExp xs)  = ExplicitList void (map cvt xs)
169 cvt (Infix (Just x) s (Just y))
170     = HsPar (OpApp (cvt x) (HsVar(vName s)) undefined (cvt y))
171 cvt (Infix Nothing  s (Just y)) = SectionR (HsVar(vName s)) (cvt y)
172 cvt (Infix (Just x) s Nothing ) = SectionL (cvt x) (HsVar(vName s))
173 cvt (Infix Nothing  s Nothing ) = HsVar(vName s) -- Can I indicate this is an infix thing?
174 cvt (SigExp e t)                = ExprWithTySig (cvt e) (cvtType t)
175
176 cvtdecs :: [Meta.Dec] -> HsBinds RdrName
177 cvtdecs [] = EmptyBinds
178 cvtdecs ds = MonoBind binds sigs Recursive
179            where
180              (binds, sigs) = cvtBindsAndSigs ds
181
182 cvtBindsAndSigs ds 
183   = (cvtds non_sigs, map cvtSig sigs)
184   where 
185     (sigs, non_sigs) = partition sigP ds
186
187 cvtSig (Proto nm typ) = Sig (vName nm) (cvtType typ) loc0
188
189 cvtds :: [Meta.Dec] -> MonoBinds RdrName
190 cvtds []     = EmptyMonoBinds
191 cvtds (d:ds) = AndMonoBinds (cvtd d) (cvtds ds)
192
193 cvtd :: Meta.Dec -> MonoBinds RdrName
194 -- Used only for declarations in a 'let/where' clause,
195 -- not for top level decls
196 cvtd (Val (Pvar s) body ds) = FunMonoBind (vName s) False 
197                                           [cvtclause (Clause [] body ds)] loc0
198 cvtd (Fun nm cls)           = FunMonoBind (vName nm) False (map cvtclause cls) loc0
199 cvtd (Val p body ds)        = PatMonoBind (cvtp p) (GRHSs (cvtguard body) 
200                                                           (cvtdecs ds) 
201                                                           void) loc0
202 cvtd x = panic "Illegal kind of declaration in where clause" 
203
204
205 cvtclause :: Meta.Clause (Meta.Pat) (Meta.Exp) (Meta.Dec) -> Hs.Match RdrName
206 cvtclause (Clause ps body wheres)
207     = Match (map cvtp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
208
209
210
211 cvtdd :: Meta.DDt -> ArithSeqInfo RdrName
212 cvtdd (Meta.From x)           = (Hs.From (cvt x))
213 cvtdd (Meta.FromThen x y)     = (Hs.FromThen (cvt x) (cvt y))
214 cvtdd (Meta.FromTo x y)       = (Hs.FromTo (cvt x) (cvt y))
215 cvtdd (Meta.FromThenTo x y z) = (Hs.FromThenTo (cvt x) (cvt y) (cvt z))
216
217
218 cvtstmts :: [Meta.Stm] -> [Hs.Stmt RdrName]
219 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
220 cvtstmts [NoBindSt e]      = [ResultStmt (cvt e) loc0]      -- when its the last element use ResultStmt
221 cvtstmts (NoBindSt e : ss) = ExprStmt (cvt e) void loc0     : cvtstmts ss
222 cvtstmts (BindSt p e : ss) = BindStmt (cvtp p) (cvt e) loc0 : cvtstmts ss
223 cvtstmts (LetSt ds : ss)   = LetStmt (cvtdecs ds)           : cvtstmts ss
224 cvtstmts (ParSt dss : ss)  = ParStmt(map cvtstmts dss)      : cvtstmts ss
225
226
227 cvtm :: Meta.Mat -> Hs.Match RdrName
228 cvtm (Mat p body wheres)
229     = Match [cvtp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
230                              
231 cvtguard :: Meta.Rhs -> [GRHS RdrName]
232 cvtguard (Guarded pairs) = map cvtpair pairs
233 cvtguard (Normal e)      = [GRHS [  ResultStmt (cvt e) loc0 ] loc0]
234
235 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
236 cvtpair (x,y) = GRHS [BindStmt truePat (cvt x) loc0,
237                       ResultStmt (cvt y) loc0] loc0
238
239 cvtOverLit :: Lit -> HsOverLit
240 cvtOverLit (Integer i)  = mkHsIntegral i
241 cvtOverLit (Rational r) = mkHsFractional r
242 -- An Integer is like an an (overloaded) '3' in a Haskell source program
243 -- Similarly 3.5 for fractionals
244
245 cvtLit :: Lit -> HsLit
246 cvtLit (Char c)   = HsChar (ord c)
247 cvtLit (String s) = HsString (mkFastString s)
248
249 cvtp :: Meta.Pat -> Hs.Pat RdrName
250 cvtp (Plit l)
251   | overloadedLit l = NPatIn (cvtOverLit l) Nothing     -- Not right for negative
252                                                         -- patterns; need to think
253                                                         -- about that!
254   | otherwise       = LitPat (cvtLit l)
255 cvtp (Pvar s)     = VarPat(vName s)
256 cvtp (Ptup ps)    = TuplePat (map cvtp ps) Boxed
257 cvtp (Pcon s ps)  = ConPatIn (cName s) (PrefixCon (map cvtp ps))
258 cvtp (Ptilde p)   = LazyPat (cvtp p)
259 cvtp (Paspat s p) = AsPat (vName s) (cvtp p)
260 cvtp Pwild        = WildPat void
261
262 -----------------------------------------------------------
263 --      Types and type variables
264
265 cvt_tvs :: [String] -> [HsTyVarBndr RdrName]
266 cvt_tvs tvs = map (UserTyVar . tName) tvs
267
268 cvt_context :: Cxt -> HsContext RdrName 
269 cvt_context tys = map cvt_pred tys
270
271 cvt_pred :: Typ -> HsPred RdrName
272 cvt_pred ty = case split_ty_app ty of
273                 (Tvar tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
274                 other -> panic "Malformed predicate"
275
276 cvtType :: Meta.Typ -> HsType RdrName
277 cvtType ty = trans (root ty [])
278   where root (Tapp a b) zs = root a (cvtType b : zs)
279         root t zs          = (t,zs)
280
281         trans (Tcon (Tuple n),args) | length args == n
282                                     = HsTupleTy (HsTupCon Boxed n) args
283         trans (Tcon Arrow,   [x,y]) = HsFunTy x y
284         trans (Tcon List,    [x])   = HsListTy x
285
286         trans (Tvar nm, args)       = foldl HsAppTy (HsTyVar (tName nm)) args
287         trans (Tcon tc, args)       = foldl HsAppTy (HsTyVar (tc_name tc)) args
288
289         tc_name (TconName nm) = tconName nm
290         tc_name Arrow         = tconName "->"
291         tc_name List          = tconName "[]"
292         tc_name (Tuple 0)     = tconName "()"
293         tc_name (Tuple n)     = tconName ("(" ++ replicate (n-1) ',' ++ ")")
294
295 split_ty_app :: Typ -> (Typ, [Typ])
296 split_ty_app ty = go ty []
297   where
298     go (Tapp f a) as = go f (a:as)
299     go f as          = (f,as)
300
301 -----------------------------------------------------------
302 sigP :: Dec -> Bool
303 sigP (Proto _ _) = True
304 sigP other       = False
305
306
307 -----------------------------------------------------------
308 -- some useful things
309
310 truePat  = ConPatIn (cName "True") (PrefixCon [])
311 falsePat = ConPatIn (cName "False") (PrefixCon [])
312
313 overloadedLit :: Lit -> Bool
314 -- True for literals that Haskell treats as overloaded
315 overloadedLit (Integer  l) = True
316 overloadedLit (Rational l) = True
317 overloadedLit l            = False
318
319 void :: Type.Type
320 void = placeHolderType
321
322 loc0 :: SrcLoc
323 loc0 = generatedSrcLoc
324
325 -- variable names
326 vName :: String -> RdrName
327 vName = mkName varName
328
329 -- Constructor function names
330 cName :: String -> RdrName
331 cName = mkName dataName
332
333 -- Type variable names
334 tName :: String -> RdrName
335 tName = mkName tvName
336
337 -- Type Constructor names
338 tconName = mkName tcName
339
340 mkName :: NameSpace -> String -> RdrName
341 -- Parse the string to see if it has a "." or ":" in it
342 -- so we know whether to generate a qualified or original name
343 -- It's a bit tricky because we need to parse 
344 --      Foo.Baz.x as Qual Foo.Baz x
345 -- So we parse it from back to front
346
347 mkName ns str
348   = split [] (reverse str)
349   where
350     split occ [] = mkRdrUnqual (mk_occ occ)
351     split occ (c:d:rev)         -- 'd' is the last char before the separator
352         |  is_sep c             -- E.g.         Fo.x    d='o'
353         && isAlphaNum d         --              Fo.+:   d='+' perhaps
354         = mk_qual (reverse (d:rev)) c occ
355     split occ (c:rev) = split (c:occ) rev
356
357     mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
358     mk_qual mod ':' occ = mkOrig    (mk_mod mod) (mk_occ occ)
359
360     mk_occ occ = mkOccFS ns (mkFastString occ)
361     mk_mod mod = mkModuleName mod
362
363     is_sep '.'   = True
364     is_sep ':'   = True
365     is_sep other = False
366 \end{code}