[project @ 2004-01-04 01:48:04 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, convertToHsType ) where
10
11 #include "HsVersions.h"
12
13 import Language.Haskell.TH as TH
14 import Language.Haskell.TH.Syntax as TH
15
16 import HsSyn as Hs
17 import RdrName  ( RdrName, mkRdrUnqual, mkRdrQual, mkOrig, nameRdrName, getRdrName )
18 import Module   ( ModuleName, mkModuleName )
19 import RdrHsSyn ( mkHsIntegral, mkHsFractional, mkClassDecl, mkTyData )
20 import Name     ( mkInternalName )
21 import qualified OccName
22 import SrcLoc   ( SrcLoc, generatedSrcLoc, noLoc, unLoc, Located(..),
23                   noSrcSpan, SrcSpan, srcLocSpan, noSrcLoc )
24 import Type     ( Type )
25 import TysWiredIn ( unitTyCon, tupleTyCon, trueDataCon, falseDataCon )
26 import BasicTypes( Boxity(..), RecFlag(Recursive), NewOrData(..) )
27 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
28                      CExportSpec(..)) 
29 import HsDecls ( CImportSpec(..), ForeignImport(..), ForeignExport(..),
30                  ForeignDecl(..) )
31 import FastString( FastString, mkFastString, nilFS )
32 import Char     ( ord, isAscii, isAlphaNum, isAlpha )
33 import List     ( partition )
34 import Unique   ( Unique, mkUniqueGrimily )
35 import ErrUtils (Message)
36 import GLAEXTS  ( Int#, Int(..) )
37 import Bag      ( emptyBag, consBag )
38 import Outputable
39
40
41 -------------------------------------------------------------------
42 convertToHsDecls :: [TH.Dec] -> [Either (LHsDecl RdrName) Message]
43 convertToHsDecls ds = map cvt_ltop ds
44
45 mk_con con = L loc0 $ case con of
46         NormalC c strtys
47          -> ConDecl (noLoc (cName c)) noExistentials noContext
48                   (PrefixCon (map mk_arg strtys))
49         RecC c varstrtys
50          -> ConDecl (noLoc (cName c)) noExistentials noContext
51                   (RecCon (map mk_id_arg varstrtys))
52         InfixC st1 c st2
53          -> ConDecl (noLoc (cName c)) noExistentials noContext
54                   (InfixCon (mk_arg st1) (mk_arg st2))
55   where
56     mk_arg (IsStrict, ty)  = noLoc $ BangType HsStrict (cvtType ty)
57     mk_arg (NotStrict, ty) = noLoc $ BangType HsNoBang (cvtType ty)
58
59     mk_id_arg (i, IsStrict, ty)
60         = (noLoc (vName i), noLoc $ BangType HsStrict (cvtType ty))
61     mk_id_arg (i, NotStrict, ty)
62         = (noLoc (vName i), noLoc $ BangType HsNoBang (cvtType ty))
63
64 mk_derivs [] = Nothing
65 mk_derivs cs = Just (noLoc [noLoc $ HsClassP (tconName c) [] | c <- cs])
66
67 cvt_ltop  :: TH.Dec -> Either (LHsDecl RdrName) Message
68 cvt_ltop d = case cvt_top d of
69                 Left d -> Left (L loc0 d)
70                 Right m -> Right m
71
72 cvt_top :: TH.Dec -> Either (HsDecl RdrName) Message
73 cvt_top d@(TH.ValD _ _ _) = Left $ Hs.ValD (unLoc (cvtd d))
74 cvt_top d@(TH.FunD _ _)   = Left $ Hs.ValD (unLoc (cvtd d))
75  
76 cvt_top (TySynD tc tvs rhs)
77   = Left $ TyClD (TySynonym (noLoc (tconName tc)) (cvt_tvs tvs) (cvtType rhs))
78
79 cvt_top (DataD ctxt tc tvs constrs derivs)
80   = Left $ TyClD (mkTyData DataType 
81                            (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs)
82                            (map mk_con constrs)
83                            (mk_derivs derivs))
84
85 cvt_top (NewtypeD ctxt tc tvs constr derivs)
86   = Left $ TyClD (mkTyData NewType 
87                            (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs)
88                            [mk_con constr]
89                            (mk_derivs derivs))
90
91 cvt_top (ClassD ctxt cl tvs decs)
92   = Left $ TyClD (mkClassDecl (cvt_context ctxt, noLoc (tconName cl), cvt_tvs tvs)
93                               noFunDeps sigs
94                               binds)
95   where
96     (binds,sigs) = cvtBindsAndSigs decs
97
98 cvt_top (InstanceD tys ty decs)
99   = Left $ InstD (InstDecl (noLoc inst_ty) binds sigs)
100   where
101     (binds, sigs) = cvtBindsAndSigs decs
102     inst_ty = mkImplicitHsForAllTy (cvt_context tys) (noLoc (HsPredTy (cvt_pred ty)))
103
104 cvt_top (TH.SigD nm typ) = Left $ Hs.SigD (Sig (noLoc (vName nm)) (cvtType typ))
105
106 cvt_top (ForeignD (ImportF callconv safety from nm typ))
107  = case parsed of
108        Just (c_header, cis) ->
109            let i = CImport callconv' safety' c_header nilFS cis
110            in Left $ ForD (ForeignImport (noLoc (vName nm)) (cvtType typ) i False)
111        Nothing -> Right $     text (show from)
112                           <+> ptext SLIT("is not a valid ccall impent")
113     where callconv' = case callconv of
114                           CCall -> CCallConv
115                           StdCall -> StdCallConv
116           safety' = case safety of
117                         Unsafe     -> PlayRisky
118                         Safe       -> PlaySafe False
119                         Threadsafe -> PlaySafe True
120           parsed = parse_ccall_impent (TH.nameBase nm) from
121
122 cvt_top (ForeignD (ExportF callconv as nm typ))
123  = let e = CExport (CExportStatic (mkFastString as) callconv')
124    in Left $ ForD (ForeignExport (noLoc (vName nm)) (cvtType typ) e False)
125     where callconv' = case callconv of
126                           CCall -> CCallConv
127                           StdCall -> StdCallConv
128
129 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
130 parse_ccall_impent nm s
131  = case lex_ccall_impent s of
132        Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
133        Just ["wrapper"] -> Just (nilFS, CWrapper)
134        Just ("static":ts) -> parse_ccall_impent_static nm ts
135        Just ts -> parse_ccall_impent_static nm ts
136        Nothing -> Nothing
137
138 parse_ccall_impent_static :: String
139                           -> [String]
140                           -> Maybe (FastString, CImportSpec)
141 parse_ccall_impent_static nm ts
142  = let ts' = case ts of
143                  [       "&", cid] -> [       cid]
144                  [fname, "&"     ] -> [fname     ]
145                  [fname, "&", cid] -> [fname, cid]
146                  _                 -> ts
147    in case ts' of
148           [       cid] | is_cid cid -> Just (nilFS,              mk_cid cid)
149           [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
150           [          ]              -> Just (nilFS,              mk_cid nm)
151           [fname     ]              -> Just (mkFastString fname, mk_cid nm)
152           _                         -> Nothing
153     where is_cid :: String -> Bool
154           is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
155           mk_cid :: String -> CImportSpec
156           mk_cid  = CFunction . StaticTarget . mkFastString
157
158 lex_ccall_impent :: String -> Maybe [String]
159 lex_ccall_impent "" = Just []
160 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
161 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
162 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
163 lex_ccall_impent xs = case span is_valid xs of
164                           ("", _) -> Nothing
165                           (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
166     where is_valid :: Char -> Bool
167           is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
168
169 noContext      = noLoc []
170 noExistentials = []
171 noFunDeps      = []
172
173 -------------------------------------------------------------------
174 convertToHsExpr :: TH.Exp -> LHsExpr RdrName
175 convertToHsExpr = cvtl
176
177 cvtl e = noLoc (cvt e)
178
179 cvt (VarE s)      = HsVar (vName s)
180 cvt (ConE s)      = HsVar (cName s)
181 cvt (LitE l) 
182   | overloadedLit l = HsOverLit (cvtOverLit l)
183   | otherwise       = HsLit (cvtLit l)
184
185 cvt (AppE x y)     = HsApp (cvtl x) (cvtl y)
186 cvt (LamE ps e)    = HsLam (mkSimpleMatch (map cvtlp ps) (cvtl e) void)
187 cvt (TupE [e])    = cvt e
188 cvt (TupE es)     = ExplicitTuple(map cvtl es) Boxed
189 cvt (CondE x y z)  = HsIf (cvtl x) (cvtl y) (cvtl z)
190 cvt (LetE ds e)   = HsLet (cvtdecs ds) (cvtl e)
191 cvt (CaseE e ms)   = HsCase (cvtl e) (map cvtm ms)
192 cvt (DoE ss)      = HsDo DoExpr (cvtstmts ss) [] void
193 cvt (CompE ss)     = HsDo ListComp (cvtstmts ss) [] void
194 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
195 cvt (ListE xs)  = ExplicitList void (map cvtl xs)
196 cvt (InfixE (Just x) s (Just y))
197     = HsPar (noLoc $ OpApp (cvtl x) (cvtl s) undefined (cvtl y))
198 cvt (InfixE Nothing  s (Just y)) = SectionR (cvtl s) (cvtl y)
199 cvt (InfixE (Just x) s Nothing ) = SectionL (cvtl x) (cvtl s)
200 cvt (InfixE Nothing  s Nothing ) = cvt s        -- Can I indicate this is an infix thing?
201 cvt (SigE e t)          = ExprWithTySig (cvtl e) (cvtType t)
202 cvt (RecConE c flds) = RecordCon (noLoc (cName c)) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
203 cvt (RecUpdE e flds) = RecordUpd (cvtl e) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
204
205 cvtdecs :: [TH.Dec] -> [HsBindGroup RdrName]
206 cvtdecs [] = []
207 cvtdecs ds = [HsBindGroup binds sigs Recursive]
208            where
209              (binds, sigs) = cvtBindsAndSigs ds
210
211 cvtBindsAndSigs ds 
212   = (cvtds non_sigs, map cvtSig sigs)
213   where 
214     (sigs, non_sigs) = partition sigP ds
215
216 cvtSig (TH.SigD nm typ) = noLoc (Hs.Sig (noLoc (vName nm)) (cvtType typ))
217
218 cvtds :: [TH.Dec] -> LHsBinds RdrName
219 cvtds []     = emptyBag
220 cvtds (d:ds) = cvtd d `consBag` cvtds ds
221
222 cvtd :: TH.Dec -> LHsBind RdrName
223 -- Used only for declarations in a 'let/where' clause,
224 -- not for top level decls
225 cvtd (TH.ValD (TH.VarP s) body ds) 
226   = noLoc $ FunBind (noLoc (vName s)) False [cvtclause (Clause [] body ds)]
227 cvtd (FunD nm cls)
228   = noLoc $ FunBind (noLoc (vName nm)) False (map cvtclause cls)
229 cvtd (TH.ValD p body ds)
230   = noLoc $ PatBind (cvtlp p) (GRHSs (cvtguard body) (cvtdecs ds) void)
231
232 cvtd d = cvtPanic "Illegal kind of declaration in where clause" 
233                   (text (show (TH.pprDec d)))
234
235
236 cvtclause :: TH.Clause -> Hs.LMatch RdrName
237 cvtclause (Clause ps body wheres)
238     = noLoc $ Hs.Match (map cvtlp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
239
240
241
242 cvtdd :: Range -> ArithSeqInfo RdrName
243 cvtdd (FromR x)               = (From (cvtl x))
244 cvtdd (FromThenR x y)     = (FromThen (cvtl x) (cvtl y))
245 cvtdd (FromToR x y)           = (FromTo (cvtl x) (cvtl y))
246 cvtdd (FromThenToR x y z) = (FromThenTo (cvtl x) (cvtl y) (cvtl z))
247
248
249 cvtstmts :: [TH.Stmt] -> [Hs.LStmt RdrName]
250 cvtstmts []                    = [] -- this is probably an error as every [stmt] should end with ResultStmt
251 cvtstmts [NoBindS e]           = [nlResultStmt (cvtl e)]      -- when its the last element use ResultStmt
252 cvtstmts (NoBindS e : ss)      = nlExprStmt (cvtl e)     : cvtstmts ss
253 cvtstmts (TH.BindS p e : ss) = nlBindStmt (cvtlp p) (cvtl e) : cvtstmts ss
254 cvtstmts (TH.LetS ds : ss)   = nlLetStmt (cvtdecs ds)       : cvtstmts ss
255 cvtstmts (TH.ParS dss : ss)  = nlParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
256
257 cvtm :: TH.Match -> Hs.LMatch RdrName
258 cvtm (TH.Match p body wheres)
259     = noLoc (Hs.Match [cvtlp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void))
260
261 cvtguard :: TH.Body -> [LGRHS RdrName]
262 cvtguard (GuardedB pairs) = map cvtpair pairs
263 cvtguard (NormalB e)     = [noLoc (GRHS [  nlResultStmt (cvtl e) ])]
264
265 cvtpair :: (TH.Exp,TH.Exp) -> LGRHS RdrName
266 cvtpair (x,y) = noLoc (GRHS [nlBindStmt truePat (cvtl x),
267                         nlResultStmt (cvtl y)])
268
269 cvtOverLit :: Lit -> HsOverLit
270 cvtOverLit (IntegerL i)  = mkHsIntegral i
271 cvtOverLit (RationalL r) = mkHsFractional r
272 -- An Integer is like an an (overloaded) '3' in a Haskell source program
273 -- Similarly 3.5 for fractionals
274
275 cvtLit :: Lit -> HsLit
276 cvtLit (IntPrimL i)    = HsIntPrim i
277 cvtLit (FloatPrimL f)  = HsFloatPrim f
278 cvtLit (DoublePrimL f) = HsDoublePrim f
279 cvtLit (CharL c)       = HsChar c
280 cvtLit (StringL s)     = HsString (mkFastString s)
281
282 cvtlp :: TH.Pat -> Hs.LPat RdrName
283 cvtlp pat = noLoc (cvtp pat)
284
285 cvtp :: TH.Pat -> Hs.Pat RdrName
286 cvtp (TH.LitP l)
287   | overloadedLit l = NPatIn (cvtOverLit l) Nothing     -- Not right for negative
288                                                         -- patterns; need to think
289                                                         -- about that!
290   | otherwise       = Hs.LitPat (cvtLit l)
291 cvtp (TH.VarP s)     = Hs.VarPat(vName s)
292 cvtp (TupP [p])   = cvtp p
293 cvtp (TupP ps)    = TuplePat (map cvtlp ps) Boxed
294 cvtp (ConP s ps)  = ConPatIn (noLoc (cName s)) (PrefixCon (map cvtlp ps))
295 cvtp (TildeP p)   = LazyPat (cvtlp p)
296 cvtp (TH.AsP s p) = AsPat (noLoc (vName s)) (cvtlp p)
297 cvtp TH.WildP   = WildPat void
298 cvtp (RecP c fs)  = ConPatIn (noLoc (cName c)) $ Hs.RecCon (map (\(s,p) -> (noLoc (vName s),cvtlp p)) fs)
299 cvtp (ListP ps)   = ListPat (map cvtlp ps) void
300
301 -----------------------------------------------------------
302 --      Types and type variables
303
304 cvt_tvs :: [TH.Name] -> [LHsTyVarBndr RdrName]
305 cvt_tvs tvs = map (noLoc . UserTyVar . tName) tvs
306
307 cvt_context :: Cxt -> LHsContext RdrName 
308 cvt_context tys = noLoc (map cvt_pred tys)
309
310 cvt_pred :: TH.Type -> LHsPred RdrName
311 cvt_pred ty = case split_ty_app ty of
312                 (ConT tc, tys) -> noLoc (HsClassP (tconName tc) (map cvtType tys))
313                 (VarT tv, tys) -> noLoc (HsClassP (tName tv) (map cvtType tys))
314                 other -> cvtPanic "Malformed predicate" (text (show (TH.pprType ty)))
315
316 convertToHsType = cvtType
317
318 cvtType :: TH.Type -> LHsType RdrName
319 cvtType ty = trans (root ty [])
320   where root (AppT a b) zs = root a (cvtType b : zs)
321         root t zs          = (t,zs)
322
323         trans (TupleT n,args)
324             | length args == n = noLoc (HsTupleTy Boxed args)
325             | n == 0    = foldl nlHsAppTy (nlHsTyVar (getRdrName unitTyCon))        args
326             | otherwise = foldl nlHsAppTy (nlHsTyVar (getRdrName (tupleTyCon Boxed n))) args
327         trans (ArrowT,   [x,y]) = nlHsFunTy x y
328         trans (ListT,    [x])   = noLoc (HsListTy x)
329
330         trans (VarT nm, args)       = foldl nlHsAppTy (nlHsTyVar (tName nm))    args
331         trans (ConT tc, args)       = foldl nlHsAppTy (nlHsTyVar (tconName tc)) args
332
333         trans (ForallT tvs cxt ty, []) = noLoc $ mkExplicitHsForAllTy 
334                                                 (cvt_tvs tvs) (cvt_context cxt) (cvtType ty)
335
336 split_ty_app :: TH.Type -> (TH.Type, [TH.Type])
337 split_ty_app ty = go ty []
338   where
339     go (AppT f a) as = go f (a:as)
340     go f as          = (f,as)
341
342 -----------------------------------------------------------
343 sigP :: Dec -> Bool
344 sigP (TH.SigD _ _) = True
345 sigP other       = False
346
347
348 -----------------------------------------------------------
349 cvtPanic :: String -> SDoc -> b
350 cvtPanic herald thing
351   = pprPanic herald (thing $$ ptext SLIT("When splicing generated code into the program"))
352
353 -----------------------------------------------------------
354 -- some useful things
355
356 truePat  = nlConPat (getRdrName trueDataCon)  []
357 falsePat = nlConPat (getRdrName falseDataCon) []
358
359 overloadedLit :: Lit -> Bool
360 -- True for literals that Haskell treats as overloaded
361 overloadedLit (IntegerL  l) = True
362 overloadedLit (RationalL l) = True
363 overloadedLit l             = False
364
365 void :: Type.Type
366 void = placeHolderType
367
368 loc0 :: SrcSpan
369 loc0 = srcLocSpan generatedSrcLoc
370
371 --------------------------------------------------------------------
372 --      Turning Name back into RdrName
373 --------------------------------------------------------------------
374
375 -- variable names
376 vName :: TH.Name -> RdrName
377 vName = thRdrName OccName.varName
378
379 -- Constructor function names; this is Haskell source, hence srcDataName
380 cName :: TH.Name -> RdrName
381 cName = thRdrName OccName.srcDataName
382
383 -- Type variable names
384 tName :: TH.Name -> RdrName
385 tName = thRdrName OccName.tvName
386
387 -- Type Constructor names
388 tconName = thRdrName OccName.tcName
389
390 thRdrName :: OccName.NameSpace -> TH.Name -> RdrName
391 -- This turns a Name into a RdrName
392 -- The last case is slightly interesting.  It constructs a
393 -- unique name from the unique in the TH thingy, so that the renamer
394 -- won't mess about.  I hope.  (Another possiblity would be to generate 
395 -- "x_77" etc, but that could conceivably clash.)
396
397 thRdrName ns (TH.Name occ (TH.NameG ns' mod))  = mkOrig (mk_mod mod) (mk_occ ns occ)
398 thRdrName ns (TH.Name occ TH.NameS)            = mkRdrUnqual (mk_occ ns occ)
399 thRdrName ns (TH.Name occ (TH.NameU uniq))     = nameRdrName (mkInternalName (mk_uniq uniq) (mk_occ ns occ) noSrcLoc)
400
401 mk_uniq :: Int# -> Unique
402 mk_uniq u = mkUniqueGrimily (I# u)
403
404 -- The packing and unpacking is rather turgid :-(
405 mk_occ :: OccName.NameSpace -> TH.OccName -> OccName.OccName
406 mk_occ ns occ = OccName.mkOccFS ns (mkFastString (TH.occString occ))
407
408 mk_mod :: TH.ModName -> ModuleName
409 mk_mod mod = mkModuleName (TH.modString mod)
410 \end{code}
411