[project @ 2005-04-04 16:49:42 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, thRdrName ) 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)       = cvtHsDo DoExpr   ss
205 cvt (CompE ss)     = cvtHsDo ListComp ss
206 cvt (ArithSeqE dd) = ArithSeq noPostTcExpr (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)) noPostTcExpr
215                                  (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
216 cvt (RecUpdE e flds) = RecordUpd (cvtl e) (map (\(x,y) -> (noLoc (vName x), cvtl y)) flds)
217                                  placeHolderType placeHolderType
218
219 cvtHsDo do_or_lc stmts
220   = HsDo do_or_lc (init stmts') body void
221   where
222     stmts' = cvtstmts stmts
223     body = case last stmts' of
224                 L _ (ExprStmt body _ _) -> body
225
226 cvtdecs :: [TH.Dec] -> [HsBindGroup RdrName]
227 cvtdecs [] = []
228 cvtdecs ds = [HsBindGroup binds sigs Recursive]
229            where
230              (binds, sigs) = cvtBindsAndSigs ds
231
232 cvtBindsAndSigs ds 
233   = (cvtds non_sigs, map cvtSig sigs)
234   where 
235     (sigs, non_sigs) = partition sigP ds
236
237 cvtSig (TH.SigD nm typ) = noLoc (Hs.Sig (noLoc (vName nm)) (cvtType typ))
238
239 cvtds :: [TH.Dec] -> LHsBinds RdrName
240 cvtds []     = emptyBag
241 cvtds (d:ds) = cvtd d `consBag` cvtds ds
242
243 cvtd :: TH.Dec -> LHsBind RdrName
244 -- Used only for declarations in a 'let/where' clause,
245 -- not for top level decls
246 cvtd (TH.ValD (TH.VarP s) body ds) 
247   = noLoc $ FunBind (noLoc (vName s)) False (mkMatchGroup [cvtclause (Clause [] body ds)])
248 cvtd (FunD nm cls)
249   = noLoc $ FunBind (noLoc (vName nm)) False (mkMatchGroup (map cvtclause cls))
250 cvtd (TH.ValD p body ds)
251   = noLoc $ PatBind (cvtlp p) (GRHSs (cvtguard body) (cvtdecs ds)) void
252
253 cvtd d = cvtPanic "Illegal kind of declaration in where clause" 
254                   (text (TH.pprint d))
255
256
257 cvtclause :: TH.Clause -> Hs.LMatch RdrName
258 cvtclause (Clause ps body wheres)
259     = noLoc $ Hs.Match (map cvtlp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres))
260
261
262
263 cvtdd :: Range -> ArithSeqInfo RdrName
264 cvtdd (FromR x)               = (From (cvtl x))
265 cvtdd (FromThenR x y)     = (FromThen (cvtl x) (cvtl y))
266 cvtdd (FromToR x y)           = (FromTo (cvtl x) (cvtl y))
267 cvtdd (FromThenToR x y z) = (FromThenTo (cvtl x) (cvtl y) (cvtl z))
268
269
270 cvtstmts :: [TH.Stmt] -> [Hs.LStmt RdrName]
271 cvtstmts []                  = []
272 cvtstmts (NoBindS e : ss)    = noLoc (mkExprStmt (cvtl e))           : cvtstmts ss
273 cvtstmts (TH.BindS p e : ss) = noLoc (mkBindStmt (cvtlp p) (cvtl e)) : cvtstmts ss
274 cvtstmts (TH.LetS ds : ss)   = noLoc (LetStmt (cvtdecs ds))          : cvtstmts ss
275 cvtstmts (TH.ParS dss : ss)  = noLoc (ParStmt [(cvtstmts ds, undefined) | ds <- dss]) : cvtstmts ss
276
277 cvtm :: TH.Match -> Hs.LMatch RdrName
278 cvtm (TH.Match p body wheres)
279     = noLoc (Hs.Match [cvtlp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres)))
280
281 cvtguard :: TH.Body -> [LGRHS RdrName]
282 cvtguard (GuardedB pairs) = map cvtpair pairs
283 cvtguard (NormalB e)     = [noLoc (GRHS [] (cvtl e))]
284
285 cvtpair :: (TH.Guard,TH.Exp) -> LGRHS RdrName
286 cvtpair (NormalG x,y) = noLoc (GRHS [noLoc $ mkBindStmt truePat (cvtl x)]
287                                     (cvtl y))
288 cvtpair (PatG x,y) = noLoc (GRHS (cvtstmts x) (cvtl y))
289
290 cvtOverLit :: Lit -> HsOverLit RdrName
291 cvtOverLit (IntegerL i)  = mkHsIntegral i
292 cvtOverLit (RationalL r) = mkHsFractional r
293 -- An Integer is like an an (overloaded) '3' in a Haskell source program
294 -- Similarly 3.5 for fractionals
295
296 cvtLit :: Lit -> HsLit
297 cvtLit (IntPrimL i)    = HsIntPrim i
298 cvtLit (FloatPrimL f)  = HsFloatPrim f
299 cvtLit (DoublePrimL f) = HsDoublePrim f
300 cvtLit (CharL c)       = HsChar c
301 cvtLit (StringL s)     = HsString (mkFastString s)
302
303 cvtlp :: TH.Pat -> Hs.LPat RdrName
304 cvtlp pat = noLoc (cvtp pat)
305
306 cvtp :: TH.Pat -> Hs.Pat RdrName
307 cvtp (TH.LitP l)
308   | overloadedLit l = mkNPat (cvtOverLit l) Nothing     -- Not right for negative
309                                                         -- patterns; need to think
310                                                         -- about that!
311   | otherwise       = Hs.LitPat (cvtLit l)
312 cvtp (TH.VarP s)     = Hs.VarPat(vName s)
313 cvtp (TupP [p])   = cvtp p
314 cvtp (TupP ps)    = TuplePat (map cvtlp ps) Boxed
315 cvtp (ConP s ps)  = ConPatIn (noLoc (cName s)) (PrefixCon (map cvtlp ps))
316 cvtp (InfixP p1 s p2)
317                   = ConPatIn (noLoc (cName s)) (InfixCon (cvtlp p1) (cvtlp p2))
318 cvtp (TildeP p)   = LazyPat (cvtlp p)
319 cvtp (TH.AsP s p) = AsPat (noLoc (vName s)) (cvtlp p)
320 cvtp TH.WildP   = WildPat void
321 cvtp (RecP c fs)  = ConPatIn (noLoc (cName c)) $ Hs.RecCon (map (\(s,p) -> (noLoc (vName s),cvtlp p)) fs)
322 cvtp (ListP ps)   = ListPat (map cvtlp ps) void
323 cvtp (SigP p t)   = SigPatIn (cvtlp p) (cvtType t)
324
325 -----------------------------------------------------------
326 --      Types and type variables
327
328 cvt_tvs :: [TH.Name] -> [LHsTyVarBndr RdrName]
329 cvt_tvs tvs = map (noLoc . UserTyVar . tName) tvs
330
331 cvt_context :: Cxt -> LHsContext RdrName 
332 cvt_context tys = noLoc (map (noLoc . cvt_pred) tys)
333
334 cvt_pred :: TH.Type -> HsPred RdrName
335 cvt_pred ty = case split_ty_app ty of
336                 (ConT tc, tys) -> HsClassP (tconName tc) (map cvtType tys)
337                 (VarT tv, tys) -> HsClassP (tName tv) (map cvtType tys)
338                 other -> cvtPanic "Malformed predicate" (text (TH.pprint ty))
339
340 convertToHsType = cvtType
341
342 cvtType :: TH.Type -> LHsType RdrName
343 cvtType ty = trans (root ty [])
344   where root (AppT a b) zs = root a (cvtType b : zs)
345         root t zs          = (t,zs)
346
347         trans (TupleT n,args)
348             | length args == n = noLoc (HsTupleTy Boxed args)
349             | n == 0    = foldl nlHsAppTy (nlHsTyVar (getRdrName unitTyCon))        args
350             | otherwise = foldl nlHsAppTy (nlHsTyVar (getRdrName (tupleTyCon Boxed n))) args
351         trans (ArrowT,   [x,y]) = nlHsFunTy x y
352         trans (ListT,    [x])   = noLoc (HsListTy x)
353
354         trans (VarT nm, args)       = foldl nlHsAppTy (nlHsTyVar (tName nm))    args
355         trans (ConT tc, args)       = foldl nlHsAppTy (nlHsTyVar (tconName tc)) args
356
357         trans (ForallT tvs cxt ty, []) = noLoc $ mkExplicitHsForAllTy 
358                                                 (cvt_tvs tvs) (cvt_context cxt) (cvtType ty)
359
360 split_ty_app :: TH.Type -> (TH.Type, [TH.Type])
361 split_ty_app ty = go ty []
362   where
363     go (AppT f a) as = go f (a:as)
364     go f as          = (f,as)
365
366 -----------------------------------------------------------
367 sigP :: Dec -> Bool
368 sigP (TH.SigD _ _) = True
369 sigP other       = False
370
371
372 -----------------------------------------------------------
373 cvtPanic :: String -> SDoc -> b
374 cvtPanic herald thing
375   = pprPanic herald (thing $$ ptext SLIT("When splicing generated code into the program"))
376
377 -----------------------------------------------------------
378 -- some useful things
379
380 truePat  = nlConPat (getRdrName trueDataCon)  []
381
382 overloadedLit :: Lit -> Bool
383 -- True for literals that Haskell treats as overloaded
384 overloadedLit (IntegerL  l) = True
385 overloadedLit (RationalL l) = True
386 overloadedLit l             = False
387
388 void :: Type.Type
389 void = placeHolderType
390
391 loc0 :: SrcSpan
392 loc0 = srcLocSpan generatedSrcLoc
393
394 --------------------------------------------------------------------
395 --      Turning Name back into RdrName
396 --------------------------------------------------------------------
397
398 -- variable names
399 vName :: TH.Name -> RdrName
400 vName = thRdrName OccName.varName
401
402 -- Constructor function names; this is Haskell source, hence srcDataName
403 cName :: TH.Name -> RdrName
404 cName = thRdrName OccName.srcDataName
405
406 -- Type variable names
407 tName :: TH.Name -> RdrName
408 tName = thRdrName OccName.tvName
409
410 -- Type Constructor names
411 tconName = thRdrName OccName.tcName
412
413 thRdrName :: OccName.NameSpace -> TH.Name -> RdrName
414 -- This turns a Name into a RdrName
415 -- The passed-in name space tells what the context is expecting;
416 --      use it unless the TH name knows what name-space it comes
417 --      from, in which case use the latter
418 thRdrName ctxt_ns (TH.Name occ (TH.NameG th_ns mod)) = mkOrig      (mk_mod mod) (mk_occ (mk_ghc_ns th_ns) occ)
419 thRdrName ctxt_ns (TH.Name occ (TH.NameL uniq))      = nameRdrName (mkInternalName (mk_uniq uniq) (mk_occ ctxt_ns occ) noSrcLoc)
420 thRdrName ctxt_ns (TH.Name occ (TH.NameQ mod))       = mkRdrQual   (mk_mod mod) (mk_occ ctxt_ns occ)
421 thRdrName ctxt_ns (TH.Name occ TH.NameS)             = mkRdrUnqual (mk_occ ctxt_ns occ)
422 thRdrName ctxt_ns (TH.Name occ (TH.NameU uniq))      = mkRdrUnqual (mk_uniq_occ ctxt_ns occ uniq)
423
424 mk_uniq_occ :: OccName.NameSpace -> TH.OccName -> Int# -> OccName.OccName
425 mk_uniq_occ ns occ uniq 
426   = OccName.mkOccName ns (TH.occString occ ++ '[' : shows (mk_uniq uniq) "]")
427         -- The idea here is to make a name that 
428         -- a) the user could not possibly write, and
429         -- b) cannot clash with another NameU
430         -- Previously I generated an Exact RdrName with mkInternalName.
431         -- This works fine for local binders, but does not work at all for
432         -- top-level binders, which must have External Names, since they are
433         -- rapidly baked into data constructors and the like.  Baling out
434         -- and generating an unqualified RdrName here is the simple solution
435
436 mk_ghc_ns :: TH.NameSpace -> OccName.NameSpace
437 mk_ghc_ns DataName     = OccName.dataName
438 mk_ghc_ns TH.TcClsName = OccName.tcClsName
439 mk_ghc_ns TH.VarName   = OccName.varName
440
441 -- The packing and unpacking is rather turgid :-(
442 mk_occ :: OccName.NameSpace -> TH.OccName -> OccName.OccName
443 mk_occ ns occ = OccName.mkOccFS ns (mkFastString (TH.occString occ))
444
445 mk_mod :: TH.ModName -> Module
446 mk_mod mod = mkModule (TH.modString mod)
447
448 mk_uniq :: Int# -> Unique
449 mk_uniq u = mkUniqueGrimily (I# u)
450 \end{code}
451