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