[project @ 2004-10-01 16:39:26 by simonpj]
[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 $ 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 $ HsBangTy HsStrict (cvtType ty)
57     mk_arg (NotStrict, ty) = noLoc $ HsBangTy HsNoBang (cvtType ty)
58
59     mk_id_arg (i, IsStrict, ty)
60         = (noLoc (vName i), noLoc $ HsBangTy HsStrict (cvtType ty))
61     mk_id_arg (i, NotStrict, ty)
62         = (noLoc (vName i), noLoc $ HsBangTy HsNoBang (cvtType ty))
63
64 mk_derivs [] = Nothing
65 mk_derivs cs = Just [noLoc $ HsPredTy $ 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                            (noLoc (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs))
82                            Nothing (map mk_con constrs)
83                            (mk_derivs derivs))
84
85 cvt_top (NewtypeD ctxt tc tvs constr derivs)
86   = Left $ TyClD (mkTyData NewType 
87                            (noLoc (cvt_context ctxt, noLoc (tconName tc), cvt_tvs tvs))
88                            Nothing [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 (mkMatchGroup [mkSimpleMatch (map cvtlp ps) (cvtl e)])
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) (mkMatchGroup (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 (mkMatchGroup [cvtclause (Clause [] body ds)])
227 cvtd (FunD nm cls)
228   = noLoc $ FunBind (noLoc (vName nm)) False (mkMatchGroup (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 (TH.pprint 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))
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)))
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.Guard,TH.Exp) -> LGRHS RdrName
266 cvtpair (NormalG x,y) = noLoc (GRHS [nlBindStmt truePat (cvtl x),
267                                nlResultStmt (cvtl y)])
268 cvtpair (PatG x,y) = noLoc (GRHS (cvtstmts x ++ [nlResultStmt (cvtl y)]))
269
270 cvtOverLit :: Lit -> HsOverLit
271 cvtOverLit (IntegerL i)  = mkHsIntegral i
272 cvtOverLit (RationalL r) = mkHsFractional r
273 -- An Integer is like an an (overloaded) '3' in a Haskell source program
274 -- Similarly 3.5 for fractionals
275
276 cvtLit :: Lit -> HsLit
277 cvtLit (IntPrimL i)    = HsIntPrim i
278 cvtLit (FloatPrimL f)  = HsFloatPrim f
279 cvtLit (DoublePrimL f) = HsDoublePrim f
280 cvtLit (CharL c)       = HsChar c
281 cvtLit (StringL s)     = HsString (mkFastString s)
282
283 cvtlp :: TH.Pat -> Hs.LPat RdrName
284 cvtlp pat = noLoc (cvtp pat)
285
286 cvtp :: TH.Pat -> Hs.Pat RdrName
287 cvtp (TH.LitP l)
288   | overloadedLit l = NPatIn (cvtOverLit l) Nothing     -- Not right for negative
289                                                         -- patterns; need to think
290                                                         -- about that!
291   | otherwise       = Hs.LitPat (cvtLit l)
292 cvtp (TH.VarP s)     = Hs.VarPat(vName s)
293 cvtp (TupP [p])   = cvtp p
294 cvtp (TupP ps)    = TuplePat (map cvtlp ps) Boxed
295 cvtp (ConP s ps)  = ConPatIn (noLoc (cName s)) (PrefixCon (map cvtlp ps))
296 cvtp (InfixP p1 s p2)
297                   = ConPatIn (noLoc (cName s)) (InfixCon (cvtlp p1) (cvtlp p2))
298 cvtp (TildeP p)   = LazyPat (cvtlp p)
299 cvtp (TH.AsP s p) = AsPat (noLoc (vName s)) (cvtlp p)
300 cvtp TH.WildP   = WildPat void
301 cvtp (RecP c fs)  = ConPatIn (noLoc (cName c)) $ Hs.RecCon (map (\(s,p) -> (noLoc (vName s),cvtlp p)) fs)
302 cvtp (ListP ps)   = ListPat (map cvtlp ps) void
303 cvtp (SigP p t)   = SigPatIn (cvtlp p) (cvtType t)
304
305 -----------------------------------------------------------
306 --      Types and type variables
307
308 cvt_tvs :: [TH.Name] -> [LHsTyVarBndr RdrName]
309 cvt_tvs tvs = map (noLoc . UserTyVar . tName) tvs
310
311 cvt_context :: Cxt -> LHsContext RdrName 
312 cvt_context tys = noLoc (map (noLoc . cvt_pred) tys)
313
314 cvt_pred :: TH.Type -> HsPred RdrName
315 cvt_pred ty = case split_ty_app ty of
316                 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
317                 (VarT tv, tys) -> HsClassP (tName tv) (map cvtType tys)
318                 other -> cvtPanic "Malformed predicate" (text (TH.pprint ty))
319
320 convertToHsType = cvtType
321
322 cvtType :: TH.Type -> LHsType RdrName
323 cvtType ty = trans (root ty [])
324   where root (AppT a b) zs = root a (cvtType b : zs)
325         root t zs          = (t,zs)
326
327         trans (TupleT n,args)
328             | length args == n = noLoc (HsTupleTy Boxed args)
329             | n == 0    = foldl nlHsAppTy (nlHsTyVar (getRdrName unitTyCon))        args
330             | otherwise = foldl nlHsAppTy (nlHsTyVar (getRdrName (tupleTyCon Boxed n))) args
331         trans (ArrowT,   [x,y]) = nlHsFunTy x y
332         trans (ListT,    [x])   = noLoc (HsListTy x)
333
334         trans (VarT nm, args)       = foldl nlHsAppTy (nlHsTyVar (tName nm))    args
335         trans (ConT tc, args)       = foldl nlHsAppTy (nlHsTyVar (tconName tc)) args
336
337         trans (ForallT tvs cxt ty, []) = noLoc $ mkExplicitHsForAllTy 
338                                                 (cvt_tvs tvs) (cvt_context cxt) (cvtType ty)
339
340 split_ty_app :: TH.Type -> (TH.Type, [TH.Type])
341 split_ty_app ty = go ty []
342   where
343     go (AppT f a) as = go f (a:as)
344     go f as          = (f,as)
345
346 -----------------------------------------------------------
347 sigP :: Dec -> Bool
348 sigP (TH.SigD _ _) = True
349 sigP other       = False
350
351
352 -----------------------------------------------------------
353 cvtPanic :: String -> SDoc -> b
354 cvtPanic herald thing
355   = pprPanic herald (thing $$ ptext SLIT("When splicing generated code into the program"))
356
357 -----------------------------------------------------------
358 -- some useful things
359
360 truePat  = nlConPat (getRdrName trueDataCon)  []
361 falsePat = nlConPat (getRdrName falseDataCon) []
362
363 overloadedLit :: Lit -> Bool
364 -- True for literals that Haskell treats as overloaded
365 overloadedLit (IntegerL  l) = True
366 overloadedLit (RationalL l) = True
367 overloadedLit l             = False
368
369 void :: Type.Type
370 void = placeHolderType
371
372 loc0 :: SrcSpan
373 loc0 = srcLocSpan generatedSrcLoc
374
375 --------------------------------------------------------------------
376 --      Turning Name back into RdrName
377 --------------------------------------------------------------------
378
379 -- variable names
380 vName :: TH.Name -> RdrName
381 vName = thRdrName OccName.varName
382
383 -- Constructor function names; this is Haskell source, hence srcDataName
384 cName :: TH.Name -> RdrName
385 cName = thRdrName OccName.srcDataName
386
387 -- Type variable names
388 tName :: TH.Name -> RdrName
389 tName = thRdrName OccName.tvName
390
391 -- Type Constructor names
392 tconName = thRdrName OccName.tcName
393
394 thRdrName :: OccName.NameSpace -> TH.Name -> RdrName
395 -- This turns a Name into a RdrName
396 -- The last case is slightly interesting.  It constructs a
397 -- unique name from the unique in the TH thingy, so that the renamer
398 -- won't mess about.  I hope.  (Another possiblity would be to generate 
399 -- "x_77" etc, but that could conceivably clash.)
400
401 thRdrName ns (TH.Name occ (TH.NameG ns' mod))  = mkOrig (mk_mod mod) (mk_occ ns occ)
402 thRdrName ns (TH.Name occ TH.NameS)            = mkDynName ns occ
403 thRdrName ns (TH.Name occ (TH.NameU uniq))     = nameRdrName (mkInternalName (mk_uniq uniq) (mk_occ ns occ) noSrcLoc)
404
405 mk_uniq :: Int# -> Unique
406 mk_uniq u = mkUniqueGrimily (I# u)
407
408 -- The packing and unpacking is rather turgid :-(
409 mk_occ :: OccName.NameSpace -> TH.OccName -> OccName.OccName
410 mk_occ ns occ = OccName.mkOccFS ns (mkFastString (TH.occString occ))
411
412 mk_mod :: TH.ModName -> ModuleName
413 mk_mod mod = mkModuleName (TH.modString mod)
414
415 mkDynName :: OccName.NameSpace -> TH.OccName -> RdrName
416 -- Parse the string to see if it has a "." in it
417 -- so we know whether to generate a qualified or unqualified name
418 -- It's a bit tricky because we need to parse 
419 --      Foo.Baz.x as Qual Foo.Baz x
420 -- So we parse it from back to front
421
422 mkDynName ns th_occ
423   = split [] (reverse (TH.occString th_occ))
424   where
425     split occ []        = mkRdrUnqual (mk_occ occ)
426     split occ ('.':rev) = mkRdrQual (mk_mod (reverse rev)) (mk_occ occ)
427     split occ (c:rev)   = split (c:occ) rev
428
429     mk_occ occ = OccName.mkOccFS ns (mkFastString occ)
430     mk_mod mod = mkModuleName mod
431 \end{code}
432