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