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