Add new field to TySynonym
[ghc-hetmet.git] / 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 qualified Name   ( Name, mkInternalName, getName )
20 import Module   ( ModuleName, mkModuleName, mkModule )
21 import RdrHsSyn ( mkClassDecl, mkTyData )
22 import qualified OccName
23 import PackageConfig    ( PackageId, stringToPackageId )
24 import OccName  ( startsVarId, startsVarSym, startsConId, startsConSym,
25                   pprNameSpace )
26 import SrcLoc   ( Located(..), SrcSpan )
27 import Type     ( Type )
28 import TysWiredIn ( unitTyCon, tupleTyCon, tupleCon, trueDataCon, nilDataCon, consDataCon )
29 import BasicTypes( Boxity(..) ) 
30 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
31                      CExportSpec(..)) 
32 import Char     ( isAscii, isAlphaNum, isAlpha )
33 import List     ( partition )
34 import Unique   ( Unique, mkUniqueGrimily )
35 import ErrUtils ( Message )
36 import GLAEXTS  ( Int(..), Int# )
37 import SrcLoc   ( noSrcLoc )
38 import Bag      ( listToBag )
39 import FastString
40 import Outputable
41
42
43
44 -------------------------------------------------------------------
45 --              The external interface
46
47 convertToHsDecls :: SrcSpan -> [TH.Dec] -> Either Message [LHsDecl RdrName]
48 convertToHsDecls loc ds = initCvt loc (mapM cvtTop ds)
49
50 convertToHsExpr :: SrcSpan -> TH.Exp -> Either Message (LHsExpr RdrName)
51 convertToHsExpr loc e 
52   = case initCvt loc (cvtl e) of
53         Left msg  -> Left (msg $$ (ptext SLIT("When converting TH expression")
54                                     <+> text (show e)))
55         Right res -> Right res
56
57 convertToHsType :: SrcSpan -> TH.Type -> Either Message (LHsType RdrName)
58 convertToHsType loc t = initCvt loc (cvtType t)
59
60
61 -------------------------------------------------------------------
62 newtype CvtM a = CvtM { unCvtM :: SrcSpan -> Either Message a }
63         -- Push down the source location;
64         -- Can fail, with a single error message
65
66 -- NB: If the conversion succeeds with (Right x), there should 
67 --     be no exception values hiding in x
68 -- Reason: so a (head []) in TH code doesn't subsequently
69 --         make GHC crash when it tries to walk the generated tree
70
71 -- Use the loc everywhere, for lack of anything better
72 -- In particular, we want it on binding locations, so that variables bound in
73 -- the spliced-in declarations get a location that at least relates to the splice point
74
75 instance Monad CvtM where
76   return x       = CvtM $ \loc -> Right x
77   (CvtM m) >>= k = CvtM $ \loc -> case m loc of
78                                     Left err -> Left err
79                                     Right v  -> unCvtM (k v) loc
80
81 initCvt :: SrcSpan -> CvtM a -> Either Message a
82 initCvt loc (CvtM m) = m loc
83
84 force :: a -> CvtM a
85 force a = a `seq` return a
86
87 failWith :: Message -> CvtM a
88 failWith m = CvtM (\loc -> Left full_msg)
89    where
90      full_msg = m $$ ptext SLIT("When splicing generated code into the program")
91
92 returnL :: a -> CvtM (Located a)
93 returnL x = CvtM (\loc -> Right (L loc x))
94
95 wrapL :: CvtM a -> CvtM (Located a)
96 wrapL (CvtM m) = CvtM (\loc -> case m loc of
97                           Left err -> Left err
98                           Right v  -> Right (L loc v))
99
100 -------------------------------------------------------------------
101 cvtTop :: TH.Dec -> CvtM (LHsDecl RdrName)
102 cvtTop d@(TH.ValD _ _ _) = do { L loc d' <- cvtBind d; return (L loc $ Hs.ValD d') }
103 cvtTop d@(TH.FunD _ _)   = do { L loc d' <- cvtBind d; return (L loc $ Hs.ValD d') }
104 cvtTop (TH.SigD nm typ)  = do  { nm' <- vNameL nm
105                                 ; ty' <- cvtType typ
106                                 ; returnL $ Hs.SigD (TypeSig nm' ty') }
107
108 cvtTop (TySynD tc tvs rhs)
109   = do  { tc' <- tconNameL tc
110         ; tvs' <- cvtTvs tvs
111         ; rhs' <- cvtType rhs
112         ; returnL $ TyClD (TySynonym tc' tvs' Nothing rhs') }
113
114 cvtTop (DataD ctxt tc tvs constrs derivs)
115   = do  { stuff <- cvt_tycl_hdr ctxt tc tvs
116         ; cons' <- mapM cvtConstr constrs
117         ; derivs' <- cvtDerivs derivs
118         ; returnL $ TyClD (mkTyData DataType stuff Nothing cons' derivs') }
119
120
121 cvtTop (NewtypeD ctxt tc tvs constr derivs)
122   = do  { stuff <- cvt_tycl_hdr ctxt tc tvs
123         ; con' <- cvtConstr constr
124         ; derivs' <- cvtDerivs derivs
125         ; returnL $ TyClD (mkTyData NewType stuff Nothing [con'] derivs') }
126
127 cvtTop (ClassD ctxt cl tvs fds decs)
128   = do  { stuff <- cvt_tycl_hdr ctxt cl tvs
129         ; fds'  <- mapM cvt_fundep fds
130         ; (binds', sigs') <- cvtBindsAndSigs decs
131         ; returnL $ TyClD $ mkClassDecl stuff fds' sigs' binds' }
132
133 cvtTop (InstanceD tys ty decs)
134   = do  { (binds', sigs') <- cvtBindsAndSigs decs
135         ; ctxt' <- cvtContext tys
136         ; L loc pred' <- cvtPred ty
137         ; inst_ty' <- returnL $ mkImplicitHsForAllTy ctxt' (L loc (HsPredTy pred'))
138         ; returnL $ InstD (InstDecl inst_ty' binds' sigs') }
139
140 cvtTop (ForeignD ford) = do { ford' <- cvtForD ford; returnL $ ForD ford' }
141
142 cvt_tycl_hdr cxt tc tvs
143   = do  { cxt' <- cvtContext cxt
144         ; tc'  <- tconNameL tc
145         ; tvs' <- cvtTvs tvs
146         ; return (cxt', tc', tvs') }
147
148 ---------------------------------------------------
149 --      Data types
150 -- Can't handle GADTs yet
151 ---------------------------------------------------
152
153 cvtConstr (NormalC c strtys)
154   = do  { c'   <- cNameL c 
155         ; cxt' <- returnL []
156         ; tys' <- mapM cvt_arg strtys
157         ; returnL $ ConDecl c' Explicit noExistentials cxt' (PrefixCon tys') ResTyH98 }
158
159 cvtConstr (RecC c varstrtys)
160   = do  { c'    <- cNameL c 
161         ; cxt'  <- returnL []
162         ; args' <- mapM cvt_id_arg varstrtys
163         ; returnL $ ConDecl c' Explicit noExistentials cxt' (RecCon args') ResTyH98 }
164
165 cvtConstr (InfixC st1 c st2)
166   = do  { c' <- cNameL c 
167         ; cxt' <- returnL []
168         ; st1' <- cvt_arg st1
169         ; st2' <- cvt_arg st2
170         ; returnL $ ConDecl c' Explicit noExistentials cxt' (InfixCon st1' st2') ResTyH98 }
171
172 cvtConstr (ForallC tvs ctxt (ForallC tvs' ctxt' con'))
173   = cvtConstr (ForallC (tvs ++ tvs') (ctxt ++ ctxt') con')
174
175 cvtConstr (ForallC tvs ctxt con)
176   = do  { L _ con' <- cvtConstr con
177         ; tvs'  <- cvtTvs tvs
178         ; ctxt' <- cvtContext ctxt
179         ; case con' of
180             ConDecl l _ [] (L _ []) x ResTyH98
181               -> returnL $ ConDecl l Explicit tvs' ctxt' x ResTyH98
182             c -> panic "ForallC: Can't happen" }
183
184 cvt_arg (IsStrict, ty)  = do { ty' <- cvtType ty; returnL $ HsBangTy HsStrict ty' }
185 cvt_arg (NotStrict, ty) = cvtType ty
186
187 cvt_id_arg (i, str, ty) = do { i' <- vNameL i
188                              ; ty' <- cvt_arg (str,ty)
189                              ; return (i', ty') }
190
191 cvtDerivs [] = return Nothing
192 cvtDerivs cs = do { cs' <- mapM cvt_one cs
193                   ; return (Just cs') }
194         where
195           cvt_one c = do { c' <- tconName c
196                          ; returnL $ HsPredTy $ HsClassP c' [] }
197
198 cvt_fundep :: FunDep -> CvtM (Located (Class.FunDep RdrName))
199 cvt_fundep (FunDep xs ys) = do { xs' <- mapM tName xs; ys' <- mapM tName ys; returnL (xs', ys') }
200
201 noExistentials = []
202
203 ------------------------------------------
204 --      Foreign declarations
205 ------------------------------------------
206
207 cvtForD :: Foreign -> CvtM (ForeignDecl RdrName)
208 cvtForD (ImportF callconv safety from nm ty)
209   | Just (c_header, cis) <- parse_ccall_impent (TH.nameBase nm) from
210   = do  { nm' <- vNameL nm
211         ; ty' <- cvtType ty
212         ; let i = CImport (cvt_conv callconv) safety' c_header nilFS cis
213         ; return $ ForeignImport nm' ty' i }
214
215   | otherwise
216   = failWith $ text (show from)<+> ptext SLIT("is not a valid ccall impent")
217   where 
218     safety' = case safety of
219                      Unsafe     -> PlayRisky
220                      Safe       -> PlaySafe False
221                      Threadsafe -> PlaySafe True
222
223 cvtForD (ExportF callconv as nm ty)
224   = do  { nm' <- vNameL nm
225         ; ty' <- cvtType ty
226         ; let e = CExport (CExportStatic (mkFastString as) (cvt_conv callconv))
227         ; return $ ForeignExport nm' ty' e }
228
229 cvt_conv CCall   = CCallConv
230 cvt_conv StdCall = StdCallConv
231
232 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
233 parse_ccall_impent nm s
234  = case lex_ccall_impent s of
235        Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
236        Just ["wrapper"] -> Just (nilFS, CWrapper)
237        Just ("static":ts) -> parse_ccall_impent_static nm ts
238        Just ts -> parse_ccall_impent_static nm ts
239        Nothing -> Nothing
240
241 parse_ccall_impent_static :: String
242                           -> [String]
243                           -> Maybe (FastString, CImportSpec)
244 parse_ccall_impent_static nm ts
245  = let ts' = case ts of
246                  [       "&", cid] -> [       cid]
247                  [fname, "&"     ] -> [fname     ]
248                  [fname, "&", cid] -> [fname, cid]
249                  _                 -> ts
250    in case ts' of
251           [       cid] | is_cid cid -> Just (nilFS,              mk_cid cid)
252           [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
253           [          ]              -> Just (nilFS,              mk_cid nm)
254           [fname     ]              -> Just (mkFastString fname, mk_cid nm)
255           _                         -> Nothing
256     where is_cid :: String -> Bool
257           is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
258           mk_cid :: String -> CImportSpec
259           mk_cid  = CFunction . StaticTarget . mkFastString
260
261 lex_ccall_impent :: String -> Maybe [String]
262 lex_ccall_impent "" = Just []
263 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
264 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
265 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
266 lex_ccall_impent xs = case span is_valid xs of
267                           ("", _) -> Nothing
268                           (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
269     where is_valid :: Char -> Bool
270           is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
271
272
273 ---------------------------------------------------
274 --              Declarations
275 ---------------------------------------------------
276
277 cvtDecs :: [TH.Dec] -> CvtM (HsLocalBinds RdrName)
278 cvtDecs [] = return EmptyLocalBinds
279 cvtDecs ds = do { (binds,sigs) <- cvtBindsAndSigs ds
280                 ; return (HsValBinds (ValBindsIn binds sigs)) }
281
282 cvtBindsAndSigs ds 
283   = do { binds' <- mapM cvtBind binds; sigs' <- mapM cvtSig sigs
284        ; return (listToBag binds', sigs') }
285   where 
286     (sigs, binds) = partition is_sig ds
287
288     is_sig (TH.SigD _ _) = True
289     is_sig other         = False
290
291 cvtSig (TH.SigD nm ty)
292   = do { nm' <- vNameL nm; ty' <- cvtType ty; returnL (Hs.TypeSig nm' ty') }
293
294 cvtBind :: TH.Dec -> CvtM (LHsBind RdrName)
295 -- Used only for declarations in a 'let/where' clause,
296 -- not for top level decls
297 cvtBind (TH.ValD (TH.VarP s) body ds) 
298   = do  { s' <- vNameL s
299         ; cl' <- cvtClause (Clause [] body ds)
300         ; returnL $ mkFunBind s' [cl'] }
301
302 cvtBind (TH.FunD nm cls)
303   = do  { nm' <- vNameL nm
304         ; cls' <- mapM cvtClause cls
305         ; returnL $ mkFunBind nm' cls' }
306
307 cvtBind (TH.ValD p body ds)
308   = do  { p' <- cvtPat p
309         ; g' <- cvtGuard body
310         ; ds' <- cvtDecs ds
311         ; returnL $ PatBind { pat_lhs = p', pat_rhs = GRHSs g' ds', 
312                               pat_rhs_ty = void, bind_fvs = placeHolderNames } }
313
314 cvtBind d 
315   = failWith (sep [ptext SLIT("Illegal kind of declaration in where clause"),
316                    nest 2 (text (TH.pprint d))])
317
318 cvtClause :: TH.Clause -> CvtM (Hs.LMatch RdrName)
319 cvtClause (Clause ps body wheres)
320   = do  { ps' <- cvtPats ps
321         ; g'  <- cvtGuard body
322         ; ds' <- cvtDecs wheres
323         ; returnL $ Hs.Match ps' Nothing (GRHSs g' ds') }
324
325
326 -------------------------------------------------------------------
327 --              Expressions
328 -------------------------------------------------------------------
329
330 cvtl :: TH.Exp -> CvtM (LHsExpr RdrName)
331 cvtl e = wrapL (cvt e)
332   where
333     cvt (VarE s)        = do { s' <- vName s; return $ HsVar s' }
334     cvt (ConE s)        = do { s' <- cName s; return $ HsVar s' }
335     cvt (LitE l) 
336       | overloadedLit l = do { l' <- cvtOverLit l; return $ HsOverLit l' }
337       | otherwise       = do { l' <- cvtLit l;     return $ HsLit l' }
338
339     cvt (AppE x y)     = do { x' <- cvtl x; y' <- cvtl y; return $ HsApp x' y' }
340     cvt (LamE ps e)    = do { ps' <- cvtPats ps; e' <- cvtl e 
341                             ; return $ HsLam (mkMatchGroup [mkSimpleMatch ps' e']) }
342     cvt (TupE [e])     = cvt e
343     cvt (TupE es)      = do { es' <- mapM cvtl es; return $ ExplicitTuple es' Boxed }
344     cvt (CondE x y z)  = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z
345                             ; return $ HsIf x' y' z' }
346     cvt (LetE ds e)    = do { ds' <- cvtDecs ds; e' <- cvtl e; return $ HsLet ds' e' }
347     cvt (CaseE e ms)   = do { e' <- cvtl e; ms' <- mapM cvtMatch ms
348                             ; return $ HsCase e' (mkMatchGroup ms') }
349     cvt (DoE ss)       = cvtHsDo DoExpr ss
350     cvt (CompE ss)     = cvtHsDo ListComp ss
351     cvt (ArithSeqE dd) = do { dd' <- cvtDD dd; return $ ArithSeq noPostTcExpr dd' }
352     cvt (ListE xs)     = do { xs' <- mapM cvtl xs; return $ ExplicitList void xs' }
353     cvt (InfixE (Just x) s (Just y)) = do { x' <- cvtl x; s' <- cvtl s; y' <- cvtl y
354                                           ; e' <- returnL $ OpApp x' s' undefined y'
355                                           ; return $ HsPar e' }
356     cvt (InfixE Nothing  s (Just y)) = do { s' <- cvtl s; y' <- cvtl y
357                                           ; return $ SectionR s' y' }
358     cvt (InfixE (Just x) s Nothing ) = do { x' <- cvtl x; s' <- cvtl s
359                                           ; return $ SectionL x' s' }
360     cvt (InfixE Nothing  s Nothing ) = cvt s    -- Can I indicate this is an infix thing?
361
362     cvt (SigE e t)       = do { e' <- cvtl e; t' <- cvtType t
363                               ; return $ ExprWithTySig e' t' }
364     cvt (RecConE c flds) = do { c' <- cNameL c
365                               ; flds' <- mapM cvtFld flds
366                               ; return $ RecordCon c' noPostTcExpr flds' }
367     cvt (RecUpdE e flds) = do { e' <- cvtl e
368                               ; flds' <- mapM cvtFld flds
369                               ; return $ RecordUpd e' flds' placeHolderType placeHolderType }
370
371 cvtFld (v,e) = do { v' <- vNameL v; e' <- cvtl e; return (v',e') }
372
373 cvtDD :: Range -> CvtM (ArithSeqInfo RdrName)
374 cvtDD (FromR x)           = do { x' <- cvtl x; return $ From x' }
375 cvtDD (FromThenR x y)     = do { x' <- cvtl x; y' <- cvtl y; return $ FromThen x' y' }
376 cvtDD (FromToR x y)       = do { x' <- cvtl x; y' <- cvtl y; return $ FromTo x' y' }
377 cvtDD (FromThenToR x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z; return $ FromThenTo x' y' z' }
378
379 -------------------------------------
380 --      Do notation and statements
381 -------------------------------------
382
383 cvtHsDo do_or_lc stmts
384   = do  { stmts' <- cvtStmts stmts
385         ; let body = case last stmts' of
386                         L _ (ExprStmt body _ _) -> body
387         ; return $ HsDo do_or_lc (init stmts') body void }
388
389 cvtStmts = mapM cvtStmt 
390
391 cvtStmt :: TH.Stmt -> CvtM (Hs.LStmt RdrName)
392 cvtStmt (NoBindS e)    = do { e' <- cvtl e; returnL $ mkExprStmt e' }
393 cvtStmt (TH.BindS p e) = do { p' <- cvtPat p; e' <- cvtl e; returnL $ mkBindStmt p' e' }
394 cvtStmt (TH.LetS ds)   = do { ds' <- cvtDecs ds; returnL $ LetStmt ds' }
395 cvtStmt (TH.ParS dss)  = do { dss' <- mapM cvt_one dss; returnL $ ParStmt dss' }
396                        where
397                          cvt_one ds = do { ds' <- cvtStmts ds; return (ds', undefined) }
398
399 cvtMatch :: TH.Match -> CvtM (Hs.LMatch RdrName)
400 cvtMatch (TH.Match p body decs)
401   = do  { p' <- cvtPat p
402         ; g' <- cvtGuard body
403         ; decs' <- cvtDecs decs
404         ; returnL $ Hs.Match [p'] Nothing (GRHSs g' decs') }
405
406 cvtGuard :: TH.Body -> CvtM [LGRHS RdrName]
407 cvtGuard (GuardedB pairs) = mapM cvtpair pairs
408 cvtGuard (NormalB e)      = do { e' <- cvtl e; g' <- returnL $ GRHS [] e'; return [g'] }
409
410 cvtpair :: (TH.Guard, TH.Exp) -> CvtM (LGRHS RdrName)
411 cvtpair (NormalG ge,rhs) = do { ge' <- cvtl ge; rhs' <- cvtl rhs
412                               ; g' <- returnL $ mkBindStmt truePat ge'
413                               ; returnL $ GRHS [g'] rhs' }
414 cvtpair (PatG gs,rhs)    = do { gs' <- cvtStmts gs; rhs' <- cvtl rhs
415                               ; returnL $ GRHS gs' rhs' }
416
417 cvtOverLit :: Lit -> CvtM (HsOverLit RdrName)
418 cvtOverLit (IntegerL i)  = do { force i; return $ mkHsIntegral i }
419 cvtOverLit (RationalL r) = do { force r; return $ mkHsFractional r }
420 -- An Integer is like an an (overloaded) '3' in a Haskell source program
421 -- Similarly 3.5 for fractionals
422
423 cvtLit :: Lit -> CvtM HsLit
424 cvtLit (IntPrimL i)    = do { force i; return $ HsIntPrim i }
425 cvtLit (FloatPrimL f)  = do { force f; return $ HsFloatPrim f }
426 cvtLit (DoublePrimL f) = do { force f; return $ HsDoublePrim f }
427 cvtLit (CharL c)       = do { force c; return $ HsChar c }
428 cvtLit (StringL s)     = do { let { s' = mkFastString s }; force s'; return $ HsString s' }
429
430 cvtPats :: [TH.Pat] -> CvtM [Hs.LPat RdrName]
431 cvtPats pats = mapM cvtPat pats
432
433 cvtPat :: TH.Pat -> CvtM (Hs.LPat RdrName)
434 cvtPat pat = wrapL (cvtp pat)
435
436 cvtp :: TH.Pat -> CvtM (Hs.Pat RdrName)
437 cvtp (TH.LitP l)
438   | overloadedLit l   = do { l' <- cvtOverLit l
439                            ; return (mkNPat l' Nothing) }
440                                   -- Not right for negative patterns; 
441                                   -- need to think about that!
442   | otherwise         = do { l' <- cvtLit l; return $ Hs.LitPat l' }
443 cvtp (TH.VarP s)      = do { s' <- vName s; return $ Hs.VarPat s' }
444 cvtp (TupP [p])       = cvtp p
445 cvtp (TupP ps)        = do { ps' <- cvtPats ps; return $ TuplePat ps' Boxed void }
446 cvtp (ConP s ps)      = do { s' <- cNameL s; ps' <- cvtPats ps; return $ ConPatIn s' (PrefixCon ps') }
447 cvtp (InfixP p1 s p2) = do { s' <- cNameL s; p1' <- cvtPat p1; p2' <- cvtPat p2
448                            ; return $ ConPatIn s' (InfixCon p1' p2') }
449 cvtp (TildeP p)       = do { p' <- cvtPat p; return $ LazyPat p' }
450 cvtp (TH.AsP s p)     = do { s' <- vNameL s; p' <- cvtPat p; return $ AsPat s' p' }
451 cvtp TH.WildP         = return $ WildPat void
452 cvtp (RecP c fs)      = do { c' <- cNameL c; fs' <- mapM cvtPatFld fs 
453                            ; return $ ConPatIn c' $ Hs.RecCon fs' }
454 cvtp (ListP ps)       = do { ps' <- cvtPats ps; return $ ListPat ps' void }
455 cvtp (SigP p t)       = do { p' <- cvtPat p; t' <- cvtType t; return $ SigPatIn p' t' }
456
457 cvtPatFld (s,p) = do { s' <- vNameL s; p' <- cvtPat p; return (s',p') }
458
459 -----------------------------------------------------------
460 --      Types and type variables
461
462 cvtTvs :: [TH.Name] -> CvtM [LHsTyVarBndr RdrName]
463 cvtTvs tvs = mapM cvt_tv tvs
464
465 cvt_tv tv = do { tv' <- tName tv; returnL $ UserTyVar tv' }
466
467 cvtContext :: Cxt -> CvtM (LHsContext RdrName)
468 cvtContext tys = do { preds' <- mapM cvtPred tys; returnL preds' }
469
470 cvtPred :: TH.Type -> CvtM (LHsPred RdrName)
471 cvtPred ty 
472   = do  { (head, tys') <- split_ty_app ty
473         ; case head of
474             ConT tc -> do { tc' <- tconName tc; returnL $ HsClassP tc' tys' }
475             VarT tv -> do { tv' <- tName tv;    returnL $ HsClassP tv' tys' }
476             other   -> failWith (ptext SLIT("Malformed predicate") <+> text (TH.pprint ty)) }
477
478 cvtType :: TH.Type -> CvtM (LHsType RdrName)
479 cvtType ty = do { (head, tys') <- split_ty_app ty
480                 ; case head of
481                     TupleT n | length tys' == n -> returnL (HsTupleTy Boxed tys')
482                              | n == 0    -> mk_apps (HsTyVar (getRdrName unitTyCon)) tys'
483                              | otherwise -> mk_apps (HsTyVar (getRdrName (tupleTyCon Boxed n))) tys'
484                     ArrowT | [x',y'] <- tys' -> returnL (HsFunTy x' y')
485                     ListT  | [x']    <- tys' -> returnL (HsListTy x')
486                     VarT nm -> do { nm' <- tName nm;    mk_apps (HsTyVar nm') tys' }
487                     ConT nm -> do { nm' <- tconName nm; mk_apps (HsTyVar nm') tys' }
488
489                     ForallT tvs cxt ty | null tys' -> do { tvs' <- cvtTvs tvs
490                                                          ; cxt' <- cvtContext cxt
491                                                          ; ty'  <- cvtType ty
492                                                          ; returnL $ mkExplicitHsForAllTy tvs' cxt' ty' }
493                     otherwise -> failWith (ptext SLIT("Malformed type") <+> text (show ty))
494              }
495   where
496     mk_apps head []       = returnL head
497     mk_apps head (ty:tys) = do { head' <- returnL head; mk_apps (HsAppTy head' ty) tys }
498
499 split_ty_app :: TH.Type -> CvtM (TH.Type, [LHsType RdrName])
500 split_ty_app ty = go ty []
501   where
502     go (AppT f a) as' = do { a' <- cvtType a; go f (a':as') }
503     go f as           = return (f,as)
504
505 -----------------------------------------------------------
506
507
508 -----------------------------------------------------------
509 -- some useful things
510
511 truePat  = nlConPat (getRdrName trueDataCon)  []
512
513 overloadedLit :: Lit -> Bool
514 -- True for literals that Haskell treats as overloaded
515 overloadedLit (IntegerL  l) = True
516 overloadedLit (RationalL l) = True
517 overloadedLit l             = False
518
519 void :: Type.Type
520 void = placeHolderType
521
522 --------------------------------------------------------------------
523 --      Turning Name back into RdrName
524 --------------------------------------------------------------------
525
526 -- variable names
527 vNameL, cNameL, tconNameL :: TH.Name -> CvtM (Located RdrName)
528 vName,  cName,  tName,  tconName  :: TH.Name -> CvtM RdrName
529
530 vNameL n = wrapL (vName n)
531 vName n = cvtName OccName.varName n
532
533 -- Constructor function names; this is Haskell source, hence srcDataName
534 cNameL n = wrapL (cName n)
535 cName n = cvtName OccName.dataName n 
536
537 -- Type variable names
538 tName n = cvtName OccName.tvName n
539
540 -- Type Constructor names
541 tconNameL n = wrapL (tconName n)
542 tconName n = cvtName OccName.tcClsName n
543
544 cvtName :: OccName.NameSpace -> TH.Name -> CvtM RdrName
545 cvtName ctxt_ns (TH.Name occ flavour)
546   | not (okOcc ctxt_ns occ_str) = failWith (badOcc ctxt_ns occ_str)
547   | otherwise                   = force (thRdrName ctxt_ns occ_str flavour)
548   where
549     occ_str = TH.occString occ
550
551 okOcc :: OccName.NameSpace -> String -> Bool
552 okOcc _  []      = False
553 okOcc ns str@(c:_) 
554   | OccName.isVarName ns = startsVarId c || startsVarSym c
555   | otherwise            = startsConId c || startsConSym c || str == "[]"
556
557 badOcc :: OccName.NameSpace -> String -> SDoc
558 badOcc ctxt_ns occ 
559   = ptext SLIT("Illegal") <+> pprNameSpace ctxt_ns
560         <+> ptext SLIT("name:") <+> quotes (text occ)
561
562 thRdrName :: OccName.NameSpace -> String -> TH.NameFlavour -> RdrName
563 -- This turns a Name into a RdrName
564 -- The passed-in name space tells what the context is expecting;
565 --      use it unless the TH name knows what name-space it comes
566 --      from, in which case use the latter
567 --
568 -- ToDo: we may generate silly RdrNames, by passing a name space
569 --       that doesn't match the string, like VarName ":+", 
570 --       which will give confusing error messages later
571 -- 
572 -- The strict applications ensure that any buried exceptions get forced
573 thRdrName ctxt_ns occ (TH.NameG th_ns pkg mod) = (mkOrig $! (mkModule (mk_pkg pkg) (mk_mod mod))) $! (mk_occ (mk_ghc_ns th_ns) occ)
574 thRdrName ctxt_ns occ (TH.NameL uniq)      = nameRdrName $! (((Name.mkInternalName $! (mk_uniq uniq)) $! (mk_occ ctxt_ns occ)) noSrcLoc)
575 thRdrName ctxt_ns occ (TH.NameQ mod)       = (mkRdrQual  $! (mk_mod mod)) $! (mk_occ ctxt_ns occ)
576 thRdrName ctxt_ns occ (TH.NameU uniq)      = mkRdrUnqual $! (mk_uniq_occ ctxt_ns occ uniq)
577 thRdrName ctxt_ns occ TH.NameS
578   | Just name <- isBuiltInOcc ctxt_ns occ  = nameRdrName $! name
579   | otherwise                              = mkRdrUnqual $! (mk_occ ctxt_ns occ)
580
581 isBuiltInOcc :: OccName.NameSpace -> String -> Maybe Name.Name
582 -- Built in syntax isn't "in scope" so an Unqual RdrName won't do
583 -- We must generate an Exact name, just as the parser does
584 isBuiltInOcc ctxt_ns occ
585   = case occ of
586         ":"              -> Just (Name.getName consDataCon)
587         "[]"             -> Just (Name.getName nilDataCon)
588         "()"             -> Just (tup_name 0)
589         '(' : ',' : rest -> go_tuple 2 rest
590         other            -> Nothing
591   where
592     go_tuple n ")"          = Just (tup_name n)
593     go_tuple n (',' : rest) = go_tuple (n+1) rest
594     go_tuple n other        = Nothing
595
596     tup_name n 
597         | OccName.isTcClsName ctxt_ns = Name.getName (tupleTyCon Boxed n)
598         | otherwise                   = Name.getName (tupleCon Boxed n)
599
600 mk_uniq_occ :: OccName.NameSpace -> String -> Int# -> OccName.OccName
601 mk_uniq_occ ns occ uniq 
602   = OccName.mkOccName ns (occ ++ '[' : shows (mk_uniq uniq) "]")
603         -- The idea here is to make a name that 
604         -- a) the user could not possibly write, and
605         -- b) cannot clash with another NameU
606         -- Previously I generated an Exact RdrName with mkInternalName.
607         -- This works fine for local binders, but does not work at all for
608         -- top-level binders, which must have External Names, since they are
609         -- rapidly baked into data constructors and the like.  Baling out
610         -- and generating an unqualified RdrName here is the simple solution
611
612 -- The packing and unpacking is rather turgid :-(
613 mk_occ :: OccName.NameSpace -> String -> OccName.OccName
614 mk_occ ns occ = OccName.mkOccNameFS ns (mkFastString occ)
615
616 mk_ghc_ns :: TH.NameSpace -> OccName.NameSpace
617 mk_ghc_ns TH.DataName  = OccName.dataName
618 mk_ghc_ns TH.TcClsName = OccName.tcClsName
619 mk_ghc_ns TH.VarName   = OccName.varName
620
621 mk_mod :: TH.ModName -> ModuleName
622 mk_mod mod = mkModuleName (TH.modString mod)
623
624 mk_pkg :: TH.ModName -> PackageId
625 mk_pkg pkg = stringToPackageId (TH.pkgString pkg)
626
627 mk_uniq :: Int# -> Unique
628 mk_uniq u = mkUniqueGrimily (I# u)
629 \end{code}
630