[project @ 2004-12-23 09:07:30 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 qualified Class (FunDep)
18 import RdrName  ( RdrName, mkRdrUnqual, mkRdrQual, mkOrig, getRdrName, nameRdrName )
19 import Name     ( mkInternalName )
20 import Module   ( Module, mkModule )
21 import RdrHsSyn ( mkClassDecl, mkTyData )
22 import qualified OccName
23 import SrcLoc   ( generatedSrcLoc, noLoc, unLoc, Located(..),
24                   SrcSpan, srcLocSpan )
25 import Type     ( Type )
26 import TysWiredIn ( unitTyCon, tupleTyCon, trueDataCon )
27 import BasicTypes( Boxity(..), RecFlag(Recursive) )
28 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
29                      CExportSpec(..)) 
30 import Char     ( isAscii, isAlphaNum, isAlpha )
31 import List     ( partition )
32 import Unique   ( Unique, mkUniqueGrimily )
33 import ErrUtils (Message)
34 import GLAEXTS  ( Int(..), Int# )
35 import SrcLoc   ( noSrcLoc )
36 import Bag      ( emptyBag, consBag )
37 import FastString
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 fds decs)
99   = Left $ TyClD $ mkClassDecl (cvt_context ctxt,
100                                 noLoc (tconName cl),
101                                 cvt_tvs tvs)
102                                (map (noLoc . cvt_fundep) fds)
103                                sigs
104                                binds
105   where
106     (binds,sigs) = cvtBindsAndSigs decs
107
108 cvt_top (InstanceD tys ty decs)
109   = Left $ InstD (InstDecl (noLoc inst_ty) binds sigs)
110   where
111     (binds, sigs) = cvtBindsAndSigs decs
112     inst_ty = mkImplicitHsForAllTy (cvt_context tys) (noLoc (HsPredTy (cvt_pred ty)))
113
114 cvt_top (TH.SigD nm typ) = Left $ Hs.SigD (Sig (noLoc (vName nm)) (cvtType typ))
115
116 cvt_top (ForeignD (ImportF callconv safety from nm typ))
117  = case parsed of
118        Just (c_header, cis) ->
119            let i = CImport callconv' safety' c_header nilFS cis
120            in Left $ ForD (ForeignImport (noLoc (vName nm)) (cvtType typ) i False)
121        Nothing -> Right $     text (show from)
122                           <+> ptext SLIT("is not a valid ccall impent")
123     where callconv' = case callconv of
124                           CCall -> CCallConv
125                           StdCall -> StdCallConv
126           safety' = case safety of
127                         Unsafe     -> PlayRisky
128                         Safe       -> PlaySafe False
129                         Threadsafe -> PlaySafe True
130           parsed = parse_ccall_impent (TH.nameBase nm) from
131
132 cvt_top (ForeignD (ExportF callconv as nm typ))
133  = let e = CExport (CExportStatic (mkFastString as) callconv')
134    in Left $ ForD (ForeignExport (noLoc (vName nm)) (cvtType typ) e False)
135     where callconv' = case callconv of
136                           CCall -> CCallConv
137                           StdCall -> StdCallConv
138
139 cvt_fundep :: FunDep -> Class.FunDep RdrName
140 cvt_fundep (FunDep xs ys) = (map tName xs, map tName ys)
141
142 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
143 parse_ccall_impent nm s
144  = case lex_ccall_impent s of
145        Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
146        Just ["wrapper"] -> Just (nilFS, CWrapper)
147        Just ("static":ts) -> parse_ccall_impent_static nm ts
148        Just ts -> parse_ccall_impent_static nm ts
149        Nothing -> Nothing
150
151 parse_ccall_impent_static :: String
152                           -> [String]
153                           -> Maybe (FastString, CImportSpec)
154 parse_ccall_impent_static nm ts
155  = let ts' = case ts of
156                  [       "&", cid] -> [       cid]
157                  [fname, "&"     ] -> [fname     ]
158                  [fname, "&", cid] -> [fname, cid]
159                  _                 -> ts
160    in case ts' of
161           [       cid] | is_cid cid -> Just (nilFS,              mk_cid cid)
162           [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
163           [          ]              -> Just (nilFS,              mk_cid nm)
164           [fname     ]              -> Just (mkFastString fname, mk_cid nm)
165           _                         -> Nothing
166     where is_cid :: String -> Bool
167           is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
168           mk_cid :: String -> CImportSpec
169           mk_cid  = CFunction . StaticTarget . mkFastString
170
171 lex_ccall_impent :: String -> Maybe [String]
172 lex_ccall_impent "" = Just []
173 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
174 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
175 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
176 lex_ccall_impent xs = case span is_valid xs of
177                           ("", _) -> Nothing
178                           (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
179     where is_valid :: Char -> Bool
180           is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
181
182 noContext      = noLoc []
183 noExistentials = []
184
185 -------------------------------------------------------------------
186 convertToHsExpr :: TH.Exp -> LHsExpr RdrName
187 convertToHsExpr = cvtl
188
189 cvtl e = noLoc (cvt e)
190
191 cvt (VarE s)      = HsVar (vName s)
192 cvt (ConE s)      = HsVar (cName s)
193 cvt (LitE l) 
194   | overloadedLit l = HsOverLit (cvtOverLit l)
195   | otherwise       = HsLit (cvtLit l)
196
197 cvt (AppE x y)     = HsApp (cvtl x) (cvtl y)
198 cvt (LamE ps e)    = HsLam (mkMatchGroup [mkSimpleMatch (map cvtlp ps) (cvtl e)])
199 cvt (TupE [e])    = cvt e
200 cvt (TupE es)     = ExplicitTuple(map cvtl es) Boxed
201 cvt (CondE x y z)  = HsIf (cvtl x) (cvtl y) (cvtl z)
202 cvt (LetE ds e)   = HsLet (cvtdecs ds) (cvtl e)
203 cvt (CaseE e ms)   = HsCase (cvtl e) (mkMatchGroup (map cvtm ms))
204 cvt (DoE ss)      = HsDo DoExpr (cvtstmts ss) [] void
205 cvt (CompE ss)     = HsDo ListComp (cvtstmts ss) [] void
206 cvt (ArithSeqE dd) = ArithSeqIn (cvtdd dd)
207 cvt (ListE xs)  = ExplicitList void (map cvtl xs)
208 cvt (InfixE (Just x) s (Just y))
209     = HsPar (noLoc $ OpApp (cvtl x) (cvtl s) undefined (cvtl y))
210 cvt (InfixE Nothing  s (Just y)) = SectionR (cvtl s) (cvtl y)
211 cvt (InfixE (Just x) s Nothing ) = SectionL (cvtl x) (cvtl s)
212 cvt (InfixE Nothing  s Nothing ) = cvt s        -- Can I indicate this is an infix thing?
213 cvt (SigE e t)          = ExprWithTySig (cvtl e) (cvtType t)
214 cvt (RecConE c flds) = RecordCon (noLoc (cName c)) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
215 cvt (RecUpdE e flds) = RecordUpd (cvtl e) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
216
217 cvtdecs :: [TH.Dec] -> [HsBindGroup RdrName]
218 cvtdecs [] = []
219 cvtdecs ds = [HsBindGroup binds sigs Recursive]
220            where
221              (binds, sigs) = cvtBindsAndSigs ds
222
223 cvtBindsAndSigs ds 
224   = (cvtds non_sigs, map cvtSig sigs)
225   where 
226     (sigs, non_sigs) = partition sigP ds
227
228 cvtSig (TH.SigD nm typ) = noLoc (Hs.Sig (noLoc (vName nm)) (cvtType typ))
229
230 cvtds :: [TH.Dec] -> LHsBinds RdrName
231 cvtds []     = emptyBag
232 cvtds (d:ds) = cvtd d `consBag` cvtds ds
233
234 cvtd :: TH.Dec -> LHsBind RdrName
235 -- Used only for declarations in a 'let/where' clause,
236 -- not for top level decls
237 cvtd (TH.ValD (TH.VarP s) body ds) 
238   = noLoc $ FunBind (noLoc (vName s)) False (mkMatchGroup [cvtclause (Clause [] body ds)])
239 cvtd (FunD nm cls)
240   = noLoc $ FunBind (noLoc (vName nm)) False (mkMatchGroup (map cvtclause cls))
241 cvtd (TH.ValD p body ds)
242   = noLoc $ PatBind (cvtlp p) (GRHSs (cvtguard body) (cvtdecs ds)) void
243
244 cvtd d = cvtPanic "Illegal kind of declaration in where clause" 
245                   (text (TH.pprint d))
246
247
248 cvtclause :: TH.Clause -> Hs.LMatch RdrName
249 cvtclause (Clause ps body wheres)
250     = noLoc $ Hs.Match (map cvtlp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres))
251
252
253
254 cvtdd :: Range -> ArithSeqInfo RdrName
255 cvtdd (FromR x)               = (From (cvtl x))
256 cvtdd (FromThenR x y)     = (FromThen (cvtl x) (cvtl y))
257 cvtdd (FromToR x y)           = (FromTo (cvtl x) (cvtl y))
258 cvtdd (FromThenToR x y z) = (FromThenTo (cvtl x) (cvtl y) (cvtl z))
259
260
261 cvtstmts :: [TH.Stmt] -> [Hs.LStmt RdrName]
262 cvtstmts []                    = [] -- this is probably an error as every [stmt] should end with ResultStmt
263 cvtstmts [NoBindS e]           = [nlResultStmt (cvtl e)]      -- when its the last element use ResultStmt
264 cvtstmts (NoBindS e : ss)      = nlExprStmt (cvtl e)     : cvtstmts ss
265 cvtstmts (TH.BindS p e : ss) = nlBindStmt (cvtlp p) (cvtl e) : cvtstmts ss
266 cvtstmts (TH.LetS ds : ss)   = nlLetStmt (cvtdecs ds)       : cvtstmts ss
267 cvtstmts (TH.ParS dss : ss)  = nlParStmt [(cvtstmts ds, undefined) | ds <- dss] : cvtstmts ss
268
269 cvtm :: TH.Match -> Hs.LMatch RdrName
270 cvtm (TH.Match p body wheres)
271     = noLoc (Hs.Match [cvtlp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres)))
272
273 cvtguard :: TH.Body -> [LGRHS RdrName]
274 cvtguard (GuardedB pairs) = map cvtpair pairs
275 cvtguard (NormalB e)     = [noLoc (GRHS [  nlResultStmt (cvtl e) ])]
276
277 cvtpair :: (TH.Guard,TH.Exp) -> LGRHS RdrName
278 cvtpair (NormalG x,y) = noLoc (GRHS [nlBindStmt truePat (cvtl x),
279                                nlResultStmt (cvtl y)])
280 cvtpair (PatG x,y) = noLoc (GRHS (cvtstmts x ++ [nlResultStmt (cvtl y)]))
281
282 cvtOverLit :: Lit -> HsOverLit
283 cvtOverLit (IntegerL i)  = mkHsIntegral i
284 cvtOverLit (RationalL r) = mkHsFractional r
285 -- An Integer is like an an (overloaded) '3' in a Haskell source program
286 -- Similarly 3.5 for fractionals
287
288 cvtLit :: Lit -> HsLit
289 cvtLit (IntPrimL i)    = HsIntPrim i
290 cvtLit (FloatPrimL f)  = HsFloatPrim f
291 cvtLit (DoublePrimL f) = HsDoublePrim f
292 cvtLit (CharL c)       = HsChar c
293 cvtLit (StringL s)     = HsString (mkFastString s)
294
295 cvtlp :: TH.Pat -> Hs.LPat RdrName
296 cvtlp pat = noLoc (cvtp pat)
297
298 cvtp :: TH.Pat -> Hs.Pat RdrName
299 cvtp (TH.LitP l)
300   | overloadedLit l = NPatIn (cvtOverLit l) Nothing     -- Not right for negative
301                                                         -- patterns; need to think
302                                                         -- about that!
303   | otherwise       = Hs.LitPat (cvtLit l)
304 cvtp (TH.VarP s)     = Hs.VarPat(vName s)
305 cvtp (TupP [p])   = cvtp p
306 cvtp (TupP ps)    = TuplePat (map cvtlp ps) Boxed
307 cvtp (ConP s ps)  = ConPatIn (noLoc (cName s)) (PrefixCon (map cvtlp ps))
308 cvtp (InfixP p1 s p2)
309                   = ConPatIn (noLoc (cName s)) (InfixCon (cvtlp p1) (cvtlp p2))
310 cvtp (TildeP p)   = LazyPat (cvtlp p)
311 cvtp (TH.AsP s p) = AsPat (noLoc (vName s)) (cvtlp p)
312 cvtp TH.WildP   = WildPat void
313 cvtp (RecP c fs)  = ConPatIn (noLoc (cName c)) $ Hs.RecCon (map (\(s,p) -> (noLoc (vName s),cvtlp p)) fs)
314 cvtp (ListP ps)   = ListPat (map cvtlp ps) void
315 cvtp (SigP p t)   = SigPatIn (cvtlp p) (cvtType t)
316
317 -----------------------------------------------------------
318 --      Types and type variables
319
320 cvt_tvs :: [TH.Name] -> [LHsTyVarBndr RdrName]
321 cvt_tvs tvs = map (noLoc . UserTyVar . tName) tvs
322
323 cvt_context :: Cxt -> LHsContext RdrName 
324 cvt_context tys = noLoc (map (noLoc . cvt_pred) tys)
325
326 cvt_pred :: TH.Type -> HsPred RdrName
327 cvt_pred ty = case split_ty_app ty of
328                 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
329                 (VarT tv, tys) -> HsClassP (tName tv) (map cvtType tys)
330                 other -> cvtPanic "Malformed predicate" (text (TH.pprint ty))
331
332 convertToHsType = cvtType
333
334 cvtType :: TH.Type -> LHsType RdrName
335 cvtType ty = trans (root ty [])
336   where root (AppT a b) zs = root a (cvtType b : zs)
337         root t zs          = (t,zs)
338
339         trans (TupleT n,args)
340             | length args == n = noLoc (HsTupleTy Boxed args)
341             | n == 0    = foldl nlHsAppTy (nlHsTyVar (getRdrName unitTyCon))        args
342             | otherwise = foldl nlHsAppTy (nlHsTyVar (getRdrName (tupleTyCon Boxed n))) args
343         trans (ArrowT,   [x,y]) = nlHsFunTy x y
344         trans (ListT,    [x])   = noLoc (HsListTy x)
345
346         trans (VarT nm, args)       = foldl nlHsAppTy (nlHsTyVar (tName nm))    args
347         trans (ConT tc, args)       = foldl nlHsAppTy (nlHsTyVar (tconName tc)) args
348
349         trans (ForallT tvs cxt ty, []) = noLoc $ mkExplicitHsForAllTy 
350                                                 (cvt_tvs tvs) (cvt_context cxt) (cvtType ty)
351
352 split_ty_app :: TH.Type -> (TH.Type, [TH.Type])
353 split_ty_app ty = go ty []
354   where
355     go (AppT f a) as = go f (a:as)
356     go f as          = (f,as)
357
358 -----------------------------------------------------------
359 sigP :: Dec -> Bool
360 sigP (TH.SigD _ _) = True
361 sigP other       = False
362
363
364 -----------------------------------------------------------
365 cvtPanic :: String -> SDoc -> b
366 cvtPanic herald thing
367   = pprPanic herald (thing $$ ptext SLIT("When splicing generated code into the program"))
368
369 -----------------------------------------------------------
370 -- some useful things
371
372 truePat  = nlConPat (getRdrName trueDataCon)  []
373
374 overloadedLit :: Lit -> Bool
375 -- True for literals that Haskell treats as overloaded
376 overloadedLit (IntegerL  l) = True
377 overloadedLit (RationalL l) = True
378 overloadedLit l             = False
379
380 void :: Type.Type
381 void = placeHolderType
382
383 loc0 :: SrcSpan
384 loc0 = srcLocSpan generatedSrcLoc
385
386 --------------------------------------------------------------------
387 --      Turning Name back into RdrName
388 --------------------------------------------------------------------
389
390 -- variable names
391 vName :: TH.Name -> RdrName
392 vName = thRdrName OccName.varName
393
394 -- Constructor function names; this is Haskell source, hence srcDataName
395 cName :: TH.Name -> RdrName
396 cName = thRdrName OccName.srcDataName
397
398 -- Type variable names
399 tName :: TH.Name -> RdrName
400 tName = thRdrName OccName.tvName
401
402 -- Type Constructor names
403 tconName = thRdrName OccName.tcName
404
405 thRdrName :: OccName.NameSpace -> TH.Name -> RdrName
406 -- This turns a Name into a RdrName
407
408 thRdrName ns (TH.Name occ TH.NameS)           = mkRdrUnqual (mk_occ ns occ)
409 thRdrName ns (TH.Name occ (TH.NameQ mod))     = mkRdrQual (mk_mod mod) (mk_occ ns occ)
410 thRdrName ns (TH.Name occ (TH.NameG ns' mod)) = mkOrig    (mk_mod mod) (mk_occ ns occ)
411 thRdrName ns (TH.Name occ (TH.NameL uniq))    = nameRdrName (mkInternalName (mk_uniq uniq) (mk_occ ns occ) noSrcLoc)
412 thRdrName ns (TH.Name occ (TH.NameU uniq))    
413   = mkRdrUnqual (OccName.mkOccName ns uniq_str)
414   where
415     uniq_str = TH.occString occ ++ '[' : shows (mk_uniq uniq) "]"
416         -- The idea here is to make a name that 
417         -- a) the user could not possibly write, and
418         -- b) cannot clash with another NameU
419         -- Previously I generated an Exact RdrName with mkInternalName.
420         -- This works fine for local binders, but does not work at all for
421         -- top-level binders, which must have External Names, since they are
422         -- rapidly baked into data constructors and the like.  Baling out
423         -- and generating an unqualified RdrName here is the simple solution
424
425 -- The packing and unpacking is rather turgid :-(
426 mk_occ :: OccName.NameSpace -> TH.OccName -> OccName.OccName
427 mk_occ ns occ = OccName.mkOccFS ns (mkFastString (TH.occString occ))
428
429 mk_mod :: TH.ModName -> Module
430 mk_mod mod = mkModule (TH.modString mod)
431
432 mk_uniq :: Int# -> Unique
433 mk_uniq u = mkUniqueGrimily (I# u)
434 \end{code}
435