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 ( ModuleName, mkModuleName, mkModule )
21 import RdrHsSyn ( mkClassDecl, mkTyData )
22 import qualified OccName
23 import PackageConfig ( PackageId, stringToPackageId )
24 import OccName ( startsVarId, startsVarSym, startsConId, startsConSym,
26 import SrcLoc ( Located(..), SrcSpan )
28 import TysWiredIn ( unitTyCon, tupleTyCon, tupleCon, trueDataCon, nilDataCon, consDataCon )
29 import BasicTypes( Boxity(..) )
30 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..),
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 )
44 -------------------------------------------------------------------
45 -- The external interface
47 convertToHsDecls :: SrcSpan -> [TH.Dec] -> Either Message [LHsDecl RdrName]
48 convertToHsDecls loc ds = initCvt loc (mapM cvtTop ds)
50 convertToHsExpr :: SrcSpan -> TH.Exp -> Either Message (LHsExpr RdrName)
52 = case initCvt loc (cvtl e) of
53 Left msg -> Left (msg $$ (ptext SLIT("When converting TH expression")
55 Right res -> Right res
57 convertToHsType :: SrcSpan -> TH.Type -> Either Message (LHsType RdrName)
58 convertToHsType loc t = initCvt loc (cvtType t)
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
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
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
75 instance Monad CvtM where
76 return x = CvtM $ \loc -> Right x
77 (CvtM m) >>= k = CvtM $ \loc -> case m loc of
79 Right v -> unCvtM (k v) loc
81 initCvt :: SrcSpan -> CvtM a -> Either Message a
82 initCvt loc (CvtM m) = m loc
85 force a = a `seq` return a
87 failWith :: Message -> CvtM a
88 failWith m = CvtM (\loc -> Left full_msg)
90 full_msg = m $$ ptext SLIT("When splicing generated code into the program")
92 returnL :: a -> CvtM (Located a)
93 returnL x = CvtM (\loc -> Right (L loc x))
95 wrapL :: CvtM a -> CvtM (Located a)
96 wrapL (CvtM m) = CvtM (\loc -> case m loc of
98 Right v -> Right (L loc v))
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
106 ; returnL $ Hs.SigD (TypeSig nm' ty') }
108 cvtTop (TySynD tc tvs rhs)
109 = do { tc' <- tconNameL tc
111 ; rhs' <- cvtType rhs
112 ; returnL $ TyClD (TySynonym tc' tvs' Nothing rhs') }
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') }
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') }
127 cvtTop (ClassD ctxt cl tvs fds decs)
128 = do { (cxt', tc', tvs', _) <- cvt_tycl_hdr ctxt cl tvs
129 ; fds' <- mapM cvt_fundep fds
130 ; (binds', sigs') <- cvtBindsAndSigs decs
131 ; returnL $ TyClD $ mkClassDecl (cxt', tc', tvs') fds' sigs' binds' []
135 cvtTop (InstanceD tys ty decs)
136 = do { (binds', sigs') <- cvtBindsAndSigs decs
137 ; ctxt' <- cvtContext tys
138 ; L loc pred' <- cvtPred ty
139 ; inst_ty' <- returnL $ mkImplicitHsForAllTy ctxt' (L loc (HsPredTy pred'))
140 ; returnL $ InstD (InstDecl inst_ty' binds' sigs' [])
144 cvtTop (ForeignD ford) = do { ford' <- cvtForD ford; returnL $ ForD ford' }
146 cvt_tycl_hdr cxt tc tvs
147 = do { cxt' <- cvtContext cxt
148 ; tc' <- tconNameL tc
150 ; return (cxt', tc', tvs', Nothing) }
152 ---------------------------------------------------
154 -- Can't handle GADTs yet
155 ---------------------------------------------------
157 cvtConstr (NormalC c strtys)
158 = do { c' <- cNameL c
160 ; tys' <- mapM cvt_arg strtys
161 ; returnL $ ConDecl c' Explicit noExistentials cxt' (PrefixCon tys') ResTyH98 }
163 cvtConstr (RecC c varstrtys)
164 = do { c' <- cNameL c
166 ; args' <- mapM cvt_id_arg varstrtys
167 ; returnL $ ConDecl c' Explicit noExistentials cxt' (RecCon args') ResTyH98 }
169 cvtConstr (InfixC st1 c st2)
170 = do { c' <- cNameL c
172 ; st1' <- cvt_arg st1
173 ; st2' <- cvt_arg st2
174 ; returnL $ ConDecl c' Explicit noExistentials cxt' (InfixCon st1' st2') ResTyH98 }
176 cvtConstr (ForallC tvs ctxt (ForallC tvs' ctxt' con'))
177 = cvtConstr (ForallC (tvs ++ tvs') (ctxt ++ ctxt') con')
179 cvtConstr (ForallC tvs ctxt con)
180 = do { L _ con' <- cvtConstr con
182 ; ctxt' <- cvtContext ctxt
184 ConDecl l _ [] (L _ []) x ResTyH98
185 -> returnL $ ConDecl l Explicit tvs' ctxt' x ResTyH98
186 c -> panic "ForallC: Can't happen" }
188 cvt_arg (IsStrict, ty) = do { ty' <- cvtType ty; returnL $ HsBangTy HsStrict ty' }
189 cvt_arg (NotStrict, ty) = cvtType ty
191 cvt_id_arg (i, str, ty) = do { i' <- vNameL i
192 ; ty' <- cvt_arg (str,ty)
195 cvtDerivs [] = return Nothing
196 cvtDerivs cs = do { cs' <- mapM cvt_one cs
197 ; return (Just cs') }
199 cvt_one c = do { c' <- tconName c
200 ; returnL $ HsPredTy $ HsClassP c' [] }
202 cvt_fundep :: FunDep -> CvtM (Located (Class.FunDep RdrName))
203 cvt_fundep (FunDep xs ys) = do { xs' <- mapM tName xs; ys' <- mapM tName ys; returnL (xs', ys') }
207 ------------------------------------------
208 -- Foreign declarations
209 ------------------------------------------
211 cvtForD :: Foreign -> CvtM (ForeignDecl RdrName)
212 cvtForD (ImportF callconv safety from nm ty)
213 | Just (c_header, cis) <- parse_ccall_impent (TH.nameBase nm) from
214 = do { nm' <- vNameL nm
216 ; let i = CImport (cvt_conv callconv) safety' c_header nilFS cis
217 ; return $ ForeignImport nm' ty' i }
220 = failWith $ text (show from)<+> ptext SLIT("is not a valid ccall impent")
222 safety' = case safety of
224 Safe -> PlaySafe False
225 Threadsafe -> PlaySafe True
227 cvtForD (ExportF callconv as nm ty)
228 = do { nm' <- vNameL nm
230 ; let e = CExport (CExportStatic (mkFastString as) (cvt_conv callconv))
231 ; return $ ForeignExport nm' ty' e }
233 cvt_conv CCall = CCallConv
234 cvt_conv StdCall = StdCallConv
236 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
237 parse_ccall_impent nm s
238 = case lex_ccall_impent s of
239 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
240 Just ["wrapper"] -> Just (nilFS, CWrapper)
241 Just ("static":ts) -> parse_ccall_impent_static nm ts
242 Just ts -> parse_ccall_impent_static nm ts
245 parse_ccall_impent_static :: String
247 -> Maybe (FastString, CImportSpec)
248 parse_ccall_impent_static nm ts
249 = let ts' = case ts of
250 [ "&", cid] -> [ cid]
251 [fname, "&" ] -> [fname ]
252 [fname, "&", cid] -> [fname, cid]
255 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
256 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
257 [ ] -> Just (nilFS, mk_cid nm)
258 [fname ] -> Just (mkFastString fname, mk_cid nm)
260 where is_cid :: String -> Bool
261 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
262 mk_cid :: String -> CImportSpec
263 mk_cid = CFunction . StaticTarget . mkFastString
265 lex_ccall_impent :: String -> Maybe [String]
266 lex_ccall_impent "" = Just []
267 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
268 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
269 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
270 lex_ccall_impent xs = case span is_valid xs of
272 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
273 where is_valid :: Char -> Bool
274 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
277 ---------------------------------------------------
279 ---------------------------------------------------
281 cvtDecs :: [TH.Dec] -> CvtM (HsLocalBinds RdrName)
282 cvtDecs [] = return EmptyLocalBinds
283 cvtDecs ds = do { (binds,sigs) <- cvtBindsAndSigs ds
284 ; return (HsValBinds (ValBindsIn binds sigs)) }
287 = do { binds' <- mapM cvtBind binds; sigs' <- mapM cvtSig sigs
288 ; return (listToBag binds', sigs') }
290 (sigs, binds) = partition is_sig ds
292 is_sig (TH.SigD _ _) = True
295 cvtSig (TH.SigD nm ty)
296 = do { nm' <- vNameL nm; ty' <- cvtType ty; returnL (Hs.TypeSig nm' ty') }
298 cvtBind :: TH.Dec -> CvtM (LHsBind RdrName)
299 -- Used only for declarations in a 'let/where' clause,
300 -- not for top level decls
301 cvtBind (TH.ValD (TH.VarP s) body ds)
302 = do { s' <- vNameL s
303 ; cl' <- cvtClause (Clause [] body ds)
304 ; returnL $ mkFunBind s' [cl'] }
306 cvtBind (TH.FunD nm cls)
307 = do { nm' <- vNameL nm
308 ; cls' <- mapM cvtClause cls
309 ; returnL $ mkFunBind nm' cls' }
311 cvtBind (TH.ValD p body ds)
312 = do { p' <- cvtPat p
313 ; g' <- cvtGuard body
315 ; returnL $ PatBind { pat_lhs = p', pat_rhs = GRHSs g' ds',
316 pat_rhs_ty = void, bind_fvs = placeHolderNames } }
319 = failWith (sep [ptext SLIT("Illegal kind of declaration in where clause"),
320 nest 2 (text (TH.pprint d))])
322 cvtClause :: TH.Clause -> CvtM (Hs.LMatch RdrName)
323 cvtClause (Clause ps body wheres)
324 = do { ps' <- cvtPats ps
325 ; g' <- cvtGuard body
326 ; ds' <- cvtDecs wheres
327 ; returnL $ Hs.Match ps' Nothing (GRHSs g' ds') }
330 -------------------------------------------------------------------
332 -------------------------------------------------------------------
334 cvtl :: TH.Exp -> CvtM (LHsExpr RdrName)
335 cvtl e = wrapL (cvt e)
337 cvt (VarE s) = do { s' <- vName s; return $ HsVar s' }
338 cvt (ConE s) = do { s' <- cName s; return $ HsVar s' }
340 | overloadedLit l = do { l' <- cvtOverLit l; return $ HsOverLit l' }
341 | otherwise = do { l' <- cvtLit l; return $ HsLit l' }
343 cvt (AppE x y) = do { x' <- cvtl x; y' <- cvtl y; return $ HsApp x' y' }
344 cvt (LamE ps e) = do { ps' <- cvtPats ps; e' <- cvtl e
345 ; return $ HsLam (mkMatchGroup [mkSimpleMatch ps' e']) }
346 cvt (TupE [e]) = cvt e
347 cvt (TupE es) = do { es' <- mapM cvtl es; return $ ExplicitTuple es' Boxed }
348 cvt (CondE x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z
349 ; return $ HsIf x' y' z' }
350 cvt (LetE ds e) = do { ds' <- cvtDecs ds; e' <- cvtl e; return $ HsLet ds' e' }
351 cvt (CaseE e ms) = do { e' <- cvtl e; ms' <- mapM cvtMatch ms
352 ; return $ HsCase e' (mkMatchGroup ms') }
353 cvt (DoE ss) = cvtHsDo DoExpr ss
354 cvt (CompE ss) = cvtHsDo ListComp ss
355 cvt (ArithSeqE dd) = do { dd' <- cvtDD dd; return $ ArithSeq noPostTcExpr dd' }
356 cvt (ListE xs) = do { xs' <- mapM cvtl xs; return $ ExplicitList void xs' }
357 cvt (InfixE (Just x) s (Just y)) = do { x' <- cvtl x; s' <- cvtl s; y' <- cvtl y
358 ; e' <- returnL $ OpApp x' s' undefined y'
359 ; return $ HsPar e' }
360 cvt (InfixE Nothing s (Just y)) = do { s' <- cvtl s; y' <- cvtl y
361 ; return $ SectionR s' y' }
362 cvt (InfixE (Just x) s Nothing ) = do { x' <- cvtl x; s' <- cvtl s
363 ; return $ SectionL x' s' }
364 cvt (InfixE Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
366 cvt (SigE e t) = do { e' <- cvtl e; t' <- cvtType t
367 ; return $ ExprWithTySig e' t' }
368 cvt (RecConE c flds) = do { c' <- cNameL c
369 ; flds' <- mapM cvtFld flds
370 ; return $ RecordCon c' noPostTcExpr flds' }
371 cvt (RecUpdE e flds) = do { e' <- cvtl e
372 ; flds' <- mapM cvtFld flds
373 ; return $ RecordUpd e' flds' placeHolderType placeHolderType }
375 cvtFld (v,e) = do { v' <- vNameL v; e' <- cvtl e; return (v',e') }
377 cvtDD :: Range -> CvtM (ArithSeqInfo RdrName)
378 cvtDD (FromR x) = do { x' <- cvtl x; return $ From x' }
379 cvtDD (FromThenR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromThen x' y' }
380 cvtDD (FromToR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromTo x' y' }
381 cvtDD (FromThenToR x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z; return $ FromThenTo x' y' z' }
383 -------------------------------------
384 -- Do notation and statements
385 -------------------------------------
387 cvtHsDo do_or_lc stmts
388 = do { stmts' <- cvtStmts stmts
389 ; let body = case last stmts' of
390 L _ (ExprStmt body _ _) -> body
391 ; return $ HsDo do_or_lc (init stmts') body void }
393 cvtStmts = mapM cvtStmt
395 cvtStmt :: TH.Stmt -> CvtM (Hs.LStmt RdrName)
396 cvtStmt (NoBindS e) = do { e' <- cvtl e; returnL $ mkExprStmt e' }
397 cvtStmt (TH.BindS p e) = do { p' <- cvtPat p; e' <- cvtl e; returnL $ mkBindStmt p' e' }
398 cvtStmt (TH.LetS ds) = do { ds' <- cvtDecs ds; returnL $ LetStmt ds' }
399 cvtStmt (TH.ParS dss) = do { dss' <- mapM cvt_one dss; returnL $ ParStmt dss' }
401 cvt_one ds = do { ds' <- cvtStmts ds; return (ds', undefined) }
403 cvtMatch :: TH.Match -> CvtM (Hs.LMatch RdrName)
404 cvtMatch (TH.Match p body decs)
405 = do { p' <- cvtPat p
406 ; g' <- cvtGuard body
407 ; decs' <- cvtDecs decs
408 ; returnL $ Hs.Match [p'] Nothing (GRHSs g' decs') }
410 cvtGuard :: TH.Body -> CvtM [LGRHS RdrName]
411 cvtGuard (GuardedB pairs) = mapM cvtpair pairs
412 cvtGuard (NormalB e) = do { e' <- cvtl e; g' <- returnL $ GRHS [] e'; return [g'] }
414 cvtpair :: (TH.Guard, TH.Exp) -> CvtM (LGRHS RdrName)
415 cvtpair (NormalG ge,rhs) = do { ge' <- cvtl ge; rhs' <- cvtl rhs
416 ; g' <- returnL $ mkBindStmt truePat ge'
417 ; returnL $ GRHS [g'] rhs' }
418 cvtpair (PatG gs,rhs) = do { gs' <- cvtStmts gs; rhs' <- cvtl rhs
419 ; returnL $ GRHS gs' rhs' }
421 cvtOverLit :: Lit -> CvtM (HsOverLit RdrName)
422 cvtOverLit (IntegerL i) = do { force i; return $ mkHsIntegral i }
423 cvtOverLit (RationalL r) = do { force r; return $ mkHsFractional r }
424 -- An Integer is like an an (overloaded) '3' in a Haskell source program
425 -- Similarly 3.5 for fractionals
427 cvtLit :: Lit -> CvtM HsLit
428 cvtLit (IntPrimL i) = do { force i; return $ HsIntPrim i }
429 cvtLit (FloatPrimL f) = do { force f; return $ HsFloatPrim f }
430 cvtLit (DoublePrimL f) = do { force f; return $ HsDoublePrim f }
431 cvtLit (CharL c) = do { force c; return $ HsChar c }
432 cvtLit (StringL s) = do { let { s' = mkFastString s }; force s'; return $ HsString s' }
434 cvtPats :: [TH.Pat] -> CvtM [Hs.LPat RdrName]
435 cvtPats pats = mapM cvtPat pats
437 cvtPat :: TH.Pat -> CvtM (Hs.LPat RdrName)
438 cvtPat pat = wrapL (cvtp pat)
440 cvtp :: TH.Pat -> CvtM (Hs.Pat RdrName)
442 | overloadedLit l = do { l' <- cvtOverLit l
443 ; return (mkNPat l' Nothing) }
444 -- Not right for negative patterns;
445 -- need to think about that!
446 | otherwise = do { l' <- cvtLit l; return $ Hs.LitPat l' }
447 cvtp (TH.VarP s) = do { s' <- vName s; return $ Hs.VarPat s' }
448 cvtp (TupP [p]) = cvtp p
449 cvtp (TupP ps) = do { ps' <- cvtPats ps; return $ TuplePat ps' Boxed void }
450 cvtp (ConP s ps) = do { s' <- cNameL s; ps' <- cvtPats ps; return $ ConPatIn s' (PrefixCon ps') }
451 cvtp (InfixP p1 s p2) = do { s' <- cNameL s; p1' <- cvtPat p1; p2' <- cvtPat p2
452 ; return $ ConPatIn s' (InfixCon p1' p2') }
453 cvtp (TildeP p) = do { p' <- cvtPat p; return $ LazyPat p' }
454 cvtp (TH.AsP s p) = do { s' <- vNameL s; p' <- cvtPat p; return $ AsPat s' p' }
455 cvtp TH.WildP = return $ WildPat void
456 cvtp (RecP c fs) = do { c' <- cNameL c; fs' <- mapM cvtPatFld fs
457 ; return $ ConPatIn c' $ Hs.RecCon fs' }
458 cvtp (ListP ps) = do { ps' <- cvtPats ps; return $ ListPat ps' void }
459 cvtp (SigP p t) = do { p' <- cvtPat p; t' <- cvtType t; return $ SigPatIn p' t' }
461 cvtPatFld (s,p) = do { s' <- vNameL s; p' <- cvtPat p; return (s',p') }
463 -----------------------------------------------------------
464 -- Types and type variables
466 cvtTvs :: [TH.Name] -> CvtM [LHsTyVarBndr RdrName]
467 cvtTvs tvs = mapM cvt_tv tvs
469 cvt_tv tv = do { tv' <- tName tv; returnL $ UserTyVar tv' }
471 cvtContext :: Cxt -> CvtM (LHsContext RdrName)
472 cvtContext tys = do { preds' <- mapM cvtPred tys; returnL preds' }
474 cvtPred :: TH.Type -> CvtM (LHsPred RdrName)
476 = do { (head, tys') <- split_ty_app ty
478 ConT tc -> do { tc' <- tconName tc; returnL $ HsClassP tc' tys' }
479 VarT tv -> do { tv' <- tName tv; returnL $ HsClassP tv' tys' }
480 other -> failWith (ptext SLIT("Malformed predicate") <+> text (TH.pprint ty)) }
482 cvtType :: TH.Type -> CvtM (LHsType RdrName)
483 cvtType ty = do { (head, tys') <- split_ty_app ty
485 TupleT n | length tys' == n -> returnL (HsTupleTy Boxed tys')
486 | n == 0 -> mk_apps (HsTyVar (getRdrName unitTyCon)) tys'
487 | otherwise -> mk_apps (HsTyVar (getRdrName (tupleTyCon Boxed n))) tys'
488 ArrowT | [x',y'] <- tys' -> returnL (HsFunTy x' y')
489 ListT | [x'] <- tys' -> returnL (HsListTy x')
490 VarT nm -> do { nm' <- tName nm; mk_apps (HsTyVar nm') tys' }
491 ConT nm -> do { nm' <- tconName nm; mk_apps (HsTyVar nm') tys' }
493 ForallT tvs cxt ty | null tys' -> do { tvs' <- cvtTvs tvs
494 ; cxt' <- cvtContext cxt
496 ; returnL $ mkExplicitHsForAllTy tvs' cxt' ty' }
497 otherwise -> failWith (ptext SLIT("Malformed type") <+> text (show ty))
500 mk_apps head [] = returnL head
501 mk_apps head (ty:tys) = do { head' <- returnL head; mk_apps (HsAppTy head' ty) tys }
503 split_ty_app :: TH.Type -> CvtM (TH.Type, [LHsType RdrName])
504 split_ty_app ty = go ty []
506 go (AppT f a) as' = do { a' <- cvtType a; go f (a':as') }
507 go f as = return (f,as)
509 -----------------------------------------------------------
512 -----------------------------------------------------------
513 -- some useful things
515 truePat = nlConPat (getRdrName trueDataCon) []
517 overloadedLit :: Lit -> Bool
518 -- True for literals that Haskell treats as overloaded
519 overloadedLit (IntegerL l) = True
520 overloadedLit (RationalL l) = True
521 overloadedLit l = False
524 void = placeHolderType
526 --------------------------------------------------------------------
527 -- Turning Name back into RdrName
528 --------------------------------------------------------------------
531 vNameL, cNameL, tconNameL :: TH.Name -> CvtM (Located RdrName)
532 vName, cName, tName, tconName :: TH.Name -> CvtM RdrName
534 vNameL n = wrapL (vName n)
535 vName n = cvtName OccName.varName n
537 -- Constructor function names; this is Haskell source, hence srcDataName
538 cNameL n = wrapL (cName n)
539 cName n = cvtName OccName.dataName n
541 -- Type variable names
542 tName n = cvtName OccName.tvName n
544 -- Type Constructor names
545 tconNameL n = wrapL (tconName n)
546 tconName n = cvtName OccName.tcClsName n
548 cvtName :: OccName.NameSpace -> TH.Name -> CvtM RdrName
549 cvtName ctxt_ns (TH.Name occ flavour)
550 | not (okOcc ctxt_ns occ_str) = failWith (badOcc ctxt_ns occ_str)
551 | otherwise = force (thRdrName ctxt_ns occ_str flavour)
553 occ_str = TH.occString occ
555 okOcc :: OccName.NameSpace -> String -> Bool
558 | OccName.isVarName ns = startsVarId c || startsVarSym c
559 | otherwise = startsConId c || startsConSym c || str == "[]"
561 badOcc :: OccName.NameSpace -> String -> SDoc
563 = ptext SLIT("Illegal") <+> pprNameSpace ctxt_ns
564 <+> ptext SLIT("name:") <+> quotes (text occ)
566 thRdrName :: OccName.NameSpace -> String -> TH.NameFlavour -> RdrName
567 -- This turns a Name into a RdrName
568 -- The passed-in name space tells what the context is expecting;
569 -- use it unless the TH name knows what name-space it comes
570 -- from, in which case use the latter
572 -- ToDo: we may generate silly RdrNames, by passing a name space
573 -- that doesn't match the string, like VarName ":+",
574 -- which will give confusing error messages later
576 -- The strict applications ensure that any buried exceptions get forced
577 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)
578 thRdrName ctxt_ns occ (TH.NameL uniq) = nameRdrName $! (((Name.mkInternalName $! (mk_uniq uniq)) $! (mk_occ ctxt_ns occ)) noSrcLoc)
579 thRdrName ctxt_ns occ (TH.NameQ mod) = (mkRdrQual $! (mk_mod mod)) $! (mk_occ ctxt_ns occ)
580 thRdrName ctxt_ns occ (TH.NameU uniq) = mkRdrUnqual $! (mk_uniq_occ ctxt_ns occ uniq)
581 thRdrName ctxt_ns occ TH.NameS
582 | Just name <- isBuiltInOcc ctxt_ns occ = nameRdrName $! name
583 | otherwise = mkRdrUnqual $! (mk_occ ctxt_ns occ)
585 isBuiltInOcc :: OccName.NameSpace -> String -> Maybe Name.Name
586 -- Built in syntax isn't "in scope" so an Unqual RdrName won't do
587 -- We must generate an Exact name, just as the parser does
588 isBuiltInOcc ctxt_ns occ
590 ":" -> Just (Name.getName consDataCon)
591 "[]" -> Just (Name.getName nilDataCon)
592 "()" -> Just (tup_name 0)
593 '(' : ',' : rest -> go_tuple 2 rest
596 go_tuple n ")" = Just (tup_name n)
597 go_tuple n (',' : rest) = go_tuple (n+1) rest
598 go_tuple n other = Nothing
601 | OccName.isTcClsName ctxt_ns = Name.getName (tupleTyCon Boxed n)
602 | otherwise = Name.getName (tupleCon Boxed n)
604 mk_uniq_occ :: OccName.NameSpace -> String -> Int# -> OccName.OccName
605 mk_uniq_occ ns occ uniq
606 = OccName.mkOccName ns (occ ++ '[' : shows (mk_uniq uniq) "]")
607 -- The idea here is to make a name that
608 -- a) the user could not possibly write, and
609 -- b) cannot clash with another NameU
610 -- Previously I generated an Exact RdrName with mkInternalName.
611 -- This works fine for local binders, but does not work at all for
612 -- top-level binders, which must have External Names, since they are
613 -- rapidly baked into data constructors and the like. Baling out
614 -- and generating an unqualified RdrName here is the simple solution
616 -- The packing and unpacking is rather turgid :-(
617 mk_occ :: OccName.NameSpace -> String -> OccName.OccName
618 mk_occ ns occ = OccName.mkOccNameFS ns (mkFastString occ)
620 mk_ghc_ns :: TH.NameSpace -> OccName.NameSpace
621 mk_ghc_ns TH.DataName = OccName.dataName
622 mk_ghc_ns TH.TcClsName = OccName.tcClsName
623 mk_ghc_ns TH.VarName = OccName.varName
625 mk_mod :: TH.ModName -> ModuleName
626 mk_mod mod = mkModuleName (TH.modString mod)
628 mk_pkg :: TH.ModName -> PackageId
629 mk_pkg pkg = stringToPackageId (TH.pkgString pkg)
631 mk_uniq :: Int# -> Unique
632 mk_uniq u = mkUniqueGrimily (I# u)