8ee43f5add75e7c0b4ec60a776db4325ce0d46c8
[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
9 \begin{code}
10 {-# OPTIONS -fno-warn-unused-imports -fno-warn-unused-binds #-}
11 -- The above warning supression flag is a temporary kludge.
12 -- While working on this module you are encouraged to remove it and fix
13 -- any warnings in the module. See
14 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 -- for details
16
17 module TcSplice( kcSpliceType, tcSpliceExpr, tcSpliceDecls, tcBracket,
18                  lookupThName_maybe,
19                  runQuasiQuoteExpr, runQuasiQuotePat, 
20                  runQuasiQuoteDecl, runQuasiQuoteType,
21                  runAnnotation ) where
22
23 #include "HsVersions.h"
24
25 import HscMain
26 import TcRnDriver
27         -- These imports are the reason that TcSplice 
28         -- is very high up the module hierarchy
29
30 import HsSyn
31 import Convert
32 import RnExpr
33 import RnEnv
34 import RdrName
35 import RnTypes
36 import TcPat
37 import TcExpr
38 import TcHsSyn
39 import TcSimplify
40 import TcUnify
41 import TcType
42 import TcEnv
43 import TcMType
44 import TcHsType
45 import TcIface
46 import TypeRep
47 import Name
48 import NameEnv
49 import PrelNames
50 import HscTypes
51 import OccName
52 import Var
53 import Module
54 import Annotations
55 import TcRnMonad
56 import Class
57 import Inst
58 import TyCon
59 import DataCon
60 import Id
61 import IdInfo
62 import TysWiredIn
63 import DsMeta
64 import DsExpr
65 import DsMonad hiding (Splice)
66 import Serialized
67 import ErrUtils
68 import SrcLoc
69 import Outputable
70 import Unique
71 import Data.Maybe
72 import BasicTypes
73 import Panic
74 import FastString
75 import Exception
76
77 import qualified Language.Haskell.TH as TH
78 -- THSyntax gives access to internal functions and data types
79 import qualified Language.Haskell.TH.Syntax as TH
80
81 #ifdef GHCI
82 -- Because GHC.Desugar might not be in the base library of the bootstrapping compiler
83 import GHC.Desugar      ( AnnotationWrapper(..) )
84 #endif
85
86 import GHC.Exts         ( unsafeCoerce#, Int#, Int(..) )
87 import System.IO.Error
88 \end{code}
89
90 Note [How top-level splices are handled]
91 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
92 Top-level splices (those not inside a [| .. |] quotation bracket) are handled
93 very straightforwardly:
94
95   1. tcTopSpliceExpr: typecheck the body e of the splice $(e)
96
97   2. runMetaT: desugar, compile, run it, and convert result back to
98      HsSyn RdrName (of the appropriate flavour, eg HsType RdrName,
99      HsExpr RdrName etc)
100
101   3. treat the result as if that's what you saw in the first place
102      e.g for HsType, rename and kind-check
103          for HsExpr, rename and type-check
104
105      (The last step is different for decls, becuase they can *only* be 
106       top-level: we return the result of step 2.)
107
108 Note [How brackets and nested splices are handled]
109 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
110 Nested splices (those inside a [| .. |] quotation bracket), are treated
111 quite differently. 
112
113   * After typechecking, the bracket [| |] carries
114
115      a) A mutable list of PendingSplice
116           type PendingSplice = (Name, LHsExpr Id)
117
118      b) The quoted expression e, *renamed*: (HsExpr Name)
119           The expression e has been typechecked, but the result of
120           that typechecking is discarded.  
121
122   * The brakcet is desugared by DsMeta.dsBracket.  It 
123
124       a) Extends the ds_meta environment with the PendingSplices
125          attached to the bracket
126
127       b) Converts the quoted (HsExpr Name) to a CoreExpr that, when
128          run, will produce a suitable TH expression/type/decl.  This
129          is why we leave the *renamed* expression attached to the bracket:
130          the quoted expression should not be decorated with all the goop
131          added by the type checker
132
133   * Each splice carries a unique Name, called a "splice point", thus
134     ${n}(e).  The name is initialised to an (Unqual "splice") when the
135     splice is created; the renamer gives it a unique.
136
137   * When the type checker type-checks a nested splice ${n}(e), it 
138         - typechecks e
139         - adds the typechecked expression (of type (HsExpr Id))
140           as a pending splice to the enclosing bracket
141         - returns something non-committal
142     Eg for [| f ${n}(g x) |], the typechecker 
143         - attaches the typechecked term (g x) to the pending splices for n
144           in the outer bracket
145         - returns a non-committal type \alpha.
146         Remember that the bracket discards the typechecked term altogether
147
148   * When DsMeta (used to desugar the body of the bracket) comes across
149     a splice, it looks up the splice's Name, n, in the ds_meta envt,
150     to find an (HsExpr Id) that should be substituted for the splice;
151     it just desugars it to get a CoreExpr (DsMeta.repSplice).
152
153 Example: 
154     Source:       f = [| Just $(g 3) |]
155       The [| |] part is a HsBracket
156
157     Typechecked:  f = [| Just ${s7}(g 3) |]{s7 = g Int 3}
158       The [| |] part is a HsBracketOut, containing *renamed* 
159         (not typechecked) expression
160       The "s7" is the "splice point"; the (g Int 3) part 
161         is a typechecked expression
162
163     Desugared:    f = do { s7 <- g Int 3
164                          ; return (ConE "Data.Maybe.Just" s7) }
165
166
167 Note [Template Haskell state diagram]
168 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169 Here are the ThStages, s, their corresponding level numbers
170 (the result of (thLevel s)), and their state transitions.  
171
172       -----------     $      ------------   $
173       |  Comp   | ---------> |  Splice  | -----|
174       |   1     |            |    0     | <----|
175       -----------            ------------
176         ^     |                ^      |
177       $ |     | [||]         $ |      | [||]
178         |     v                |      v
179    --------------          ----------------
180    | Brack Comp |          | Brack Splice |
181    |     2      |          |      1       |
182    --------------          ----------------
183
184 * Normal top-level declarations start in state Comp 
185        (which has level 1).
186   Annotations start in state Splice, since they are
187        treated very like a splice (only without a '$')
188
189 * Code compiled in state Splice (and only such code) 
190   will be *run at compile time*, with the result replacing
191   the splice
192
193 * The original paper used level -1 instead of 0, etc.
194
195 * The original paper did not allow a splice within a 
196   splice, but there is no reason not to. This is the 
197   $ transition in the top right.
198
199 Note [Template Haskell levels]
200 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
201 * Imported things are impLevel (= 0)
202
203 * In GHCi, variables bound by a previous command are treated
204   as impLevel, because we have bytecode for them.
205
206 * Variables are bound at the "current level"
207
208 * The current level starts off at outerLevel (= 1)
209
210 * The level is decremented by splicing $(..)
211                incremented by brackets [| |]
212                incremented by name-quoting 'f
213
214 When a variable is used, we compare 
215         bind:  binding level, and
216         use:   current level at usage site
217
218   Generally
219         bind > use      Always error (bound later than used)
220                         [| \x -> $(f x) |]
221                         
222         bind = use      Always OK (bound same stage as used)
223                         [| \x -> $(f [| x |]) |]
224
225         bind < use      Inside brackets, it depends
226                         Inside splice, OK
227                         Inside neither, OK
228
229   For (bind < use) inside brackets, there are three cases:
230     - Imported things   OK      f = [| map |]
231     - Top-level things  OK      g = [| f |]
232     - Non-top-level     Only if there is a liftable instance
233                                 h = \(x:Int) -> [| x |]
234
235 See Note [What is a top-level Id?]
236
237 Note [Quoting names]
238 ~~~~~~~~~~~~~~~~~~~~
239 A quoted name 'n is a bit like a quoted expression [| n |], except that we 
240 have no cross-stage lifting (c.f. TcExpr.thBrackId).  So, after incrementing
241 the use-level to account for the brackets, the cases are:
242
243         bind > use                      Error
244         bind = use                      OK
245         bind < use      
246                 Imported things         OK
247                 Top-level things        OK
248                 Non-top-level           Error
249
250 See Note [What is a top-level Id?] in TcEnv.  Examples:
251
252   f 'map        -- OK; also for top-level defns of this module
253
254   \x. f 'x      -- Not ok (whereas \x. f [| x |] might have been ok, by
255                 --                               cross-stage lifting
256
257   \y. [| \x. $(f 'y) |] -- Not ok (same reason)
258
259   [| \x. $(f 'x) |]     -- OK
260
261
262 Note [What is a top-level Id?]
263 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
264 In the level-control criteria above, we need to know what a "top level Id" is.
265 There are three kinds:
266   * Imported from another module                (GlobalId, ExternalName)
267   * Bound at the top level of this module       (ExternalName)
268   * In GHCi, bound by a previous stmt           (GlobalId)
269 It's strange that there is no one criterion tht picks out all three, but that's
270 how it is right now.  (The obvious thing is to give an ExternalName to GHCi Ids 
271 bound in an earlier Stmt, but what module would you choose?  See 
272 Note [Interactively-bound Ids in GHCi] in TcRnDriver.)
273
274 The predicate we use is TcEnv.thTopLevelId.
275
276
277 %************************************************************************
278 %*                                                                      *
279 \subsection{Main interface + stubs for the non-GHCI case
280 %*                                                                      *
281 %************************************************************************
282
283 \begin{code}
284 tcBracket     :: HsBracket Name -> BoxyRhoType -> TcM (LHsExpr TcId)
285 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
286 tcSpliceExpr  :: HsSplice Name -> BoxyRhoType -> TcM (HsExpr TcId)
287 kcSpliceType  :: HsSplice Name -> TcM (HsType Name, TcKind)
288         -- None of these functions add constraints to the LIE
289
290 lookupThName_maybe :: TH.Name -> TcM (Maybe Name)
291
292 runQuasiQuoteExpr :: HsQuasiQuote RdrName -> RnM (LHsExpr RdrName)
293 runQuasiQuotePat  :: HsQuasiQuote RdrName -> RnM (LPat RdrName)
294 runQuasiQuoteType :: HsQuasiQuote RdrName -> RnM (LHsType RdrName)
295 runQuasiQuoteDecl :: HsQuasiQuote RdrName -> RnM [LHsDecl RdrName]
296
297 runAnnotation     :: CoreAnnTarget -> LHsExpr Name -> TcM Annotation
298
299 #ifndef GHCI
300 tcBracket     x _ = pprPanic "Cant do tcBracket without GHCi"     (ppr x)
301 tcSpliceExpr  e   = pprPanic "Cant do tcSpliceExpr without GHCi"  (ppr e)
302 tcSpliceDecls x   = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr x)
303 kcSpliceType  x   = pprPanic "Cant do kcSpliceType without GHCi"  (ppr x)
304
305 lookupThName_maybe n = pprPanic "Cant do lookupThName_maybe without GHCi" (ppr n)
306
307 runQuasiQuoteExpr q = pprPanic "Cant do runQuasiQuoteExpr without GHCi" (ppr q)
308 runQuasiQuotePat  q = pprPanic "Cant do runQuasiQuotePat without GHCi" (ppr q)
309 runQuasiQuoteType q = pprPanic "Cant do runQuasiQuoteType without GHCi" (ppr q)
310 runQuasiQuoteDecl q = pprPanic "Cant do runQuasiQuoteDecl without GHCi" (ppr q)
311 runAnnotation   _ q = pprPanic "Cant do runAnnotation without GHCi" (ppr q)
312 #else
313 \end{code}
314
315 %************************************************************************
316 %*                                                                      *
317 \subsection{Quoting an expression}
318 %*                                                                      *
319 %************************************************************************
320
321
322 \begin{code}
323 -- See Note [How brackets and nested splices are handled]
324 tcBracket brack res_ty 
325   = addErrCtxt (hang (ptext (sLit "In the Template Haskell quotation"))
326                    2 (ppr brack)) $
327     do {        -- Check for nested brackets
328          cur_stage <- getStage
329        ; checkTc (not (isBrackStage cur_stage)) illegalBracket 
330
331         -- Brackets are desugared to code that mentions the TH package
332        ; recordThUse
333
334         -- Typecheck expr to make sure it is valid,
335         -- but throw away the results.  We'll type check
336         -- it again when we actually use it.
337        ; pending_splices <- newMutVar []
338        ; lie_var <- getLIEVar
339
340        ; (meta_ty, lie) <- setStage (Brack cur_stage pending_splices lie_var)
341                                     (getLIE (tc_bracket cur_stage brack))
342        ; tcSimplifyBracket lie
343
344         -- Make the expected type have the right shape
345        ; _ <- boxyUnify meta_ty res_ty
346
347         -- Return the original expression, not the type-decorated one
348        ; pendings <- readMutVar pending_splices
349        ; return (noLoc (HsBracketOut brack pendings)) }
350
351 tc_bracket :: ThStage -> HsBracket Name -> TcM TcType
352 tc_bracket outer_stage (VarBr name)     -- Note [Quoting names]
353   = do  { thing <- tcLookup name
354         ; case thing of
355             AGlobal _ -> return ()
356             ATcId { tct_level = bind_lvl, tct_id = id }
357                 | thTopLevelId id       -- C.f TcExpr.checkCrossStageLifting
358                 -> keepAliveTc id               
359                 | otherwise
360                 -> do { checkTc (thLevel outer_stage + 1 == bind_lvl)
361                                 (quotedNameStageErr name) }
362             _ -> pprPanic "th_bracket" (ppr name)
363
364         ; tcMetaTy nameTyConName        -- Result type is Var (not Q-monadic)
365         }
366
367 tc_bracket _ (ExpBr expr) 
368   = do  { any_ty <- newFlexiTyVarTy liftedTypeKind
369         ; _ <- tcMonoExprNC expr any_ty  -- NC for no context; tcBracket does that
370         ; tcMetaTy expQTyConName }
371         -- Result type is ExpQ (= Q Exp)
372
373 tc_bracket _ (TypBr typ) 
374   = do  { _ <- tcHsSigTypeNC ThBrackCtxt typ
375         ; tcMetaTy typeQTyConName }
376         -- Result type is Type (= Q Typ)
377
378 tc_bracket _ (DecBrG decls)
379   = do  { _ <- tcTopSrcDecls emptyModDetails decls
380                -- Typecheck the declarations, dicarding the result
381                -- We'll get all that stuff later, when we splice it in
382         ; tcMetaTy decsQTyConName } -- Result type is Q [Dec]
383
384 tc_bracket _ (PatBr pat)
385   = do  { any_ty <- newFlexiTyVarTy liftedTypeKind
386         ; _ <- tcPat ThPatQuote pat any_ty unitTy $ \_ ->
387                return ()
388         ; tcMetaTy patQTyConName }
389         -- Result type is PatQ (= Q Pat)
390
391 tc_bracket _ (DecBrL _)
392   = panic "tc_bracket: Unexpected DecBrL"
393
394 quotedNameStageErr :: Name -> SDoc
395 quotedNameStageErr v 
396   = sep [ ptext (sLit "Stage error: the non-top-level quoted name") <+> ppr (VarBr v)
397         , ptext (sLit "must be used at the same stage at which is is bound")]
398 \end{code}
399
400
401 %************************************************************************
402 %*                                                                      *
403 \subsection{Splicing an expression}
404 %*                                                                      *
405 %************************************************************************
406
407 \begin{code}
408 tcSpliceExpr (HsSplice name expr) res_ty
409   = setSrcSpan (getLoc expr)    $ do
410     { stage <- getStage
411     ; case stage of {
412         Splice -> tcTopSplice expr res_ty ;
413         Comp   -> tcTopSplice expr res_ty ;
414
415         Brack pop_stage ps_var lie_var -> do
416
417         -- See Note [How brackets and nested splices are handled]
418         -- A splice inside brackets
419         -- NB: ignore res_ty, apart from zapping it to a mono-type
420         -- e.g.   [| reverse $(h 4) |]
421         -- Here (h 4) :: Q Exp
422         -- but $(h 4) :: forall a.a     i.e. anything!
423
424      { _ <- unBox res_ty
425      ; meta_exp_ty <- tcMetaTy expQTyConName
426      ; expr' <- setStage pop_stage $
427                 setLIEVar lie_var    $
428                 tcMonoExpr expr meta_exp_ty
429
430         -- Write the pending splice into the bucket
431      ; ps <- readMutVar ps_var
432      ; writeMutVar ps_var ((name,expr') : ps)
433
434      ; return (panic "tcSpliceExpr")    -- The returned expression is ignored
435      }}}
436
437 tcTopSplice :: LHsExpr Name -> BoxyRhoType -> TcM (HsExpr Id)
438 -- Note [How top-level splices are handled]
439 tcTopSplice expr res_ty
440   = do { meta_exp_ty <- tcMetaTy expQTyConName
441
442         -- Typecheck the expression
443        ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_exp_ty)
444
445         -- Run the expression
446        ; expr2 <- runMetaE zonked_q_expr
447        ; showSplice "expression" expr (ppr expr2)
448
449         -- Rename it, but bale out if there are errors
450         -- otherwise the type checker just gives more spurious errors
451        ; addErrCtxt (spliceResultDoc expr) $ do 
452        { (exp3, _fvs) <- checkNoErrs (rnLExpr expr2)
453
454        ; exp4 <- tcMonoExpr exp3 res_ty 
455        ; return (unLoc exp4) } }
456
457 spliceResultDoc :: LHsExpr Name -> SDoc
458 spliceResultDoc expr
459   = sep [ ptext (sLit "In the result of the splice:")
460         , nest 2 (char '$' <> pprParendExpr expr)
461         , ptext (sLit "To see what the splice expanded to, use -ddump-splices")]
462
463 -------------------
464 tcTopSpliceExpr :: TcM (LHsExpr Id) -> TcM (LHsExpr Id)
465 -- Note [How top-level splices are handled]
466 -- Type check an expression that is the body of a top-level splice
467 --   (the caller will compile and run it)
468 -- Note that set the level to Splice, regardless of the original level,
469 -- before typechecking the expression.  For example:
470 --      f x = $( ...$(g 3) ... )
471 -- The recursive call to tcMonoExpr will simply expand the 
472 -- inner escape before dealing with the outer one
473
474 tcTopSpliceExpr tc_action
475   = checkNoErrs $  -- checkNoErrs: must not try to run the thing
476                    -- if the type checker fails!
477     setStage Splice $ 
478     do {    -- Typecheck the expression
479          (expr', lie) <- getLIE tc_action
480         
481         -- Solve the constraints
482         ; const_binds <- tcSimplifyTop lie
483         
484           -- Zonk it and tie the knot of dictionary bindings
485        ; zonkTopLExpr (mkHsDictLet const_binds expr') }
486 \end{code}
487
488
489 %************************************************************************
490 %*                                                                      *
491                 Splicing a type
492 %*                                                                      *
493 %************************************************************************
494
495 Very like splicing an expression, but we don't yet share code.
496
497 \begin{code}
498 kcSpliceType (HsSplice name hs_expr)
499   = setSrcSpan (getLoc hs_expr) $ do    
500     { stage <- getStage
501     ; case stage of {
502         Splice -> kcTopSpliceType hs_expr ;
503         Comp   -> kcTopSpliceType hs_expr ;
504
505         Brack pop_level ps_var lie_var -> do
506            -- See Note [How brackets and nested splices are handled]
507            -- A splice inside brackets
508     { meta_ty <- tcMetaTy typeQTyConName
509     ; expr' <- setStage pop_level $
510                setLIEVar lie_var $
511                tcMonoExpr hs_expr meta_ty
512
513         -- Write the pending splice into the bucket
514     ; ps <- readMutVar ps_var
515     ; writeMutVar ps_var ((name,expr') : ps)
516
517     -- e.g.   [| f (g :: Int -> $(h 4)) |]
518     -- Here (h 4) :: Q Type
519     -- but $(h 4) :: a  i.e. any type, of any kind
520
521     -- We return a HsSpliceTyOut, which serves to convey the kind to 
522     -- the ensuing TcHsType.dsHsType, which makes up a non-committal
523     -- type variable of a suitable kind
524     ; kind <- newKindVar
525     ; return (HsSpliceTyOut kind, kind) 
526     }}}
527
528 kcTopSpliceType :: LHsExpr Name -> TcM (HsType Name, TcKind)
529 -- Note [How top-level splices are handled]
530 kcTopSpliceType expr
531   = do  { meta_ty <- tcMetaTy typeQTyConName
532
533         -- Typecheck the expression
534         ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_ty)
535
536         -- Run the expression
537         ; hs_ty2 <- runMetaT zonked_q_expr
538         ; showSplice "type" expr (ppr hs_ty2)
539   
540         -- Rename it, but bale out if there are errors
541         -- otherwise the type checker just gives more spurious errors
542         ; addErrCtxt (spliceResultDoc expr) $ do 
543         { let doc = ptext (sLit "In the spliced type") <+> ppr hs_ty2
544         ; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)
545         ; (ty4, kind) <- kcLHsType hs_ty3
546         ; return (unLoc ty4, kind) }}
547 \end{code}
548
549 %************************************************************************
550 %*                                                                      *
551 \subsection{Splicing an expression}
552 %*                                                                      *
553 %************************************************************************
554
555 \begin{code}
556 -- Note [How top-level splices are handled]
557 -- Always at top level
558 -- Type sig at top of file:
559 --      tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
560 tcSpliceDecls expr
561   = do  { list_q <- tcMetaTy decsQTyConName     -- Q [Dec]
562         ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr list_q)
563
564                 -- Run the expression
565         ; decls <- runMetaD zonked_q_expr
566         ; showSplice "declarations" expr 
567                      (ppr (getLoc expr) $$ (vcat (map ppr decls)))
568
569         ; return decls }
570 \end{code}
571
572
573 %************************************************************************
574 %*                                                                      *
575         Annotations
576 %*                                                                      *
577 %************************************************************************
578
579 \begin{code}
580 runAnnotation target expr = do
581     -- Find the classes we want instances for in order to call toAnnotationWrapper
582     loc <- getSrcSpanM
583     data_class <- tcLookupClass dataClassName
584     to_annotation_wrapper_id <- tcLookupId toAnnotationWrapperName
585     
586     -- Check the instances we require live in another module (we want to execute it..)
587     -- and check identifiers live in other modules using TH stage checks. tcSimplifyStagedExpr
588     -- also resolves the LIE constraints to detect e.g. instance ambiguity
589     zonked_wrapped_expr' <- tcTopSpliceExpr $ 
590            do { (expr', expr_ty) <- tcInferRhoNC expr
591                 -- We manually wrap the typechecked expression in a call to toAnnotationWrapper
592                 -- By instantiating the call >here< it gets registered in the 
593                 -- LIE consulted by tcTopSpliceExpr
594                 -- and hence ensures the appropriate dictionary is bound by const_binds
595               ; wrapper <- instCall AnnOrigin [expr_ty] [mkClassPred data_class [expr_ty]]
596               ; let specialised_to_annotation_wrapper_expr  
597                       = L loc (HsWrap wrapper (HsVar to_annotation_wrapper_id))
598               ; return (L loc (HsApp specialised_to_annotation_wrapper_expr expr')) }
599
600     -- Run the appropriately wrapped expression to get the value of
601     -- the annotation and its dictionaries. The return value is of
602     -- type AnnotationWrapper by construction, so this conversion is
603     -- safe
604     flip runMetaAW zonked_wrapped_expr' $ \annotation_wrapper ->
605         case annotation_wrapper of
606             AnnotationWrapper value | let serialized = toSerialized serializeWithData value ->
607                 -- Got the value and dictionaries: build the serialized value and 
608                 -- call it a day. We ensure that we seq the entire serialized value 
609                 -- in order that any errors in the user-written code for the
610                 -- annotation are exposed at this point.  This is also why we are 
611                 -- doing all this stuff inside the context of runMeta: it has the 
612                 -- facilities to deal with user error in a meta-level expression
613                 seqSerialized serialized `seq` Annotation { 
614                     ann_target = target,
615                     ann_value = serialized
616                 }
617 \end{code}
618
619
620 %************************************************************************
621 %*                                                                      *
622         Quasi-quoting
623 %*                                                                      *
624 %************************************************************************
625
626 Note [Quasi-quote overview]
627 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
628 The GHC "quasi-quote" extension is described by Geoff Mainland's paper
629 "Why it's nice to be quoted: quasiquoting for Haskell" (Haskell
630 Workshop 2007).
631
632 Briefly, one writes
633         [p| stuff |]
634 and the arbitrary string "stuff" gets parsed by the parser 'p', whose
635 type should be Language.Haskell.TH.Quote.QuasiQuoter.  'p' must be
636 defined in another module, because we are going to run it here.  It's
637 a bit like a TH splice:
638         $(p "stuff")
639
640 However, you can do this in patterns as well as terms.  Becuase of this,
641 the splice is run by the *renamer* rather than the type checker.
642
643 %************************************************************************
644 %*                                                                      *
645 \subsubsection{Quasiquotation}
646 %*                                                                      *
647 %************************************************************************
648
649 See Note [Quasi-quote overview] in TcSplice.
650
651 \begin{code}
652 runQuasiQuote :: Outputable hs_syn
653               => HsQuasiQuote RdrName   -- Contains term of type QuasiQuoter, and the String
654               -> Name                   -- Of type QuasiQuoter -> String -> Q th_syn
655               -> Name                   -- Name of th_syn type  
656               -> MetaOps th_syn hs_syn 
657               -> RnM hs_syn
658 runQuasiQuote (HsQuasiQuote quoter q_span quote) quote_selector meta_ty meta_ops
659   = do  { quoter' <- lookupOccRn quoter
660                 -- If 'quoter' is not in scope, proceed no further
661                 -- Otherwise lookupOcc adds an error messsage and returns 
662                 -- an "unubound name", which makes the subsequent attempt to
663                 -- run the quote fail
664                 --
665                 -- We use lookupOcc rather than lookupGlobalOcc because in the
666                 -- erroneous case of \x -> [x| ...|] we get a better error message
667                 -- (stage restriction rather than out of scope).
668
669           -- Check that the quoter is not locally defined, otherwise the TH
670           -- machinery will not be able to run the quasiquote.
671         ; this_mod <- getModule
672         ; let is_local = nameIsLocalOrFrom this_mod quoter'
673         ; checkTc (not is_local) (quoteStageError quoter')
674
675         ; traceTc (text "runQQ" <+> ppr quoter <+> ppr is_local)
676
677           -- Build the expression 
678         ; let quoterExpr = L q_span $! HsVar $! quoter'
679         ; let quoteExpr = L q_span $! HsLit $! HsString quote
680         ; let expr = L q_span $
681                      HsApp (L q_span $
682                             HsApp (L q_span (HsVar quote_selector)) quoterExpr) quoteExpr
683         ; meta_exp_ty <- tcMetaTy meta_ty
684
685         -- Typecheck the expression
686         ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_exp_ty)
687
688         -- Run the expression
689         ; result <- runMetaQ meta_ops zonked_q_expr
690         ; showSplice (mt_desc meta_ops) quoteExpr (ppr result)
691
692         ; return result }
693
694 runQuasiQuoteExpr qq = runQuasiQuote qq quoteExpName  expQTyConName  exprMetaOps
695 runQuasiQuotePat  qq = runQuasiQuote qq quotePatName  patQTyConName  patMetaOps
696 runQuasiQuoteType qq = runQuasiQuote qq quoteTypeName typeQTyConName typeMetaOps
697 runQuasiQuoteDecl qq = runQuasiQuote qq quoteDecName  decsQTyConName declMetaOps
698
699 quoteStageError :: Name -> SDoc
700 quoteStageError quoter
701   = sep [ptext (sLit "GHC stage restriction:") <+> ppr quoter,
702          nest 2 (ptext (sLit "is used in a quasiquote, and must be imported, not defined locally"))]
703 \end{code}
704
705
706 %************************************************************************
707 %*                                                                      *
708 \subsection{Running an expression}
709 %*                                                                      *
710 %************************************************************************
711
712 \begin{code}
713 data MetaOps th_syn hs_syn
714   = MT { mt_desc :: String             -- Type of beast (expression, type etc)
715        , mt_show :: th_syn -> String   -- How to show the th_syn thing
716        , mt_cvt  :: SrcSpan -> th_syn -> Either Message hs_syn
717                                        -- How to convert to hs_syn
718     }
719
720 exprMetaOps :: MetaOps TH.Exp (LHsExpr RdrName)
721 exprMetaOps = MT { mt_desc = "expression", mt_show = TH.pprint, mt_cvt = convertToHsExpr }
722
723 patMetaOps :: MetaOps TH.Pat (LPat RdrName)
724 patMetaOps = MT { mt_desc = "pattern", mt_show = TH.pprint, mt_cvt = convertToPat }
725
726 typeMetaOps :: MetaOps TH.Type (LHsType RdrName)
727 typeMetaOps = MT { mt_desc = "type", mt_show = TH.pprint, mt_cvt = convertToHsType }
728
729 declMetaOps :: MetaOps [TH.Dec] [LHsDecl RdrName]
730 declMetaOps = MT { mt_desc = "declarations", mt_show = TH.pprint, mt_cvt = convertToHsDecls }
731
732 ----------------
733 runMetaAW :: Outputable output
734           => (AnnotationWrapper -> output)
735           -> LHsExpr Id         -- Of type AnnotationWrapper
736           -> TcM output
737 runMetaAW k = runMeta False (\_ -> return . Right . k)
738     -- We turn off showing the code in meta-level exceptions because doing so exposes
739     -- the toAnnotationWrapper function that we slap around the users code
740
741 -----------------
742 runMetaQ :: Outputable hs_syn 
743          => MetaOps th_syn hs_syn
744          -> LHsExpr Id
745          -> TcM hs_syn
746 runMetaQ (MT { mt_show = show_th, mt_cvt = cvt }) expr
747   = runMeta True run_and_cvt expr
748   where
749     run_and_cvt expr_span hval
750        = do { th_result <- TH.runQ hval
751             ; traceTc (text "Got TH result:" <+> text (show_th th_result))
752             ; return (cvt expr_span th_result) }
753
754 runMetaE :: LHsExpr Id          -- Of type (Q Exp)
755          -> TcM (LHsExpr RdrName)
756 runMetaE = runMetaQ exprMetaOps
757
758 runMetaT :: LHsExpr Id          -- Of type (Q Type)
759          -> TcM (LHsType RdrName)       
760 runMetaT = runMetaQ typeMetaOps
761
762 runMetaD :: LHsExpr Id          -- Of type Q [Dec]
763          -> TcM [LHsDecl RdrName]
764 runMetaD = runMetaQ declMetaOps
765
766 ---------------
767 runMeta :: (Outputable hs_syn)
768         => Bool                 -- Whether code should be printed in the exception message
769         -> (SrcSpan -> x -> TcM (Either Message hs_syn))        -- How to run x 
770         -> LHsExpr Id           -- Of type x; typically x = Q TH.Exp, or something like that
771         -> TcM hs_syn           -- Of type t
772 runMeta show_code run_and_convert expr
773   = do  { traceTc (text "About to run" <+> ppr expr)
774
775         -- Desugar
776         ; ds_expr <- initDsTc (dsLExpr expr)
777         -- Compile and link it; might fail if linking fails
778         ; hsc_env <- getTopEnv
779         ; src_span <- getSrcSpanM
780         ; either_hval <- tryM $ liftIO $
781                          HscMain.compileExpr hsc_env src_span ds_expr
782         ; case either_hval of {
783             Left exn   -> failWithTc (mk_msg "compile and link" exn) ;
784             Right hval -> do
785
786         {       -- Coerce it to Q t, and run it
787
788                 -- Running might fail if it throws an exception of any kind (hence tryAllM)
789                 -- including, say, a pattern-match exception in the code we are running
790                 --
791                 -- We also do the TH -> HS syntax conversion inside the same
792                 -- exception-cacthing thing so that if there are any lurking 
793                 -- exceptions in the data structure returned by hval, we'll
794                 -- encounter them inside the try
795                 --
796                 -- See Note [Exceptions in TH] 
797           let expr_span = getLoc expr
798         ; either_tval <- tryAllM $
799                          setSrcSpan expr_span $ -- Set the span so that qLocation can
800                                                 -- see where this splice is
801              do { mb_result <- run_and_convert expr_span (unsafeCoerce# hval)
802                 ; case mb_result of
803                     Left err     -> failWithTc err
804                     Right result -> do { traceTc (ptext (sLit "Got HsSyn result:") <+> ppr result) 
805                                        ; return $! result } }
806
807         ; case either_tval of
808             Right v -> return v
809             Left se -> case fromException se of
810                          Just IOEnvFailure -> failM -- Error already in Tc monad
811                          _ -> failWithTc (mk_msg "run" se)      -- Exception
812         }}}
813   where
814     mk_msg s exn = vcat [text "Exception when trying to" <+> text s <+> text "compile-time code:",
815                          nest 2 (text (Panic.showException exn)),
816                          if show_code then nest 2 (text "Code:" <+> ppr expr) else empty]
817 \end{code}
818
819 Note [Exceptions in TH]
820 ~~~~~~~~~~~~~~~~~~~~~~~
821 Supppose we have something like this 
822         $( f 4 )
823 where
824         f :: Int -> Q [Dec]
825         f n | n>3       = fail "Too many declarations"
826             | otherwise = ...
827
828 The 'fail' is a user-generated failure, and should be displayed as a
829 perfectly ordinary compiler error message, not a panic or anything
830 like that.  Here's how it's processed:
831
832   * 'fail' is the monad fail.  The monad instance for Q in TH.Syntax
833     effectively transforms (fail s) to 
834         qReport True s >> fail
835     where 'qReport' comes from the Quasi class and fail from its monad
836     superclass.
837
838   * The TcM monad is an instance of Quasi (see TcSplice), and it implements
839     (qReport True s) by using addErr to add an error message to the bag of errors.
840     The 'fail' in TcM raises an IOEnvFailure exception
841
842   * So, when running a splice, we catch all exceptions; then for 
843         - an IOEnvFailure exception, we assume the error is already 
844                 in the error-bag (above)
845         - other errors, we add an error to the bag
846     and then fail
847
848
849 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
850
851 \begin{code}
852 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
853   qNewName s = do { u <- newUnique 
854                   ; let i = getKey u
855                   ; return (TH.mkNameU s i) }
856
857   qReport True msg  = addErr (text msg)
858   qReport False msg = addReport (text msg) empty
859
860   qLocation = do { m <- getModule
861                  ; l <- getSrcSpanM
862                  ; return (TH.Loc { TH.loc_filename = unpackFS (srcSpanFile l)
863                                   , TH.loc_module   = moduleNameString (moduleName m)
864                                   , TH.loc_package  = packageIdString (modulePackageId m)
865                                   , TH.loc_start = (srcSpanStartLine l, srcSpanStartCol l)
866                                   , TH.loc_end = (srcSpanEndLine   l, srcSpanEndCol   l) }) }
867                 
868   qReify v = reify v
869
870         -- For qRecover, discard error messages if 
871         -- the recovery action is chosen.  Otherwise
872         -- we'll only fail higher up.  c.f. tryTcLIE_
873   qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main
874                              ; case mb_res of
875                                  Just val -> do { addMessages msgs      -- There might be warnings
876                                                 ; return val }
877                                  Nothing  -> recover                    -- Discard all msgs
878                           }
879
880   qRunIO io = liftIO io
881 \end{code}
882
883
884 %************************************************************************
885 %*                                                                      *
886 \subsection{Errors and contexts}
887 %*                                                                      *
888 %************************************************************************
889
890 \begin{code}
891 showSplice :: String -> LHsExpr Name -> SDoc -> TcM ()
892 -- Note that 'before' is *renamed* but not *typechecked*
893 -- Reason (a) less typechecking crap
894 --        (b) data constructors after type checking have been
895 --            changed to their *wrappers*, and that makes them
896 --            print always fully qualified
897 showSplice what before after
898   = do { loc <- getSrcSpanM
899        ; traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what, 
900                             nest 2 (sep [nest 2 (ppr before),
901                                          text "======>",
902                                          nest 2 after])]) }
903
904 illegalBracket :: SDoc
905 illegalBracket = ptext (sLit "Template Haskell brackets cannot be nested (without intervening splices)")
906 #endif  /* GHCI */
907 \end{code}
908
909
910 %************************************************************************
911 %*                                                                      *
912                         Reification
913 %*                                                                      *
914 %************************************************************************
915
916
917 \begin{code}
918 reify :: TH.Name -> TcM TH.Info
919 reify th_name
920   = do  { name <- lookupThName th_name
921         ; thing <- tcLookupTh name
922                 -- ToDo: this tcLookup could fail, which would give a
923                 --       rather unhelpful error message
924         ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
925         ; reifyThing thing
926     }
927   where
928     ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
929     ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
930     ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
931     ppr_ns _ = panic "reify/ppr_ns"
932
933 lookupThName :: TH.Name -> TcM Name
934 lookupThName th_name = do
935     mb_name <- lookupThName_maybe th_name
936     case mb_name of
937         Nothing   -> failWithTc (notInScope th_name)
938         Just name -> return name
939
940 lookupThName_maybe th_name
941   =  do { names <- mapMaybeM lookup (thRdrNameGuesses th_name)
942           -- Pick the first that works
943           -- E.g. reify (mkName "A") will pick the class A in preference to the data constructor A
944         ; return (listToMaybe names) }  
945   where
946     lookup rdr_name
947         = do {  -- Repeat much of lookupOccRn, becase we want
948                 -- to report errors in a TH-relevant way
949              ; rdr_env <- getLocalRdrEnv
950              ; case lookupLocalRdrEnv rdr_env rdr_name of
951                  Just name -> return (Just name)
952                  Nothing   -> lookupGlobalOccRn_maybe rdr_name }
953
954 tcLookupTh :: Name -> TcM TcTyThing
955 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
956 -- it gives a reify-related error message on failure, whereas in the normal
957 -- tcLookup, failure is a bug.
958 tcLookupTh name
959   = do  { (gbl_env, lcl_env) <- getEnvs
960         ; case lookupNameEnv (tcl_env lcl_env) name of {
961                 Just thing -> return thing;
962                 Nothing    -> do
963         { if nameIsLocalOrFrom (tcg_mod gbl_env) name
964           then  -- It's defined in this module
965               case lookupNameEnv (tcg_type_env gbl_env) name of
966                 Just thing -> return (AGlobal thing)
967                 Nothing    -> failWithTc (notInEnv name)
968          
969           else do               -- It's imported
970         { (eps,hpt) <- getEpsAndHpt
971         ; dflags <- getDOpts
972         ; case lookupType dflags hpt (eps_PTE eps) name of 
973             Just thing -> return (AGlobal thing)
974             Nothing    -> do { thing <- tcImportDecl name
975                              ; return (AGlobal thing) }
976                 -- Imported names should always be findable; 
977                 -- if not, we fail hard in tcImportDecl
978     }}}}
979
980 notInScope :: TH.Name -> SDoc
981 notInScope th_name = quotes (text (TH.pprint th_name)) <+> 
982                      ptext (sLit "is not in scope at a reify")
983         -- Ugh! Rather an indirect way to display the name
984
985 notInEnv :: Name -> SDoc
986 notInEnv name = quotes (ppr name) <+> 
987                      ptext (sLit "is not in the type environment at a reify")
988
989 ------------------------------
990 reifyThing :: TcTyThing -> TcM TH.Info
991 -- The only reason this is monadic is for error reporting,
992 -- which in turn is mainly for the case when TH can't express
993 -- some random GHC extension
994
995 reifyThing (AGlobal (AnId id))
996   = do  { ty <- reifyType (idType id)
997         ; fix <- reifyFixity (idName id)
998         ; let v = reifyName id
999         ; case idDetails id of
1000             ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
1001             _             -> return (TH.VarI     v ty Nothing fix)
1002     }
1003
1004 reifyThing (AGlobal (ATyCon tc))  = reifyTyCon tc
1005 reifyThing (AGlobal (AClass cls)) = reifyClass cls
1006 reifyThing (AGlobal (ADataCon dc))
1007   = do  { let name = dataConName dc
1008         ; ty <- reifyType (idType (dataConWrapId dc))
1009         ; fix <- reifyFixity name
1010         ; return (TH.DataConI (reifyName name) ty 
1011                               (reifyName (dataConOrigTyCon dc)) fix) 
1012         }
1013
1014 reifyThing (ATcId {tct_id = id, tct_type = ty}) 
1015   = do  { ty1 <- zonkTcType ty  -- Make use of all the info we have, even
1016                                 -- though it may be incomplete
1017         ; ty2 <- reifyType ty1
1018         ; fix <- reifyFixity (idName id)
1019         ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
1020
1021 reifyThing (ATyVar tv ty) 
1022   = do  { ty1 <- zonkTcType ty
1023         ; ty2 <- reifyType ty1
1024         ; return (TH.TyVarI (reifyName tv) ty2) }
1025
1026 reifyThing (AThing {}) = panic "reifyThing AThing"
1027
1028 ------------------------------
1029 reifyTyCon :: TyCon -> TcM TH.Info
1030 reifyTyCon tc
1031   | isFunTyCon tc  
1032   = return (TH.PrimTyConI (reifyName tc) 2                False)
1033   | isPrimTyCon tc 
1034   = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc))
1035   | isOpenTyCon tc
1036   = let flavour = reifyFamFlavour tc
1037         tvs     = tyConTyVars tc
1038         kind    = tyConKind tc
1039         kind'
1040           | isLiftedTypeKind kind = Nothing
1041           | otherwise             = Just $ reifyKind kind
1042     in
1043     return (TH.TyConI $
1044               TH.FamilyD flavour (reifyName tc) (reifyTyVars tvs) kind')
1045   | isSynTyCon tc
1046   = do { let (tvs, rhs) = synTyConDefn tc 
1047        ; rhs' <- reifyType rhs
1048        ; return (TH.TyConI $ 
1049                    TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') 
1050        }
1051
1052 reifyTyCon tc
1053   = do  { cxt <- reifyCxt (tyConStupidTheta tc)
1054         ; let tvs = tyConTyVars tc
1055         ; cons <- mapM (reifyDataCon (mkTyVarTys tvs)) (tyConDataCons tc)
1056         ; let name = reifyName tc
1057               r_tvs  = reifyTyVars tvs
1058               deriv = []        -- Don't know about deriving
1059               decl | isNewTyCon tc = TH.NewtypeD cxt name r_tvs (head cons) deriv
1060                    | otherwise     = TH.DataD    cxt name r_tvs cons        deriv
1061         ; return (TH.TyConI decl) }
1062
1063 reifyDataCon :: [Type] -> DataCon -> TcM TH.Con
1064 reifyDataCon tys dc
1065   | isVanillaDataCon dc
1066   = do  { arg_tys <- reifyTypes (dataConInstOrigArgTys dc tys)
1067         ; let stricts = map reifyStrict (dataConStrictMarks dc)
1068               fields  = dataConFieldLabels dc
1069               name    = reifyName dc
1070               [a1,a2] = arg_tys
1071               [s1,s2] = stricts
1072         ; ASSERT( length arg_tys == length stricts )
1073           if not (null fields) then
1074              return (TH.RecC name (zip3 (map reifyName fields) stricts arg_tys))
1075           else
1076           if dataConIsInfix dc then
1077              ASSERT( length arg_tys == 2 )
1078              return (TH.InfixC (s1,a1) name (s2,a2))
1079           else
1080              return (TH.NormalC name (stricts `zip` arg_tys)) }
1081   | otherwise
1082   = failWithTc (ptext (sLit "Can't reify a GADT data constructor:") 
1083                 <+> quotes (ppr dc))
1084
1085 ------------------------------
1086 reifyClass :: Class -> TcM TH.Info
1087 reifyClass cls 
1088   = do  { cxt <- reifyCxt theta
1089         ; ops <- mapM reify_op op_stuff
1090         ; return (TH.ClassI $ TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) fds' ops) }
1091   where
1092     (tvs, fds, theta, _, _, op_stuff) = classExtraBigSig cls
1093     fds' = map reifyFunDep fds
1094     reify_op (op, _) = do { ty <- reifyType (idType op)
1095                           ; return (TH.SigD (reifyName op) ty) }
1096
1097 ------------------------------
1098 reifyType :: TypeRep.Type -> TcM TH.Type
1099 reifyType ty@(ForAllTy _ _)        = reify_for_all ty
1100 reifyType ty@(PredTy {} `FunTy` _) = reify_for_all ty           -- Types like ((?x::Int) => Char -> Char)
1101 reifyType (TyVarTy tv)      = return (TH.VarT (reifyName tv))
1102 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys   -- Do not expand type synonyms here
1103 reifyType (AppTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
1104 reifyType (FunTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
1105 reifyType ty@(PredTy {})    = pprPanic "reifyType PredTy" (ppr ty)
1106
1107 reify_for_all :: TypeRep.Type -> TcM TH.Type
1108 reify_for_all ty
1109   = do { cxt' <- reifyCxt cxt; 
1110        ; tau' <- reifyType tau 
1111        ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
1112   where
1113     (tvs, cxt, tau) = tcSplitSigmaTy ty   
1114                                 
1115 reifyTypes :: [Type] -> TcM [TH.Type]
1116 reifyTypes = mapM reifyType
1117
1118 reifyKind :: Kind -> TH.Kind
1119 reifyKind  ki
1120   = let (kis, ki') = splitKindFunTys ki
1121         kis_rep    = map reifyKind kis
1122         ki'_rep    = reifyNonArrowKind ki'
1123     in
1124     foldl TH.ArrowK ki'_rep kis_rep
1125   where
1126     reifyNonArrowKind k | isLiftedTypeKind k = TH.StarK
1127                         | otherwise          = pprPanic "Exotic form of kind" 
1128                                                         (ppr k)
1129
1130 reifyCxt :: [PredType] -> TcM [TH.Pred]
1131 reifyCxt   = mapM reifyPred
1132
1133 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
1134 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
1135
1136 reifyFamFlavour :: TyCon -> TH.FamFlavour
1137 reifyFamFlavour tc | isOpenSynTyCon tc = TH.TypeFam
1138                    | isOpenTyCon    tc = TH.DataFam
1139                    | otherwise         
1140                    = panic "TcSplice.reifyFamFlavour: not a type family"
1141
1142 reifyTyVars :: [TyVar] -> [TH.TyVarBndr]
1143 reifyTyVars = map reifyTyVar
1144   where
1145     reifyTyVar tv | isLiftedTypeKind kind = TH.PlainTV  name
1146                   | otherwise             = TH.KindedTV name (reifyKind kind)
1147       where
1148         kind = tyVarKind tv
1149         name = reifyName tv
1150
1151 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
1152 reify_tc_app tc tys = do { tys' <- reifyTypes tys 
1153                          ; return (foldl TH.AppT (TH.ConT tc) tys') }
1154
1155 reifyPred :: TypeRep.PredType -> TcM TH.Pred
1156 reifyPred (ClassP cls tys) 
1157   = do { tys' <- reifyTypes tys 
1158        ; return $ TH.ClassP (reifyName cls) tys'
1159        }
1160 reifyPred p@(IParam _ _)   = noTH (sLit "implicit parameters") (ppr p)
1161 reifyPred (EqPred ty1 ty2) 
1162   = do { ty1' <- reifyType ty1
1163        ; ty2' <- reifyType ty2
1164        ; return $ TH.EqualP ty1' ty2'
1165        }
1166
1167
1168 ------------------------------
1169 reifyName :: NamedThing n => n -> TH.Name
1170 reifyName thing
1171   | isExternalName name = mk_varg pkg_str mod_str occ_str
1172   | otherwise           = TH.mkNameU occ_str (getKey (getUnique name))
1173         -- Many of the things we reify have local bindings, and 
1174         -- NameL's aren't supposed to appear in binding positions, so
1175         -- we use NameU.  When/if we start to reify nested things, that
1176         -- have free variables, we may need to generate NameL's for them.
1177   where
1178     name    = getName thing
1179     mod     = ASSERT( isExternalName name ) nameModule name
1180     pkg_str = packageIdString (modulePackageId mod)
1181     mod_str = moduleNameString (moduleName mod)
1182     occ_str = occNameString occ
1183     occ     = nameOccName name
1184     mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
1185             | OccName.isVarOcc  occ = TH.mkNameG_v
1186             | OccName.isTcOcc   occ = TH.mkNameG_tc
1187             | otherwise             = pprPanic "reifyName" (ppr name)
1188
1189 ------------------------------
1190 reifyFixity :: Name -> TcM TH.Fixity
1191 reifyFixity name
1192   = do  { fix <- lookupFixityRn name
1193         ; return (conv_fix fix) }
1194     where
1195       conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
1196       conv_dir BasicTypes.InfixR = TH.InfixR
1197       conv_dir BasicTypes.InfixL = TH.InfixL
1198       conv_dir BasicTypes.InfixN = TH.InfixN
1199
1200 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
1201 reifyStrict MarkedStrict    = TH.IsStrict
1202 reifyStrict MarkedUnboxed   = TH.IsStrict
1203 reifyStrict NotMarkedStrict = TH.NotStrict
1204
1205 ------------------------------
1206 noTH :: LitString -> SDoc -> TcM a
1207 noTH s d = failWithTc (hsep [ptext (sLit "Can't represent") <+> ptext s <+> 
1208                                 ptext (sLit "in Template Haskell:"),
1209                              nest 2 d])
1210 \end{code}