2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 This module converts Template Haskell syntax into HsSyn
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 module Convert( convertToHsExpr, convertToPat, convertToHsDecls,
17 convertToHsType, thRdrName ) where
20 import qualified Class
25 import qualified OccName
40 import Language.Haskell.TH as TH hiding (sigP)
41 import Language.Haskell.TH.Syntax as TH
45 -------------------------------------------------------------------
46 -- The external interface
48 convertToHsDecls :: SrcSpan -> [TH.Dec] -> Either Message [LHsDecl RdrName]
49 convertToHsDecls loc ds = initCvt loc (mapM cvtTop ds)
51 convertToHsExpr :: SrcSpan -> TH.Exp -> Either Message (LHsExpr RdrName)
53 = case initCvt loc (cvtl e) of
54 Left msg -> Left (msg $$ (ptext (sLit "When converting TH expression")
56 Right res -> Right res
58 convertToPat :: SrcSpan -> TH.Pat -> Either Message (LPat RdrName)
60 = case initCvt loc (cvtPat e) of
61 Left msg -> Left (msg $$ (ptext (sLit "When converting TH pattern")
63 Right res -> Right res
65 convertToHsType :: SrcSpan -> TH.Type -> Either Message (LHsType RdrName)
66 convertToHsType loc t = initCvt loc (cvtType t)
69 -------------------------------------------------------------------
70 newtype CvtM a = CvtM { unCvtM :: SrcSpan -> Either Message a }
71 -- Push down the source location;
72 -- Can fail, with a single error message
74 -- NB: If the conversion succeeds with (Right x), there should
75 -- be no exception values hiding in x
76 -- Reason: so a (head []) in TH code doesn't subsequently
77 -- make GHC crash when it tries to walk the generated tree
79 -- Use the loc everywhere, for lack of anything better
80 -- In particular, we want it on binding locations, so that variables bound in
81 -- the spliced-in declarations get a location that at least relates to the splice point
83 instance Monad CvtM where
84 return x = CvtM $ \_ -> Right x
85 (CvtM m) >>= k = CvtM $ \loc -> case m loc of
87 Right v -> unCvtM (k v) loc
89 initCvt :: SrcSpan -> CvtM a -> Either Message a
90 initCvt loc (CvtM m) = m loc
93 force a = a `seq` return a
95 failWith :: Message -> CvtM a
96 failWith m = CvtM (\_ -> Left full_msg)
98 full_msg = m $$ ptext (sLit "When splicing generated code into the program")
100 returnL :: a -> CvtM (Located a)
101 returnL x = CvtM (\loc -> Right (L loc x))
103 wrapL :: CvtM a -> CvtM (Located a)
104 wrapL (CvtM m) = CvtM (\loc -> case m loc of
106 Right v -> Right (L loc v))
108 -------------------------------------------------------------------
109 cvtTop :: TH.Dec -> CvtM (LHsDecl RdrName)
110 cvtTop d@(TH.ValD _ _ _) = do { L loc d' <- cvtBind d; return (L loc $ Hs.ValD d') }
111 cvtTop d@(TH.FunD _ _) = do { L loc d' <- cvtBind d; return (L loc $ Hs.ValD d') }
112 cvtTop (TH.SigD nm typ) = do { nm' <- vNameL nm
114 ; returnL $ Hs.SigD (TypeSig nm' ty') }
116 cvtTop (TySynD tc tvs rhs)
117 = do { tc' <- tconNameL tc
119 ; rhs' <- cvtType rhs
120 ; returnL $ TyClD (TySynonym tc' tvs' Nothing rhs') }
122 cvtTop (DataD ctxt tc tvs constrs derivs)
123 = do { stuff <- cvt_tycl_hdr ctxt tc tvs
124 ; cons' <- mapM cvtConstr constrs
125 ; derivs' <- cvtDerivs derivs
126 ; returnL $ TyClD (mkTyData DataType stuff Nothing cons' derivs') }
129 cvtTop (NewtypeD ctxt tc tvs constr derivs)
130 = do { stuff <- cvt_tycl_hdr ctxt tc tvs
131 ; con' <- cvtConstr constr
132 ; derivs' <- cvtDerivs derivs
133 ; returnL $ TyClD (mkTyData NewType stuff Nothing [con'] derivs') }
135 cvtTop (ClassD ctxt cl tvs fds decs)
136 = do { (cxt', tc', tvs', _) <- cvt_tycl_hdr ctxt cl tvs
137 ; fds' <- mapM cvt_fundep fds
138 ; (binds', sigs') <- cvtBindsAndSigs decs
139 ; returnL $ TyClD $ mkClassDecl (cxt', tc', tvs') fds' sigs' binds' [] []
140 -- no ATs or docs in TH ^^ ^^
143 cvtTop (InstanceD tys ty decs)
144 = do { (binds', sigs') <- cvtBindsAndSigs decs
145 ; ctxt' <- cvtContext tys
146 ; L loc pred' <- cvtPred ty
147 ; inst_ty' <- returnL $ mkImplicitHsForAllTy ctxt' (L loc (HsPredTy pred'))
148 ; returnL $ InstD (InstDecl inst_ty' binds' sigs' [])
152 cvtTop (ForeignD ford) = do { ford' <- cvtForD ford; returnL $ ForD ford' }
154 cvt_tycl_hdr :: TH.Cxt -> TH.Name -> [TH.Name]
155 -> CvtM (LHsContext RdrName
157 ,[LHsTyVarBndr RdrName]
158 ,Maybe [LHsType RdrName])
159 cvt_tycl_hdr cxt tc tvs
160 = do { cxt' <- cvtContext cxt
161 ; tc' <- tconNameL tc
163 ; return (cxt', tc', tvs', Nothing) }
165 ---------------------------------------------------
167 -- Can't handle GADTs yet
168 ---------------------------------------------------
170 cvtConstr :: TH.Con -> CvtM (LConDecl RdrName)
172 cvtConstr (NormalC c strtys)
173 = do { c' <- cNameL c
175 ; tys' <- mapM cvt_arg strtys
176 ; returnL $ ConDecl c' Explicit noExistentials cxt' (PrefixCon tys') ResTyH98 Nothing }
178 cvtConstr (RecC c varstrtys)
179 = do { c' <- cNameL c
181 ; args' <- mapM cvt_id_arg varstrtys
182 ; returnL $ ConDecl c' Explicit noExistentials cxt' (RecCon args') ResTyH98 Nothing }
184 cvtConstr (InfixC st1 c st2)
185 = do { c' <- cNameL c
187 ; st1' <- cvt_arg st1
188 ; st2' <- cvt_arg st2
189 ; returnL $ ConDecl c' Explicit noExistentials cxt' (InfixCon st1' st2') ResTyH98 Nothing }
191 cvtConstr (ForallC tvs ctxt (ForallC tvs' ctxt' con'))
192 = cvtConstr (ForallC (tvs ++ tvs') (ctxt ++ ctxt') con')
194 cvtConstr (ForallC tvs ctxt con)
195 = do { L _ con' <- cvtConstr con
197 ; ctxt' <- cvtContext ctxt
199 ConDecl l _ [] (L _ []) x ResTyH98 _
200 -> returnL $ ConDecl l Explicit tvs' ctxt' x ResTyH98 Nothing
201 _ -> panic "ForallC: Can't happen" }
203 cvt_arg :: (TH.Strict, TH.Type) -> CvtM (LHsType RdrName)
204 cvt_arg (IsStrict, ty) = do { ty' <- cvtType ty; returnL $ HsBangTy HsStrict ty' }
205 cvt_arg (NotStrict, ty) = cvtType ty
207 cvt_id_arg :: (TH.Name, TH.Strict, TH.Type) -> CvtM (ConDeclField RdrName)
208 cvt_id_arg (i, str, ty)
209 = do { i' <- vNameL i
210 ; ty' <- cvt_arg (str,ty)
211 ; return (ConDeclField { cd_fld_name = i', cd_fld_type = ty', cd_fld_doc = Nothing}) }
213 cvtDerivs :: [TH.Name] -> CvtM (Maybe [LHsType RdrName])
214 cvtDerivs [] = return Nothing
215 cvtDerivs cs = do { cs' <- mapM cvt_one cs
216 ; return (Just cs') }
218 cvt_one c = do { c' <- tconName c
219 ; returnL $ HsPredTy $ HsClassP c' [] }
221 cvt_fundep :: FunDep -> CvtM (Located (Class.FunDep RdrName))
222 cvt_fundep (FunDep xs ys) = do { xs' <- mapM tName xs; ys' <- mapM tName ys; returnL (xs', ys') }
224 noExistentials :: [LHsTyVarBndr RdrName]
227 ------------------------------------------
228 -- Foreign declarations
229 ------------------------------------------
231 cvtForD :: Foreign -> CvtM (ForeignDecl RdrName)
232 cvtForD (ImportF callconv safety from nm ty)
233 | Just (c_header, cis) <- parse_ccall_impent (TH.nameBase nm) from
234 = do { nm' <- vNameL nm
236 ; let i = CImport (cvt_conv callconv) safety' c_header nilFS cis
237 ; return $ ForeignImport nm' ty' i }
240 = failWith $ text (show from)<+> ptext (sLit "is not a valid ccall impent")
242 safety' = case safety of
244 Safe -> PlaySafe False
245 Threadsafe -> PlaySafe True
247 cvtForD (ExportF callconv as nm ty)
248 = do { nm' <- vNameL nm
250 ; let e = CExport (CExportStatic (mkFastString as) (cvt_conv callconv))
251 ; return $ ForeignExport nm' ty' e }
253 cvt_conv :: TH.Callconv -> CCallConv
254 cvt_conv TH.CCall = CCallConv
255 cvt_conv TH.StdCall = StdCallConv
257 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
258 parse_ccall_impent nm s
259 = case lex_ccall_impent s of
260 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
261 Just ["wrapper"] -> Just (nilFS, CWrapper)
262 Just ("static":ts) -> parse_ccall_impent_static nm ts
263 Just ts -> parse_ccall_impent_static nm ts
266 parse_ccall_impent_static :: String
268 -> Maybe (FastString, CImportSpec)
269 parse_ccall_impent_static nm ts
270 = let ts' = case ts of
271 [ "&", cid] -> [ cid]
272 [fname, "&" ] -> [fname ]
273 [fname, "&", cid] -> [fname, cid]
276 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
277 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
278 [ ] -> Just (nilFS, mk_cid nm)
279 [fname ] -> Just (mkFastString fname, mk_cid nm)
281 where is_cid :: String -> Bool
282 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
283 mk_cid :: String -> CImportSpec
284 mk_cid = CFunction . StaticTarget . mkFastString
286 lex_ccall_impent :: String -> Maybe [String]
287 lex_ccall_impent "" = Just []
288 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
289 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
290 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
291 lex_ccall_impent xs = case span is_valid xs of
293 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
294 where is_valid :: Char -> Bool
295 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
298 ---------------------------------------------------
300 ---------------------------------------------------
302 cvtDecs :: [TH.Dec] -> CvtM (HsLocalBinds RdrName)
303 cvtDecs [] = return EmptyLocalBinds
304 cvtDecs ds = do { (binds,sigs) <- cvtBindsAndSigs ds
305 ; return (HsValBinds (ValBindsIn binds sigs)) }
307 cvtBindsAndSigs :: [TH.Dec] -> CvtM (Bag (LHsBind RdrName), [LSig RdrName])
309 = do { binds' <- mapM cvtBind binds; sigs' <- mapM cvtSig sigs
310 ; return (listToBag binds', sigs') }
312 (sigs, binds) = partition is_sig ds
314 is_sig (TH.SigD _ _) = True
317 cvtSig :: TH.Dec -> CvtM (LSig RdrName)
318 cvtSig (TH.SigD nm ty)
319 = do { nm' <- vNameL nm; ty' <- cvtType ty; returnL (Hs.TypeSig nm' ty') }
321 cvtBind :: TH.Dec -> CvtM (LHsBind RdrName)
322 -- Used only for declarations in a 'let/where' clause,
323 -- not for top level decls
324 cvtBind (TH.ValD (TH.VarP s) body ds)
325 = do { s' <- vNameL s
326 ; cl' <- cvtClause (Clause [] body ds)
327 ; returnL $ mkFunBind s' [cl'] }
329 cvtBind (TH.FunD nm cls)
330 = do { nm' <- vNameL nm
331 ; cls' <- mapM cvtClause cls
332 ; returnL $ mkFunBind nm' cls' }
334 cvtBind (TH.ValD p body ds)
335 = do { p' <- cvtPat p
336 ; g' <- cvtGuard body
338 ; returnL $ PatBind { pat_lhs = p', pat_rhs = GRHSs g' ds',
339 pat_rhs_ty = void, bind_fvs = placeHolderNames } }
342 = failWith (sep [ptext (sLit "Illegal kind of declaration in where clause"),
343 nest 2 (text (TH.pprint d))])
345 cvtClause :: TH.Clause -> CvtM (Hs.LMatch RdrName)
346 cvtClause (Clause ps body wheres)
347 = do { ps' <- cvtPats ps
348 ; g' <- cvtGuard body
349 ; ds' <- cvtDecs wheres
350 ; returnL $ Hs.Match ps' Nothing (GRHSs g' ds') }
353 -------------------------------------------------------------------
355 -------------------------------------------------------------------
357 cvtl :: TH.Exp -> CvtM (LHsExpr RdrName)
358 cvtl e = wrapL (cvt e)
360 cvt (VarE s) = do { s' <- vName s; return $ HsVar s' }
361 cvt (ConE s) = do { s' <- cName s; return $ HsVar s' }
363 | overloadedLit l = do { l' <- cvtOverLit l; return $ HsOverLit l' }
364 | otherwise = do { l' <- cvtLit l; return $ HsLit l' }
366 cvt (AppE x y) = do { x' <- cvtl x; y' <- cvtl y; return $ HsApp x' y' }
367 cvt (LamE ps e) = do { ps' <- cvtPats ps; e' <- cvtl e
368 ; return $ HsLam (mkMatchGroup [mkSimpleMatch ps' e']) }
369 cvt (TupE [e]) = cvt e -- Singleton tuples treated like nothing (just parens)
370 cvt (TupE es) = do { es' <- mapM cvtl es; return $ ExplicitTuple es' Boxed }
371 cvt (CondE x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z
372 ; return $ HsIf x' y' z' }
373 cvt (LetE ds e) = do { ds' <- cvtDecs ds; e' <- cvtl e; return $ HsLet ds' e' }
374 cvt (CaseE e ms) = do { e' <- cvtl e; ms' <- mapM cvtMatch ms
375 ; return $ HsCase e' (mkMatchGroup ms') }
376 cvt (DoE ss) = cvtHsDo DoExpr ss
377 cvt (CompE ss) = cvtHsDo ListComp ss
378 cvt (ArithSeqE dd) = do { dd' <- cvtDD dd; return $ ArithSeq noPostTcExpr dd' }
379 cvt (ListE xs) = do { xs' <- mapM cvtl xs; return $ ExplicitList void xs' }
380 cvt (InfixE (Just x) s (Just y)) = do { x' <- cvtl x; s' <- cvtl s; y' <- cvtl y
381 ; e' <- returnL $ OpApp x' s' undefined y'
382 ; return $ HsPar e' }
383 cvt (InfixE Nothing s (Just y)) = do { s' <- cvtl s; y' <- cvtl y
384 ; return $ SectionR s' y' }
385 cvt (InfixE (Just x) s Nothing ) = do { x' <- cvtl x; s' <- cvtl s
386 ; return $ SectionL x' s' }
387 cvt (InfixE Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
389 cvt (SigE e t) = do { e' <- cvtl e; t' <- cvtType t
390 ; return $ ExprWithTySig e' t' }
391 cvt (RecConE c flds) = do { c' <- cNameL c
392 ; flds' <- mapM cvtFld flds
393 ; return $ RecordCon c' noPostTcExpr (HsRecFields flds' Nothing)}
394 cvt (RecUpdE e flds) = do { e' <- cvtl e
395 ; flds' <- mapM cvtFld flds
396 ; return $ RecordUpd e' (HsRecFields flds' Nothing) [] [] [] }
398 cvtFld :: (TH.Name, TH.Exp) -> CvtM (HsRecField RdrName (LHsExpr RdrName))
400 = do { v' <- vNameL v; e' <- cvtl e
401 ; return (HsRecField { hsRecFieldId = v', hsRecFieldArg = e', hsRecPun = False}) }
403 cvtDD :: Range -> CvtM (ArithSeqInfo RdrName)
404 cvtDD (FromR x) = do { x' <- cvtl x; return $ From x' }
405 cvtDD (FromThenR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromThen x' y' }
406 cvtDD (FromToR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromTo x' y' }
407 cvtDD (FromThenToR x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z; return $ FromThenTo x' y' z' }
409 -------------------------------------
410 -- Do notation and statements
411 -------------------------------------
413 cvtHsDo :: HsStmtContext Name.Name -> [TH.Stmt] -> CvtM (HsExpr RdrName)
414 cvtHsDo do_or_lc stmts
415 = do { stmts' <- cvtStmts stmts
416 ; let body = case last stmts' of
417 L _ (ExprStmt body _ _) -> body
418 ; return $ HsDo do_or_lc (init stmts') body void }
420 cvtStmts :: [TH.Stmt] -> CvtM [Hs.LStmt RdrName]
421 cvtStmts = mapM cvtStmt
423 cvtStmt :: TH.Stmt -> CvtM (Hs.LStmt RdrName)
424 cvtStmt (NoBindS e) = do { e' <- cvtl e; returnL $ mkExprStmt e' }
425 cvtStmt (TH.BindS p e) = do { p' <- cvtPat p; e' <- cvtl e; returnL $ mkBindStmt p' e' }
426 cvtStmt (TH.LetS ds) = do { ds' <- cvtDecs ds; returnL $ LetStmt ds' }
427 cvtStmt (TH.ParS dss) = do { dss' <- mapM cvt_one dss; returnL $ ParStmt dss' }
429 cvt_one ds = do { ds' <- cvtStmts ds; return (ds', undefined) }
431 cvtMatch :: TH.Match -> CvtM (Hs.LMatch RdrName)
432 cvtMatch (TH.Match p body decs)
433 = do { p' <- cvtPat p
434 ; g' <- cvtGuard body
435 ; decs' <- cvtDecs decs
436 ; returnL $ Hs.Match [p'] Nothing (GRHSs g' decs') }
438 cvtGuard :: TH.Body -> CvtM [LGRHS RdrName]
439 cvtGuard (GuardedB pairs) = mapM cvtpair pairs
440 cvtGuard (NormalB e) = do { e' <- cvtl e; g' <- returnL $ GRHS [] e'; return [g'] }
442 cvtpair :: (TH.Guard, TH.Exp) -> CvtM (LGRHS RdrName)
443 cvtpair (NormalG ge,rhs) = do { ge' <- cvtl ge; rhs' <- cvtl rhs
444 ; g' <- returnL $ mkExprStmt ge'
445 ; returnL $ GRHS [g'] rhs' }
446 cvtpair (PatG gs,rhs) = do { gs' <- cvtStmts gs; rhs' <- cvtl rhs
447 ; returnL $ GRHS gs' rhs' }
449 cvtOverLit :: Lit -> CvtM (HsOverLit RdrName)
450 cvtOverLit (IntegerL i) = do { force i; return $ mkHsIntegral i placeHolderType}
451 cvtOverLit (RationalL r) = do { force r; return $ mkHsFractional r placeHolderType}
452 cvtOverLit (StringL s) = do { let { s' = mkFastString s }; force s'; return $ mkHsIsString s' placeHolderType }
453 -- An Integer is like an an (overloaded) '3' in a Haskell source program
454 -- Similarly 3.5 for fractionals
456 cvtLit :: Lit -> CvtM HsLit
457 cvtLit (IntPrimL i) = do { force i; return $ HsIntPrim i }
458 cvtLit (WordPrimL w) = do { force w; return $ HsWordPrim w }
459 cvtLit (FloatPrimL f) = do { force f; return $ HsFloatPrim f }
460 cvtLit (DoublePrimL f) = do { force f; return $ HsDoublePrim f }
461 cvtLit (CharL c) = do { force c; return $ HsChar c }
462 cvtLit (StringL s) = do { let { s' = mkFastString s }; force s'; return $ HsString s' }
464 cvtPats :: [TH.Pat] -> CvtM [Hs.LPat RdrName]
465 cvtPats pats = mapM cvtPat pats
467 cvtPat :: TH.Pat -> CvtM (Hs.LPat RdrName)
468 cvtPat pat = wrapL (cvtp pat)
470 cvtp :: TH.Pat -> CvtM (Hs.Pat RdrName)
472 | overloadedLit l = do { l' <- cvtOverLit l
473 ; return (mkNPat l' Nothing) }
474 -- Not right for negative patterns;
475 -- need to think about that!
476 | otherwise = do { l' <- cvtLit l; return $ Hs.LitPat l' }
477 cvtp (TH.VarP s) = do { s' <- vName s; return $ Hs.VarPat s' }
478 cvtp (TupP [p]) = cvtp p
479 cvtp (TupP ps) = do { ps' <- cvtPats ps; return $ TuplePat ps' Boxed void }
480 cvtp (ConP s ps) = do { s' <- cNameL s; ps' <- cvtPats ps; return $ ConPatIn s' (PrefixCon ps') }
481 cvtp (InfixP p1 s p2) = do { s' <- cNameL s; p1' <- cvtPat p1; p2' <- cvtPat p2
482 ; return $ ConPatIn s' (InfixCon p1' p2') }
483 cvtp (TildeP p) = do { p' <- cvtPat p; return $ LazyPat p' }
484 cvtp (TH.AsP s p) = do { s' <- vNameL s; p' <- cvtPat p; return $ AsPat s' p' }
485 cvtp TH.WildP = return $ WildPat void
486 cvtp (RecP c fs) = do { c' <- cNameL c; fs' <- mapM cvtPatFld fs
487 ; return $ ConPatIn c' $ Hs.RecCon (HsRecFields fs' Nothing) }
488 cvtp (ListP ps) = do { ps' <- cvtPats ps; return $ ListPat ps' void }
489 cvtp (SigP p t) = do { p' <- cvtPat p; t' <- cvtType t; return $ SigPatIn p' t' }
491 cvtPatFld :: (TH.Name, TH.Pat) -> CvtM (HsRecField RdrName (LPat RdrName))
493 = do { s' <- vNameL s; p' <- cvtPat p
494 ; return (HsRecField { hsRecFieldId = s', hsRecFieldArg = p', hsRecPun = False}) }
496 -----------------------------------------------------------
497 -- Types and type variables
499 cvtTvs :: [TH.Name] -> CvtM [LHsTyVarBndr RdrName]
500 cvtTvs tvs = mapM cvt_tv tvs
502 cvt_tv :: TH.Name -> CvtM (LHsTyVarBndr RdrName)
503 cvt_tv tv = do { tv' <- tName tv; returnL $ UserTyVar tv' }
505 cvtContext :: Cxt -> CvtM (LHsContext RdrName)
506 cvtContext tys = do { preds' <- mapM cvtPred tys; returnL preds' }
508 cvtPred :: TH.Type -> CvtM (LHsPred RdrName)
510 = do { (head, tys') <- split_ty_app ty
512 ConT tc -> do { tc' <- tconName tc; returnL $ HsClassP tc' tys' }
513 VarT tv -> do { tv' <- tName tv; returnL $ HsClassP tv' tys' }
514 _ -> failWith (ptext (sLit "Malformed predicate") <+> text (TH.pprint ty)) }
516 cvtType :: TH.Type -> CvtM (LHsType RdrName)
517 cvtType ty = do { (head_ty, tys') <- split_ty_app ty
519 TupleT n | length tys' == n -- Saturated
520 -> if n==1 then return (head tys') -- Singleton tuples treated
521 -- like nothing (ie just parens)
522 else returnL (HsTupleTy Boxed tys')
523 | n == 1 -> failWith (ptext (sLit "Illegal 1-tuple type constructor"))
524 | otherwise -> mk_apps (HsTyVar (getRdrName (tupleTyCon Boxed n))) tys'
525 ArrowT | [x',y'] <- tys' -> returnL (HsFunTy x' y')
526 ListT | [x'] <- tys' -> returnL (HsListTy x')
527 VarT nm -> do { nm' <- tName nm; mk_apps (HsTyVar nm') tys' }
528 ConT nm -> do { nm' <- tconName nm; mk_apps (HsTyVar nm') tys' }
530 ForallT tvs cxt ty | null tys' -> do { tvs' <- cvtTvs tvs
531 ; cxt' <- cvtContext cxt
533 ; returnL $ mkExplicitHsForAllTy tvs' cxt' ty' }
534 _ -> failWith (ptext (sLit "Malformed type") <+> text (show ty))
537 mk_apps head_ty [] = returnL head_ty
538 mk_apps head_ty (ty:tys) = do { head_ty' <- returnL head_ty
539 ; mk_apps (HsAppTy head_ty' ty) tys }
541 split_ty_app :: TH.Type -> CvtM (TH.Type, [LHsType RdrName])
542 split_ty_app ty = go ty []
544 go (AppT f a) as' = do { a' <- cvtType a; go f (a':as') }
545 go f as = return (f,as)
547 -----------------------------------------------------------
550 -----------------------------------------------------------
551 -- some useful things
553 overloadedLit :: Lit -> Bool
554 -- True for literals that Haskell treats as overloaded
555 overloadedLit (IntegerL _) = True
556 overloadedLit (RationalL _) = True
557 overloadedLit _ = False
560 void = placeHolderType
562 --------------------------------------------------------------------
563 -- Turning Name back into RdrName
564 --------------------------------------------------------------------
567 vNameL, cNameL, tconNameL :: TH.Name -> CvtM (Located RdrName)
568 vName, cName, tName, tconName :: TH.Name -> CvtM RdrName
570 vNameL n = wrapL (vName n)
571 vName n = cvtName OccName.varName n
573 -- Constructor function names; this is Haskell source, hence srcDataName
574 cNameL n = wrapL (cName n)
575 cName n = cvtName OccName.dataName n
577 -- Type variable names
578 tName n = cvtName OccName.tvName n
580 -- Type Constructor names
581 tconNameL n = wrapL (tconName n)
582 tconName n = cvtName OccName.tcClsName n
584 cvtName :: OccName.NameSpace -> TH.Name -> CvtM RdrName
585 cvtName ctxt_ns (TH.Name occ flavour)
586 | not (okOcc ctxt_ns occ_str) = failWith (badOcc ctxt_ns occ_str)
587 | otherwise = force (thRdrName ctxt_ns occ_str flavour)
589 occ_str = TH.occString occ
591 okOcc :: OccName.NameSpace -> String -> Bool
594 | OccName.isVarName ns = startsVarId c || startsVarSym c
595 | otherwise = startsConId c || startsConSym c || str == "[]"
597 badOcc :: OccName.NameSpace -> String -> SDoc
599 = ptext (sLit "Illegal") <+> pprNameSpace ctxt_ns
600 <+> ptext (sLit "name:") <+> quotes (text occ)
602 thRdrName :: OccName.NameSpace -> String -> TH.NameFlavour -> RdrName
603 -- This turns a Name into a RdrName
604 -- The passed-in name space tells what the context is expecting;
605 -- use it unless the TH name knows what name-space it comes
606 -- from, in which case use the latter
608 -- ToDo: we may generate silly RdrNames, by passing a name space
609 -- that doesn't match the string, like VarName ":+",
610 -- which will give confusing error messages later
612 -- The strict applications ensure that any buried exceptions get forced
613 thRdrName _ occ (TH.NameG th_ns pkg mod) = (mkOrig $! (mkModule (mk_pkg pkg) (mk_mod mod))) $! (mk_occ (mk_ghc_ns th_ns) occ)
614 thRdrName ctxt_ns occ (TH.NameL uniq) = nameRdrName $! (((Name.mkInternalName $! (mk_uniq uniq)) $! (mk_occ ctxt_ns occ)) noSrcSpan)
615 thRdrName ctxt_ns occ (TH.NameQ mod) = (mkRdrQual $! (mk_mod mod)) $! (mk_occ ctxt_ns occ)
616 thRdrName ctxt_ns occ (TH.NameU uniq) = mkRdrUnqual $! (mk_uniq_occ ctxt_ns occ uniq)
617 thRdrName ctxt_ns occ TH.NameS
618 | Just name <- isBuiltInOcc ctxt_ns occ = nameRdrName $! name
619 | otherwise = mkRdrUnqual $! (mk_occ ctxt_ns occ)
621 isBuiltInOcc :: OccName.NameSpace -> String -> Maybe Name.Name
622 -- Built in syntax isn't "in scope" so an Unqual RdrName won't do
623 -- We must generate an Exact name, just as the parser does
624 isBuiltInOcc ctxt_ns occ
626 ":" -> Just (Name.getName consDataCon)
627 "[]" -> Just (Name.getName nilDataCon)
628 "()" -> Just (tup_name 0)
629 '(' : ',' : rest -> go_tuple 2 rest
632 go_tuple n ")" = Just (tup_name n)
633 go_tuple n (',' : rest) = go_tuple (n+1) rest
634 go_tuple _ _ = Nothing
637 | OccName.isTcClsName ctxt_ns = Name.getName (tupleTyCon Boxed n)
638 | otherwise = Name.getName (tupleCon Boxed n)
640 mk_uniq_occ :: OccName.NameSpace -> String -> Int# -> OccName.OccName
641 mk_uniq_occ ns occ uniq
642 = OccName.mkOccName ns (occ ++ '[' : shows (mk_uniq uniq) "]")
643 -- The idea here is to make a name that
644 -- a) the user could not possibly write, and
645 -- b) cannot clash with another NameU
646 -- Previously I generated an Exact RdrName with mkInternalName.
647 -- This works fine for local binders, but does not work at all for
648 -- top-level binders, which must have External Names, since they are
649 -- rapidly baked into data constructors and the like. Baling out
650 -- and generating an unqualified RdrName here is the simple solution
652 -- The packing and unpacking is rather turgid :-(
653 mk_occ :: OccName.NameSpace -> String -> OccName.OccName
654 mk_occ ns occ = OccName.mkOccNameFS ns (mkFastString occ)
656 mk_ghc_ns :: TH.NameSpace -> OccName.NameSpace
657 mk_ghc_ns TH.DataName = OccName.dataName
658 mk_ghc_ns TH.TcClsName = OccName.tcClsName
659 mk_ghc_ns TH.VarName = OccName.varName
661 mk_mod :: TH.ModName -> ModuleName
662 mk_mod mod = mkModuleName (TH.modString mod)
664 mk_pkg :: TH.ModName -> PackageId
665 mk_pkg pkg = stringToPackageId (TH.pkgString pkg)
667 mk_uniq :: Int# -> Unique
668 mk_uniq u = mkUniqueGrimily (I# u)