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