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