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