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