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