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