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