[project @ 2003-12-30 16:29:17 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcSplice.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcSplice]{Template Haskell splices}
5
6 \begin{code}
7 module TcSplice( tcSpliceExpr, tcSpliceDecls, tcBracket ) where
8
9 #include "HsVersions.h"
10
11 import HscMain          ( compileExpr )
12 import TcRnDriver       ( tcTopSrcDecls )
13         -- These imports are the reason that TcSplice 
14         -- is very high up the module hierarchy
15
16 import qualified Language.Haskell.TH.THSyntax as TH
17 import qualified Language.Haskell.TH.THLib    as TH
18 -- THSyntax gives access to internal functions and data types
19
20 import HsSyn            ( HsBracket(..), HsExpr(..), HsSplice(..), LHsExpr, LHsDecl, 
21                           HsType, LHsType )
22 import Convert          ( convertToHsExpr, convertToHsDecls, convertToHsType )
23 import RnExpr           ( rnLExpr )
24 import RnEnv            ( lookupFixityRn, lookupSrcOcc_maybe )
25 import RdrName          ( RdrName, mkRdrUnqual, lookupLocalRdrEnv )
26 import RnTypes          ( rnLHsType )
27 import TcExpr           ( tcCheckRho, tcMonoExpr )
28 import TcHsSyn          ( mkHsLet, zonkTopLExpr )
29 import TcSimplify       ( tcSimplifyTop, tcSimplifyBracket )
30 import TcUnify          ( Expected, zapExpectedTo, zapExpectedType )
31 import TcType           ( TcType, TcKind, liftedTypeKind, mkAppTy, tcSplitSigmaTy )
32 import TcEnv            ( spliceOK, tcMetaTy, bracketOK, tcLookup )
33 import TcMType          ( newTyVarTy, newKindVar, UserTypeCtxt(ExprSigCtxt), zonkTcType, zonkTcTyVar )
34 import TcHsType         ( tcHsSigType, kcHsType )
35 import TypeRep          ( Type(..), PredType(..), TyThing(..) ) -- For reification
36 import Name             ( Name, NamedThing(..), nameOccName, nameModule, isExternalName, mkInternalName )
37 import OccName
38 import Var              ( Id, TyVar, idType )
39 import Module           ( moduleUserString, mkModuleName )
40 import TcRnMonad
41 import IfaceEnv         ( lookupOrig )
42
43 import Class            ( Class, classBigSig )
44 import TyCon            ( TyCon, tyConTheta, tyConTyVars, getSynTyConDefn, isSynTyCon, isNewTyCon, tyConDataCons )
45 import DataCon          ( DataCon, dataConTyCon, dataConOrigArgTys, dataConStrictMarks, 
46                           dataConName, dataConFieldLabels, dataConWrapId )
47 import Id               ( idName, globalIdDetails )
48 import IdInfo           ( GlobalIdDetails(..) )
49 import TysWiredIn       ( mkListTy )
50 import DsMeta           ( expQTyConName, typeQTyConName, decTyConName, qTyConName, nameTyConName )
51 import ErrUtils         ( Message )
52 import SrcLoc           ( noLoc, unLoc, getLoc, noSrcLoc )
53 import Outputable
54 import Unique           ( Unique, Uniquable(..), getKey, mkUniqueGrimily )
55
56 import BasicTypes       ( StrictnessMark(..), Fixity(..), FixityDirection(..) )
57 import Panic            ( showException )
58 import FastString       ( LitString )
59
60 import GHC.Base         ( unsafeCoerce#, Int#, Int(..) )        -- Should have a better home in the module hierarchy
61 import Monad            ( liftM )
62 \end{code}
63
64
65 %************************************************************************
66 %*                                                                      *
67 \subsection{Main interface + stubs for the non-GHCI case
68 %*                                                                      *
69 %************************************************************************
70
71 \begin{code}
72 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
73 tcSpliceExpr  :: HsSplice Name -> Expected TcType -> TcM (HsExpr TcId)
74 kcSpliceType  :: HsSplice Name -> TcM (HsType Name, TcKind)
75
76 #ifndef GHCI
77 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
78 tcSpliceDecls e     = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
79 #else
80 \end{code}
81
82 %************************************************************************
83 %*                                                                      *
84 \subsection{Quoting an expression}
85 %*                                                                      *
86 %************************************************************************
87
88 \begin{code}
89 tcBracket :: HsBracket Name -> Expected TcType -> TcM (LHsExpr Id)
90 tcBracket brack res_ty
91   = getStage                            `thenM` \ level ->
92     case bracketOK level of {
93         Nothing         -> failWithTc (illegalBracket level) ;
94         Just next_level ->
95
96         -- Typecheck expr to make sure it is valid,
97         -- but throw away the results.  We'll type check
98         -- it again when we actually use it.
99     newMutVar []                        `thenM` \ pending_splices ->
100     getLIEVar                           `thenM` \ lie_var ->
101
102     setStage (Brack next_level pending_splices lie_var) (
103         getLIE (tc_bracket brack)
104     )                                   `thenM` \ (meta_ty, lie) ->
105     tcSimplifyBracket lie               `thenM_`  
106
107         -- Make the expected type have the right shape
108     zapExpectedTo res_ty meta_ty        `thenM_`
109
110         -- Return the original expression, not the type-decorated one
111     readMutVar pending_splices          `thenM` \ pendings ->
112     returnM (noLoc (HsBracketOut brack pendings))
113     }
114
115 tc_bracket :: HsBracket Name -> TcM TcType
116 tc_bracket (VarBr v) 
117   = tcMetaTy nameTyConName
118         -- Result type is Var (not Q-monadic)
119
120 tc_bracket (ExpBr expr) 
121   = newTyVarTy liftedTypeKind   `thenM` \ any_ty ->
122     tcCheckRho expr any_ty      `thenM_`
123     tcMetaTy expQTyConName
124         -- Result type is Expr (= Q Exp)
125
126 tc_bracket (TypBr typ) 
127   = tcHsSigType ExprSigCtxt typ         `thenM_`
128     tcMetaTy typeQTyConName
129         -- Result type is Type (= Q Typ)
130
131 tc_bracket (DecBr decls)
132   = tcTopSrcDecls decls         `thenM_`
133         -- Typecheck the declarations, dicarding the result
134         -- We'll get all that stuff later, when we splice it in
135
136     tcMetaTy decTyConName       `thenM` \ decl_ty ->
137     tcMetaTy qTyConName         `thenM` \ q_ty ->
138     returnM (mkAppTy q_ty (mkListTy decl_ty))
139         -- Result type is Q [Dec]
140 \end{code}
141
142
143 %************************************************************************
144 %*                                                                      *
145 \subsection{Splicing an expression}
146 %*                                                                      *
147 %************************************************************************
148
149 \begin{code}
150 tcSpliceExpr (HsSplice name expr) res_ty
151   = addSrcSpan (getLoc expr)    $
152     getStage            `thenM` \ level ->
153     case spliceOK level of {
154         Nothing         -> failWithTc (illegalSplice level) ;
155         Just next_level -> 
156
157     case level of {
158         Comp                   -> do { e <- tcTopSplice expr res_ty ;
159                                        returnM (unLoc e) };
160         Brack _ ps_var lie_var ->  
161
162         -- A splice inside brackets
163         -- NB: ignore res_ty, apart from zapping it to a mono-type
164         -- e.g.   [| reverse $(h 4) |]
165         -- Here (h 4) :: Q Exp
166         -- but $(h 4) :: forall a.a     i.e. anything!
167
168     zapExpectedType res_ty liftedTypeKind       `thenM_`
169     tcMetaTy expQTyConName                      `thenM` \ meta_exp_ty ->
170     setStage (Splice next_level) (
171         setLIEVar lie_var          $
172         tcCheckRho expr meta_exp_ty
173     )                                           `thenM` \ expr' ->
174
175         -- Write the pending splice into the bucket
176     readMutVar ps_var                           `thenM` \ ps ->
177     writeMutVar ps_var ((name,expr') : ps)      `thenM_`
178
179     returnM (panic "tcSpliceExpr")      -- The returned expression is ignored
180     }} 
181
182 -- tcTopSplice used to have this:
183 -- Note that we do not decrement the level (to -1) before 
184 -- typechecking the expression.  For example:
185 --      f x = $( ...$(g 3) ... )
186 -- The recursive call to tcMonoExpr will simply expand the 
187 -- inner escape before dealing with the outer one
188
189 tcTopSplice :: LHsExpr Name -> Expected TcType -> TcM (LHsExpr Id)
190 tcTopSplice expr res_ty
191   = tcMetaTy expQTyConName              `thenM` \ meta_exp_ty ->
192
193         -- Typecheck the expression
194     tcTopSpliceExpr expr meta_exp_ty    `thenM` \ zonked_q_expr ->
195
196         -- Run the expression
197     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
198     runMetaE zonked_q_expr              `thenM` \ simple_expr ->
199   
200     let 
201         -- simple_expr :: TH.Exp
202
203         expr2 :: LHsExpr RdrName
204         expr2 = convertToHsExpr simple_expr 
205     in
206     traceTc (text "Got result" <+> ppr expr2)   `thenM_`
207
208     showSplice "expression" 
209                zonked_q_expr (ppr expr2)        `thenM_`
210
211         -- Rename it, but bale out if there are errors
212         -- otherwise the type checker just gives more spurious errors
213     checkNoErrs (rnLExpr expr2)                 `thenM` \ (exp3, fvs) ->
214
215     tcMonoExpr exp3 res_ty
216
217
218 tcTopSpliceExpr :: LHsExpr Name -> TcType -> TcM (LHsExpr Id)
219 -- Type check an expression that is the body of a top-level splice
220 --   (the caller will compile and run it)
221 tcTopSpliceExpr expr meta_ty
222   = checkNoErrs $       -- checkNoErrs: must not try to run the thing
223                         --              if the type checker fails!
224
225     setStage topSpliceStage $
226
227         -- Typecheck the expression
228     getLIE (tcCheckRho expr meta_ty)    `thenM` \ (expr', lie) ->
229
230         -- Solve the constraints
231     tcSimplifyTop lie                   `thenM` \ const_binds ->
232         
233         -- And zonk it
234     zonkTopLExpr (mkHsLet const_binds expr')
235 \end{code}
236
237
238 %************************************************************************
239 %*                                                                      *
240                 Splicing a type
241 %*                                                                      *
242 %************************************************************************
243
244 Very like splicing an expression, but we don't yet share code.
245
246 \begin{code}
247 kcSpliceType (HsSplice name hs_expr)
248   = addSrcSpan (getLoc hs_expr) $ do    
249         { level <- getStage
250         ; case spliceOK level of {
251                 Nothing         -> failWithTc (illegalSplice level) ;
252                 Just next_level -> do 
253
254         { case level of {
255                 Comp                   -> do { (t,k) <- kcTopSpliceType hs_expr 
256                                              ; return (unLoc t, k) } ;
257                 Brack _ ps_var lie_var -> do
258
259         {       -- A splice inside brackets
260         ; meta_ty <- tcMetaTy typeQTyConName
261         ; expr' <- setStage (Splice next_level) $
262                    setLIEVar lie_var            $
263                    tcCheckRho hs_expr meta_ty
264
265                 -- Write the pending splice into the bucket
266         ; ps <- readMutVar ps_var
267         ; writeMutVar ps_var ((name,expr') : ps)
268
269         -- e.g.   [| Int -> $(h 4) |]
270         -- Here (h 4) :: Q Type
271         -- but $(h 4) :: forall a.a     i.e. any kind
272         ; kind <- newKindVar
273         ; returnM (panic "kcSpliceType", kind)  -- The returned type is ignored
274     }}}}}
275
276 kcTopSpliceType :: LHsExpr Name -> TcM (LHsType Name, TcKind)
277 kcTopSpliceType expr
278   = do  { meta_ty <- tcMetaTy typeQTyConName
279
280         -- Typecheck the expression
281         ; zonked_q_expr <- tcTopSpliceExpr expr meta_ty
282
283         -- Run the expression
284         ; traceTc (text "About to run" <+> ppr zonked_q_expr)
285         ; simple_ty <- runMetaT zonked_q_expr
286   
287         ; let   -- simple_ty :: TH.Type
288                 hs_ty2 :: LHsType RdrName
289                 hs_ty2 = convertToHsType simple_ty
290          
291         ; traceTc (text "Got result" <+> ppr hs_ty2)
292
293         ; showSplice "type" zonked_q_expr (ppr hs_ty2)
294
295         -- Rename it, but bale out if there are errors
296         -- otherwise the type checker just gives more spurious errors
297         ; let doc = ptext SLIT("In the spliced type") <+> ppr hs_ty2
298         ; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)
299
300         ; kcHsType hs_ty3 }
301 \end{code}
302
303 %************************************************************************
304 %*                                                                      *
305 \subsection{Splicing an expression}
306 %*                                                                      *
307 %************************************************************************
308
309 \begin{code}
310 -- Always at top level
311 tcSpliceDecls expr
312   = do  { meta_dec_ty <- tcMetaTy decTyConName
313         ; meta_q_ty <- tcMetaTy qTyConName
314         ; let list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
315         ; zonked_q_expr <- tcTopSpliceExpr expr list_q
316
317                 -- Run the expression
318         ; traceTc (text "About to run" <+> ppr zonked_q_expr)
319         ; simple_expr <- runMetaD zonked_q_expr
320
321             -- simple_expr :: [TH.Dec]
322             -- decls :: [RdrNameHsDecl]
323         ; decls <- handleErrors (convertToHsDecls simple_expr)
324         ; traceTc (text "Got result" <+> vcat (map ppr decls))
325         ; showSplice "declarations"
326                      zonked_q_expr (vcat (map ppr decls))
327         ; returnM decls }
328
329   where handleErrors :: [Either a Message] -> TcM [a]
330         handleErrors [] = return []
331         handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
332         handleErrors (Right m:xs) = do addErrTc m
333                                        handleErrors xs
334 \end{code}
335
336
337 %************************************************************************
338 %*                                                                      *
339 \subsection{Running an expression}
340 %*                                                                      *
341 %************************************************************************
342
343 \begin{code}
344 runMetaE :: LHsExpr Id  -- Of type (Q Exp)
345          -> TcM TH.Exp  -- Of type Exp
346 runMetaE e = runMeta e
347
348 runMetaT :: LHsExpr Id          -- Of type (Q Type)
349          -> TcM TH.Type         -- Of type Type
350 runMetaT e = runMeta e
351
352 runMetaD :: LHsExpr Id          -- Of type Q [Dec]
353          -> TcM [TH.Dec]        -- Of type [Dec]
354 runMetaD e = runMeta e
355
356 runMeta :: LHsExpr Id   -- Of type X
357         -> TcM t                -- Of type t
358 runMeta expr
359   = do  { hsc_env <- getTopEnv
360         ; tcg_env <- getGblEnv
361         ; this_mod <- getModule
362         ; let type_env = tcg_type_env tcg_env
363               rdr_env  = tcg_rdr_env tcg_env
364         -- Wrap the compile-and-run in an exception-catcher
365         -- Compiling might fail if linking fails
366         -- Running might fail if it throws an exception
367         ; either_tval <- tryM $ do
368                 {       -- Compile it
369                   hval <- ioToTcRn (HscMain.compileExpr 
370                                       hsc_env this_mod 
371                                       rdr_env type_env expr)
372                         -- Coerce it to Q t, and run it
373                 ; TH.runQ (unsafeCoerce# hval) }
374
375         ; case either_tval of
376               Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:", 
377                                             nest 4 (vcat [text "Code:" <+> ppr expr,
378                                                       text ("Exn: " ++ Panic.showException exn)])])
379               Right v  -> returnM v }
380 \end{code}
381
382 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
383
384 \begin{code}
385 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
386   qNewName s = do  { u <- newUnique 
387                   ; let i = getKey u
388                   ; return (TH.mkNameU s i) }
389
390   qReport True msg  = addErr (text msg)
391   qReport False msg = addReport (text msg)
392
393   qCurrentModule = do { m <- getModule; return (moduleUserString m) }
394   qReify v = reify v
395   qRecover = recoverM
396
397   qRunIO io = ioToTcRn io
398 \end{code}
399
400
401 %************************************************************************
402 %*                                                                      *
403 \subsection{Errors and contexts}
404 %*                                                                      *
405 %************************************************************************
406
407 \begin{code}
408 showSplice :: String -> LHsExpr Id -> SDoc -> TcM ()
409 showSplice what before after
410   = getSrcSpanM         `thenM` \ loc ->
411     traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what, 
412                        nest 2 (sep [nest 2 (ppr before),
413                                     text "======>",
414                                     nest 2 after])])
415
416 illegalBracket level
417   = ptext SLIT("Illegal bracket at level") <+> ppr level
418
419 illegalSplice level
420   = ptext SLIT("Illegal splice at level") <+> ppr level
421
422 #endif  /* GHCI */
423 \end{code}
424
425
426 %************************************************************************
427 %*                                                                      *
428                         Reification
429 %*                                                                      *
430 %************************************************************************
431
432
433 \begin{code}
434 reify :: TH.Name -> TcM TH.Info
435 reify th_name
436   = do  { name <- lookupThName th_name
437         ; thing <- tcLookup name
438                 -- ToDo: this tcLookup could fail, which would give a
439                 --       rather unhelpful error message
440         ; reifyThing thing
441     }
442
443 lookupThName :: TH.Name -> TcM Name
444 lookupThName (TH.Name occ (TH.NameG th_ns mod))
445   = lookupOrig (mkModuleName (TH.modString mod))
446                (OccName.mkOccName ghc_ns (TH.occString occ))
447   where
448     ghc_ns = case th_ns of
449                 TH.DataName  -> dataName
450                 TH.TcClsName -> tcClsName
451                 TH.VarName   -> varName
452
453 lookupThName th_name@(TH.Name occ TH.NameS) 
454   =  do { let rdr_name = mkRdrUnqual (OccName.mkOccFS ns occ_fs)
455         ; rdr_env <- getLocalRdrEnv
456         ; case lookupLocalRdrEnv rdr_env rdr_name of
457                 Just name -> return name
458                 Nothing   -> do
459         { mb_name <- lookupSrcOcc_maybe rdr_name
460         ; case mb_name of
461             Just name -> return name ;
462             Nothing   -> failWithTc (notInScope th_name)
463         }}
464   where
465     ns | isLexCon occ_fs = OccName.dataName
466        | otherwise       = OccName.varName
467     occ_fs = mkFastString (TH.occString occ)
468
469 lookupThName (TH.Name occ (TH.NameU uniq)) 
470   = return (mkInternalName (mk_uniq uniq) (OccName.mkOccFS bogus_ns occ_fs) noSrcLoc)
471   where
472     occ_fs = mkFastString (TH.occString occ)
473     bogus_ns = OccName.varName  -- Not yet recorded in the TH name
474                                 -- but only the unique matters
475
476 mk_uniq :: Int# -> Unique
477 mk_uniq u = mkUniqueGrimily (I# u)
478
479 notInScope :: TH.Name -> SDoc
480 notInScope th_name = quotes (text (show (TH.pprName th_name))) <+> 
481                      ptext SLIT("is not in scope at a reify")
482         -- Ugh! Rather an indirect way to display the name
483
484 ------------------------------
485 reifyThing :: TcTyThing -> TcM TH.Info
486 -- The only reason this is monadic is for error reporting,
487 -- which in turn is mainly for the case when TH can't express
488 -- some random GHC extension
489
490 reifyThing (AGlobal (AnId id))
491   = do  { ty <- reifyType (idType id)
492         ; fix <- reifyFixity (idName id)
493         ; let v = reifyName id
494         ; case globalIdDetails id of
495             ClassOpId cls    -> return (TH.ClassOpI v ty (reifyName cls) fix)
496             other            -> return (TH.VarI     v ty Nothing fix)
497     }
498
499 reifyThing (AGlobal (ATyCon tc))   = do { dec <- reifyTyCon tc;  return (TH.TyConI dec) }
500 reifyThing (AGlobal (AClass cls))  = do { dec <- reifyClass cls; return (TH.ClassI dec) }
501 reifyThing (AGlobal (ADataCon dc))
502   = do  { let name = dataConName dc
503         ; ty <- reifyType (idType (dataConWrapId dc))
504         ; fix <- reifyFixity name
505         ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
506
507 reifyThing (ATcId id _ _) 
508   = do  { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
509                                         -- though it may be incomplete
510         ; ty2 <- reifyType ty1
511         ; fix <- reifyFixity (idName id)
512         ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
513
514 reifyThing (ATyVar tv) 
515   = do  { ty1 <- zonkTcTyVar tv
516         ; ty2 <- reifyType ty1
517         ; return (TH.TyVarI (reifyName tv) ty2) }
518
519 ------------------------------
520 reifyTyCon :: TyCon -> TcM TH.Dec
521 reifyTyCon tc
522   | isSynTyCon tc
523   = do  { let (tvs, rhs) = getSynTyConDefn tc
524         ; rhs' <- reifyType rhs
525         ; return (TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
526
527   | isNewTyCon tc
528   = do  { cxt <- reifyCxt (tyConTheta tc)
529         ; con <- reifyDataCon (head (tyConDataCons tc))
530         ; return (TH.NewtypeD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
531                               con [{- Don't know about deriving -}]) }
532
533   | otherwise   -- Algebraic
534   = do  { cxt <- reifyCxt (tyConTheta tc)
535         ; cons <- mapM reifyDataCon (tyConDataCons tc)
536         ; return (TH.DataD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
537                               cons [{- Don't know about deriving -}]) }
538
539 reifyDataCon :: DataCon -> TcM TH.Con
540 reifyDataCon dc
541   = do  { arg_tys <- reifyTypes (dataConOrigArgTys dc)
542         ; let stricts = map reifyStrict (dataConStrictMarks dc)
543               fields  = dataConFieldLabels dc
544         ; if null fields then
545              return (TH.NormalC (reifyName dc) (stricts `zip` arg_tys))
546           else
547              return (TH.RecC (reifyName dc) (zip3 (map reifyName fields) stricts arg_tys)) }
548         -- NB: we don't remember whether the constructor was declared in an infix way
549
550 ------------------------------
551 reifyClass :: Class -> TcM TH.Dec
552 reifyClass cls 
553   = do  { cxt <- reifyCxt theta
554         ; ops <- mapM reify_op op_stuff
555         ; return (TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) ops) }
556   where
557     (tvs, theta, _, op_stuff) = classBigSig cls
558     reify_op (op, _) = do { ty <- reifyType (idType op)
559                           ; return (TH.SigD (reifyName op) ty) }
560
561 ------------------------------
562 reifyType :: TypeRep.Type -> TcM TH.Type
563 reifyType (TyVarTy tv)      = return (TH.VarT (reifyName tv))
564 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
565 reifyType (NewTcApp tc tys) = reify_tc_app (reifyName tc) tys
566 reifyType (NoteTy _ ty)     = reifyType ty
567 reifyType (AppTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
568 reifyType (FunTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
569 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt; 
570                                  ; tau' <- reifyType tau 
571                                  ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
572                             where
573                                 (tvs, cxt, tau) = tcSplitSigmaTy ty
574 reifyTypes = mapM reifyType
575 reifyCxt   = mapM reifyPred
576
577 reifyTyVars :: [TyVar] -> [TH.Name]
578 reifyTyVars = map reifyName
579
580 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
581 reify_tc_app tc tys = do { tys' <- reifyTypes tys 
582                          ; return (foldl TH.AppT (TH.ConT tc) tys') }
583
584 reifyPred :: TypeRep.PredType -> TcM TH.Type
585 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
586 reifyPred p@(IParam _ _)   = noTH SLIT("implicit parameters") (ppr p)
587
588
589 ------------------------------
590 reifyName :: NamedThing n => n -> TH.Name
591 reifyName thing
592   | isExternalName name = mk_varg mod occ_str
593   | otherwise           = TH.mkNameU occ_str (getKey (getUnique name))
594   where
595     name    = getName thing
596     mod     = moduleUserString (nameModule name)
597     occ_str = occNameUserString occ
598     occ     = nameOccName name
599     mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
600             | OccName.isVarOcc  occ = TH.mkNameG_v
601             | OccName.isTcOcc   occ = TH.mkNameG_tc
602             | otherwise             = pprPanic "reifyName" (ppr name)
603
604 ------------------------------
605 reifyFixity :: Name -> TcM TH.Fixity
606 reifyFixity name
607   = do  { fix <- lookupFixityRn name
608         ; return (conv_fix fix) }
609     where
610       conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
611       conv_dir BasicTypes.InfixR = TH.InfixR
612       conv_dir BasicTypes.InfixL = TH.InfixL
613       conv_dir BasicTypes.InfixN = TH.InfixN
614
615 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
616 reifyStrict MarkedStrict    = TH.IsStrict
617 reifyStrict MarkedUnboxed   = TH.IsStrict
618 reifyStrict NotMarkedStrict = TH.NotStrict
619
620 ------------------------------
621 noTH :: LitString -> SDoc -> TcM a
622 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+> 
623                                 ptext SLIT("in Template Haskell:"),
624                              nest 2 d])
625 \end{code}