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