2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcSplice]{Template Haskell splices}
7 module TcSplice( tcSpliceExpr, tcSpliceDecls, tcBracket ) where
9 #include "HsVersions.h"
11 import HscMain ( compileExpr )
12 import TcRnDriver ( tcTopSrcDecls )
13 -- These imports are the reason that TcSplice
14 -- is very high up the module hierarchy
16 import qualified Language.Haskell.TH as TH
17 -- THSyntax gives access to internal functions and data types
18 import qualified Language.Haskell.TH.Syntax as TH
20 import HsSyn ( HsBracket(..), HsExpr(..), HsSplice(..), LHsExpr, LHsDecl,
22 import Convert ( convertToHsExpr, convertToHsDecls, convertToHsType, thRdrName )
23 import RnExpr ( rnLExpr )
24 import RnEnv ( lookupFixityRn, lookupSrcOcc_maybe, lookupImportedName )
25 import RdrName ( RdrName, lookupLocalRdrEnv, isSrcRdrName )
26 import RnTypes ( rnLHsType )
27 import TcExpr ( tcMonoExpr )
28 import TcHsSyn ( mkHsDictLet, zonkTopLExpr )
29 import TcSimplify ( tcSimplifyTop, tcSimplifyBracket )
30 import TcUnify ( boxyUnify, unBox )
31 import TcType ( TcType, TcKind, BoxyRhoType, liftedTypeKind, mkAppTy, tcSplitSigmaTy )
32 import TcEnv ( spliceOK, tcMetaTy, bracketOK )
33 import TcMType ( newFlexiTyVarTy, newKindVar, UserTypeCtxt(ExprSigCtxt), zonkTcType )
34 import TcHsType ( tcHsSigType, kcHsType )
35 import TcIface ( tcImportDecl )
36 import TypeRep ( Type(..), PredType(..), TyThing(..) ) -- For reification
37 import PrelNames ( thFAKE )
38 import Name ( Name, NamedThing(..), nameOccName, nameModule, isExternalName,
40 import NameEnv ( lookupNameEnv )
41 import HscTypes ( lookupType, ExternalPackageState(..), emptyModDetails )
43 import Var ( Id, TyVar, idType )
44 import Module ( moduleName, moduleNameString, modulePackageId )
46 import IfaceEnv ( lookupOrig )
47 import Class ( Class, classExtraBigSig )
48 import TyCon ( TyCon, tyConTyVars, synTyConDefn,
49 isSynTyCon, isNewTyCon, tyConDataCons, isPrimTyCon, isFunTyCon,
50 tyConArity, tyConStupidTheta, isUnLiftedTyCon )
51 import DataCon ( DataCon, dataConTyCon, dataConOrigArgTys, dataConStrictMarks,
52 dataConName, dataConFieldLabels, dataConWrapId, dataConIsInfix,
54 import Id ( idName, globalIdDetails )
55 import IdInfo ( GlobalIdDetails(..) )
56 import TysWiredIn ( mkListTy )
57 import DsMeta ( expQTyConName, typeQTyConName, decTyConName, qTyConName, nameTyConName )
58 import DsExpr ( dsLExpr )
59 import DsMonad ( initDsTc )
60 import ErrUtils ( Message )
61 import SrcLoc ( SrcSpan, noLoc, unLoc, getLoc )
63 import Unique ( Unique, Uniquable(..), getKey, mkUniqueGrimily )
64 import PackageConfig ( packageIdString )
65 import BasicTypes ( StrictnessMark(..), Fixity(..), FixityDirection(..) )
66 import Panic ( showException )
67 import FastString ( LitString )
69 import GHC.Base ( unsafeCoerce#, Int#, Int(..) ) -- Should have a better home in the module hierarchy
70 import Monad ( liftM )
73 import FastString ( mkFastString )
78 %************************************************************************
80 \subsection{Main interface + stubs for the non-GHCI case
82 %************************************************************************
85 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
86 tcSpliceExpr :: HsSplice Name -> BoxyRhoType -> TcM (HsExpr TcId)
87 kcSpliceType :: HsSplice Name -> TcM (HsType Name, TcKind)
90 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
91 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
95 %************************************************************************
97 \subsection{Quoting an expression}
99 %************************************************************************
102 tcBracket :: HsBracket Name -> BoxyRhoType -> TcM (LHsExpr TcId)
103 tcBracket brack res_ty
104 = getStage `thenM` \ level ->
105 case bracketOK level of {
106 Nothing -> failWithTc (illegalBracket level) ;
109 -- Typecheck expr to make sure it is valid,
110 -- but throw away the results. We'll type check
111 -- it again when we actually use it.
113 newMutVar [] `thenM` \ pending_splices ->
114 getLIEVar `thenM` \ lie_var ->
116 setStage (Brack next_level pending_splices lie_var) (
117 getLIE (tc_bracket brack)
118 ) `thenM` \ (meta_ty, lie) ->
119 tcSimplifyBracket lie `thenM_`
121 -- Make the expected type have the right shape
122 boxyUnify meta_ty res_ty `thenM_`
124 -- Return the original expression, not the type-decorated one
125 readMutVar pending_splices `thenM` \ pendings ->
126 returnM (noLoc (HsBracketOut brack pendings))
129 tc_bracket :: HsBracket Name -> TcM TcType
131 = tcMetaTy nameTyConName -- Result type is Var (not Q-monadic)
133 tc_bracket (ExpBr expr)
134 = newFlexiTyVarTy liftedTypeKind `thenM` \ any_ty ->
135 tcMonoExpr expr any_ty `thenM_`
136 tcMetaTy expQTyConName
137 -- Result type is Expr (= Q Exp)
139 tc_bracket (TypBr typ)
140 = tcHsSigType ExprSigCtxt typ `thenM_`
141 tcMetaTy typeQTyConName
142 -- Result type is Type (= Q Typ)
144 tc_bracket (DecBr decls)
145 = do { tcTopSrcDecls emptyModDetails decls
146 -- Typecheck the declarations, dicarding the result
147 -- We'll get all that stuff later, when we splice it in
149 ; decl_ty <- tcMetaTy decTyConName
150 ; q_ty <- tcMetaTy qTyConName
151 ; return (mkAppTy q_ty (mkListTy decl_ty))
152 -- Result type is Q [Dec]
156 = failWithTc (ptext SLIT("Tempate Haskell pattern brackets are not supported yet"))
160 %************************************************************************
162 \subsection{Splicing an expression}
164 %************************************************************************
167 tcSpliceExpr (HsSplice name expr) res_ty
168 = setSrcSpan (getLoc expr) $
169 getStage `thenM` \ level ->
170 case spliceOK level of {
171 Nothing -> failWithTc (illegalSplice level) ;
175 Comp -> do { e <- tcTopSplice expr res_ty
176 ; returnM (unLoc e) } ;
177 Brack _ ps_var lie_var ->
179 -- A splice inside brackets
180 -- NB: ignore res_ty, apart from zapping it to a mono-type
181 -- e.g. [| reverse $(h 4) |]
182 -- Here (h 4) :: Q Exp
183 -- but $(h 4) :: forall a.a i.e. anything!
185 unBox res_ty `thenM_`
186 tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
187 setStage (Splice next_level) (
189 tcMonoExpr expr meta_exp_ty
192 -- Write the pending splice into the bucket
193 readMutVar ps_var `thenM` \ ps ->
194 writeMutVar ps_var ((name,expr') : ps) `thenM_`
196 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
199 -- tcTopSplice used to have this:
200 -- Note that we do not decrement the level (to -1) before
201 -- typechecking the expression. For example:
202 -- f x = $( ...$(g 3) ... )
203 -- The recursive call to tcMonoExpr will simply expand the
204 -- inner escape before dealing with the outer one
206 tcTopSplice :: LHsExpr Name -> BoxyRhoType -> TcM (LHsExpr Id)
207 tcTopSplice expr res_ty
208 = tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
210 -- Typecheck the expression
211 tcTopSpliceExpr expr meta_exp_ty `thenM` \ zonked_q_expr ->
213 -- Run the expression
214 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
215 runMetaE convertToHsExpr zonked_q_expr `thenM` \ expr2 ->
217 traceTc (text "Got result" <+> ppr expr2) `thenM_`
219 showSplice "expression"
220 zonked_q_expr (ppr expr2) `thenM_`
222 -- Rename it, but bale out if there are errors
223 -- otherwise the type checker just gives more spurious errors
224 checkNoErrs (rnLExpr expr2) `thenM` \ (exp3, fvs) ->
226 tcMonoExpr exp3 res_ty
229 tcTopSpliceExpr :: LHsExpr Name -> TcType -> TcM (LHsExpr Id)
230 -- Type check an expression that is the body of a top-level splice
231 -- (the caller will compile and run it)
232 tcTopSpliceExpr expr meta_ty
233 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
234 -- if the type checker fails!
236 setStage topSpliceStage $ do
239 do { recordThUse -- Record that TH is used (for pkg depdendency)
241 -- Typecheck the expression
242 ; (expr', lie) <- getLIE (tcMonoExpr expr meta_ty)
244 -- Solve the constraints
245 ; const_binds <- tcSimplifyTop lie
248 ; zonkTopLExpr (mkHsDictLet const_binds expr') }
252 %************************************************************************
256 %************************************************************************
258 Very like splicing an expression, but we don't yet share code.
261 kcSpliceType (HsSplice name hs_expr)
262 = setSrcSpan (getLoc hs_expr) $ do
264 ; case spliceOK level of {
265 Nothing -> failWithTc (illegalSplice level) ;
266 Just next_level -> do
269 Comp -> do { (t,k) <- kcTopSpliceType hs_expr
270 ; return (unLoc t, k) } ;
271 Brack _ ps_var lie_var -> do
273 { -- A splice inside brackets
274 ; meta_ty <- tcMetaTy typeQTyConName
275 ; expr' <- setStage (Splice next_level) $
277 tcMonoExpr hs_expr meta_ty
279 -- Write the pending splice into the bucket
280 ; ps <- readMutVar ps_var
281 ; writeMutVar ps_var ((name,expr') : ps)
283 -- e.g. [| Int -> $(h 4) |]
284 -- Here (h 4) :: Q Type
285 -- but $(h 4) :: forall a.a i.e. any kind
287 ; returnM (panic "kcSpliceType", kind) -- The returned type is ignored
290 kcTopSpliceType :: LHsExpr Name -> TcM (LHsType Name, TcKind)
292 = do { meta_ty <- tcMetaTy typeQTyConName
294 -- Typecheck the expression
295 ; zonked_q_expr <- tcTopSpliceExpr expr meta_ty
297 -- Run the expression
298 ; traceTc (text "About to run" <+> ppr zonked_q_expr)
299 ; hs_ty2 <- runMetaT convertToHsType zonked_q_expr
301 ; traceTc (text "Got result" <+> ppr hs_ty2)
303 ; showSplice "type" zonked_q_expr (ppr hs_ty2)
305 -- Rename it, but bale out if there are errors
306 -- otherwise the type checker just gives more spurious errors
307 ; let doc = ptext SLIT("In the spliced type") <+> ppr hs_ty2
308 ; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)
313 %************************************************************************
315 \subsection{Splicing an expression}
317 %************************************************************************
320 -- Always at top level
321 -- Type sig at top of file:
322 -- tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
324 = do { meta_dec_ty <- tcMetaTy decTyConName
325 ; meta_q_ty <- tcMetaTy qTyConName
326 ; let list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
327 ; zonked_q_expr <- tcTopSpliceExpr expr list_q
329 -- Run the expression
330 ; traceTc (text "About to run" <+> ppr zonked_q_expr)
331 ; decls <- runMetaD convertToHsDecls zonked_q_expr
333 ; traceTc (text "Got result" <+> vcat (map ppr decls))
334 ; showSplice "declarations"
336 (ppr (getLoc expr) $$ (vcat (map ppr decls)))
339 where handleErrors :: [Either a Message] -> TcM [a]
340 handleErrors [] = return []
341 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
342 handleErrors (Right m:xs) = do addErrTc m
347 %************************************************************************
349 \subsection{Running an expression}
351 %************************************************************************
354 runMetaE :: (SrcSpan -> TH.Exp -> Either Message (LHsExpr RdrName))
355 -> LHsExpr Id -- Of type (Q Exp)
356 -> TcM (LHsExpr RdrName)
359 runMetaT :: (SrcSpan -> TH.Type -> Either Message (LHsType RdrName))
360 -> LHsExpr Id -- Of type (Q Type)
361 -> TcM (LHsType RdrName)
364 runMetaD :: (SrcSpan -> [TH.Dec] -> Either Message [LHsDecl RdrName])
365 -> LHsExpr Id -- Of type Q [Dec]
366 -> TcM [LHsDecl RdrName]
369 runMeta :: (SrcSpan -> th_syn -> Either Message hs_syn)
370 -> LHsExpr Id -- Of type X
371 -> TcM hs_syn -- Of type t
374 ds_expr <- initDsTc (dsLExpr expr)
376 -- Compile and link it; might fail if linking fails
377 ; hsc_env <- getTopEnv
378 ; src_span <- getSrcSpanM
379 ; either_hval <- tryM $ ioToTcRn $
380 HscMain.compileExpr hsc_env src_span ds_expr
381 ; case either_hval of {
382 Left exn -> failWithTc (mk_msg "compile and link" exn) ;
385 { -- Coerce it to Q t, and run it
386 -- Running might fail if it throws an exception of any kind (hence tryAllM)
387 -- including, say, a pattern-match exception in the code we are running
389 -- We also do the TH -> HS syntax conversion inside the same
390 -- exception-cacthing thing so that if there are any lurking
391 -- exceptions in the data structure returned by hval, we'll
392 -- encounter them inside the try
393 either_tval <- tryAllM $ do
394 { th_syn <- TH.runQ (unsafeCoerce# hval)
395 ; case convert (getLoc expr) th_syn of
396 Left err -> do { addErrTc err; return Nothing }
397 Right hs_syn -> return (Just hs_syn) }
399 ; case either_tval of
400 Right (Just v) -> return v
401 Right Nothing -> failM -- Error already in Tc monad
402 Left exn -> failWithTc (mk_msg "run" exn) -- Exception
405 mk_msg s exn = vcat [text "Exception when trying to" <+> text s <+> text "compile-time code:",
406 nest 2 (text (Panic.showException exn)),
407 nest 2 (text "Code:" <+> ppr expr)]
410 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
413 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
414 qNewName s = do { u <- newUnique
416 ; return (TH.mkNameU s i) }
418 qReport True msg = addErr (text msg)
419 qReport False msg = addReport (text msg)
421 qCurrentModule = do { m <- getModule;
422 return (moduleNameString (moduleName m)) }
423 -- ToDo: is throwing away the package name ok here?
427 -- For qRecover, discard error messages if
428 -- the recovery action is chosen. Otherwise
429 -- we'll only fail higher up. c.f. tryTcLIE_
430 qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main
432 Just val -> do { addMessages msgs -- There might be warnings
434 Nothing -> recover -- Discard all msgs
437 qRunIO io = ioToTcRn io
441 %************************************************************************
443 \subsection{Errors and contexts}
445 %************************************************************************
448 showSplice :: String -> LHsExpr Id -> SDoc -> TcM ()
449 showSplice what before after
450 = getSrcSpanM `thenM` \ loc ->
451 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
452 nest 2 (sep [nest 2 (ppr before),
457 = ptext SLIT("Illegal bracket at level") <+> ppr level
460 = ptext SLIT("Illegal splice at level") <+> ppr level
466 %************************************************************************
470 %************************************************************************
474 reify :: TH.Name -> TcM TH.Info
476 = do { name <- lookupThName th_name
477 ; thing <- tcLookupTh name
478 -- ToDo: this tcLookup could fail, which would give a
479 -- rather unhelpful error message
480 ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
484 ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
485 ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
486 ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
488 lookupThName :: TH.Name -> TcM Name
489 lookupThName th_name@(TH.Name occ flavour)
490 = do { let rdr_name = thRdrName guessed_ns occ_str flavour
492 -- Repeat much of lookupOccRn, becase we want
493 -- to report errors in a TH-relevant way
494 ; rdr_env <- getLocalRdrEnv
495 ; case lookupLocalRdrEnv rdr_env rdr_name of
496 Just name -> return name
497 Nothing | not (isSrcRdrName rdr_name) -- Exact, Orig
498 -> lookupImportedName rdr_name
499 | otherwise -- Unqual, Qual
501 mb_name <- lookupSrcOcc_maybe rdr_name
503 Just name -> return name
504 Nothing -> failWithTc (notInScope th_name) }
507 -- guessed_ns is the name space guessed from looking at the TH name
508 guessed_ns | isLexCon (mkFastString occ_str) = OccName.dataName
509 | otherwise = OccName.varName
510 occ_str = TH.occString occ
512 tcLookupTh :: Name -> TcM TcTyThing
513 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
514 -- it gives a reify-related error message on failure, whereas in the normal
515 -- tcLookup, failure is a bug.
517 = do { (gbl_env, lcl_env) <- getEnvs
518 ; case lookupNameEnv (tcl_env lcl_env) name of {
519 Just thing -> returnM thing;
521 { if nameIsLocalOrFrom (tcg_mod gbl_env) name
522 then -- It's defined in this module
523 case lookupNameEnv (tcg_type_env gbl_env) name of
524 Just thing -> return (AGlobal thing)
525 Nothing -> failWithTc (notInEnv name)
527 else do -- It's imported
528 { (eps,hpt) <- getEpsAndHpt
530 ; case lookupType dflags hpt (eps_PTE eps) name of
531 Just thing -> return (AGlobal thing)
532 Nothing -> do { thing <- tcImportDecl name
533 ; return (AGlobal thing) }
534 -- Imported names should always be findable;
535 -- if not, we fail hard in tcImportDecl
538 notInScope :: TH.Name -> SDoc
539 notInScope th_name = quotes (text (TH.pprint th_name)) <+>
540 ptext SLIT("is not in scope at a reify")
541 -- Ugh! Rather an indirect way to display the name
543 notInEnv :: Name -> SDoc
544 notInEnv name = quotes (ppr name) <+>
545 ptext SLIT("is not in the type environment at a reify")
547 ------------------------------
548 reifyThing :: TcTyThing -> TcM TH.Info
549 -- The only reason this is monadic is for error reporting,
550 -- which in turn is mainly for the case when TH can't express
551 -- some random GHC extension
553 reifyThing (AGlobal (AnId id))
554 = do { ty <- reifyType (idType id)
555 ; fix <- reifyFixity (idName id)
556 ; let v = reifyName id
557 ; case globalIdDetails id of
558 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
559 other -> return (TH.VarI v ty Nothing fix)
562 reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc
563 reifyThing (AGlobal (AClass cls)) = reifyClass cls
564 reifyThing (AGlobal (ADataCon dc))
565 = do { let name = dataConName dc
566 ; ty <- reifyType (idType (dataConWrapId dc))
567 ; fix <- reifyFixity name
568 ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
570 reifyThing (ATcId {tct_id = id, tct_type = ty})
571 = do { ty1 <- zonkTcType ty -- Make use of all the info we have, even
572 -- though it may be incomplete
573 ; ty2 <- reifyType ty1
574 ; fix <- reifyFixity (idName id)
575 ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
577 reifyThing (ATyVar tv ty)
578 = do { ty1 <- zonkTcType ty
579 ; ty2 <- reifyType ty1
580 ; return (TH.TyVarI (reifyName tv) ty2) }
582 ------------------------------
583 reifyTyCon :: TyCon -> TcM TH.Info
585 | isFunTyCon tc = return (TH.PrimTyConI (reifyName tc) 2 False)
586 | isPrimTyCon tc = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc))
588 = do { let (tvs, rhs) = synTyConDefn tc
589 ; rhs' <- reifyType rhs
590 ; return (TH.TyConI $ TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
593 = do { cxt <- reifyCxt (tyConStupidTheta tc)
594 ; cons <- mapM reifyDataCon (tyConDataCons tc)
595 ; let name = reifyName tc
596 tvs = reifyTyVars (tyConTyVars tc)
597 deriv = [] -- Don't know about deriving
598 decl | isNewTyCon tc = TH.NewtypeD cxt name tvs (head cons) deriv
599 | otherwise = TH.DataD cxt name tvs cons deriv
600 ; return (TH.TyConI decl) }
602 reifyDataCon :: DataCon -> TcM TH.Con
604 | isVanillaDataCon dc
605 = do { arg_tys <- reifyTypes (dataConOrigArgTys dc)
606 ; let stricts = map reifyStrict (dataConStrictMarks dc)
607 fields = dataConFieldLabels dc
611 ; ASSERT( length arg_tys == length stricts )
612 if not (null fields) then
613 return (TH.RecC name (zip3 (map reifyName fields) stricts arg_tys))
615 if dataConIsInfix dc then
616 ASSERT( length arg_tys == 2 )
617 return (TH.InfixC (s1,a1) name (s2,a2))
619 return (TH.NormalC name (stricts `zip` arg_tys)) }
621 = failWithTc (ptext SLIT("Can't reify a non-Haskell-98 data constructor:")
624 ------------------------------
625 reifyClass :: Class -> TcM TH.Info
627 = do { cxt <- reifyCxt theta
628 ; ops <- mapM reify_op op_stuff
629 ; return (TH.ClassI $ TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) fds' ops) }
631 (tvs, fds, theta, _, op_stuff) = classExtraBigSig cls
632 fds' = map reifyFunDep fds
633 reify_op (op, _) = do { ty <- reifyType (idType op)
634 ; return (TH.SigD (reifyName op) ty) }
636 ------------------------------
637 reifyType :: TypeRep.Type -> TcM TH.Type
638 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
639 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
640 reifyType (NoteTy _ ty) = reifyType ty
641 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
642 reifyType (FunTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
643 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt;
644 ; tau' <- reifyType tau
645 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
647 (tvs, cxt, tau) = tcSplitSigmaTy ty
648 reifyTypes = mapM reifyType
649 reifyCxt = mapM reifyPred
651 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
652 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
654 reifyTyVars :: [TyVar] -> [TH.Name]
655 reifyTyVars = map reifyName
657 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
658 reify_tc_app tc tys = do { tys' <- reifyTypes tys
659 ; return (foldl TH.AppT (TH.ConT tc) tys') }
661 reifyPred :: TypeRep.PredType -> TcM TH.Type
662 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
663 reifyPred p@(IParam _ _) = noTH SLIT("implicit parameters") (ppr p)
666 ------------------------------
667 reifyName :: NamedThing n => n -> TH.Name
669 | isExternalName name = mk_varg pkg_str mod_str occ_str
670 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
671 -- Many of the things we reify have local bindings, and
672 -- NameL's aren't supposed to appear in binding positions, so
673 -- we use NameU. When/if we start to reify nested things, that
674 -- have free variables, we may need to generate NameL's for them.
677 mod = nameModule name
678 pkg_str = packageIdString (modulePackageId mod)
679 mod_str = moduleNameString (moduleName mod)
680 occ_str = occNameString occ
681 occ = nameOccName name
682 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
683 | OccName.isVarOcc occ = TH.mkNameG_v
684 | OccName.isTcOcc occ = TH.mkNameG_tc
685 | otherwise = pprPanic "reifyName" (ppr name)
687 ------------------------------
688 reifyFixity :: Name -> TcM TH.Fixity
690 = do { fix <- lookupFixityRn name
691 ; return (conv_fix fix) }
693 conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
694 conv_dir BasicTypes.InfixR = TH.InfixR
695 conv_dir BasicTypes.InfixL = TH.InfixL
696 conv_dir BasicTypes.InfixN = TH.InfixN
698 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
699 reifyStrict MarkedStrict = TH.IsStrict
700 reifyStrict MarkedUnboxed = TH.IsStrict
701 reifyStrict NotMarkedStrict = TH.NotStrict
703 ------------------------------
704 noTH :: LitString -> SDoc -> TcM a
705 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+>
706 ptext SLIT("in Template Haskell:"),