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