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