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