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
66 import DsMonad hiding (Splice)
71 import Util ( dropList )
72 import Data.List ( mapAccumL )
79 import Control.Monad ( when )
81 import qualified Language.Haskell.TH as TH
82 -- THSyntax gives access to internal functions and data types
83 import qualified Language.Haskell.TH.Syntax as TH
86 -- Because GHC.Desugar might not be in the base library of the bootstrapping compiler
87 import GHC.Desugar ( AnnotationWrapper(..) )
90 import GHC.Exts ( unsafeCoerce#, Int#, Int(..) )
91 import System.IO.Error
94 Note [How top-level splices are handled]
95 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
96 Top-level splices (those not inside a [| .. |] quotation bracket) are handled
97 very straightforwardly:
99 1. tcTopSpliceExpr: typecheck the body e of the splice $(e)
101 2. runMetaT: desugar, compile, run it, and convert result back to
102 HsSyn RdrName (of the appropriate flavour, eg HsType RdrName,
105 3. treat the result as if that's what you saw in the first place
106 e.g for HsType, rename and kind-check
107 for HsExpr, rename and type-check
109 (The last step is different for decls, becuase they can *only* be
110 top-level: we return the result of step 2.)
112 Note [How brackets and nested splices are handled]
113 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
114 Nested splices (those inside a [| .. |] quotation bracket), are treated
117 * After typechecking, the bracket [| |] carries
119 a) A mutable list of PendingSplice
120 type PendingSplice = (Name, LHsExpr Id)
122 b) The quoted expression e, *renamed*: (HsExpr Name)
123 The expression e has been typechecked, but the result of
124 that typechecking is discarded.
126 * The brakcet is desugared by DsMeta.dsBracket. It
128 a) Extends the ds_meta environment with the PendingSplices
129 attached to the bracket
131 b) Converts the quoted (HsExpr Name) to a CoreExpr that, when
132 run, will produce a suitable TH expression/type/decl. This
133 is why we leave the *renamed* expression attached to the bracket:
134 the quoted expression should not be decorated with all the goop
135 added by the type checker
137 * Each splice carries a unique Name, called a "splice point", thus
138 ${n}(e). The name is initialised to an (Unqual "splice") when the
139 splice is created; the renamer gives it a unique.
141 * When the type checker type-checks a nested splice ${n}(e), it
143 - adds the typechecked expression (of type (HsExpr Id))
144 as a pending splice to the enclosing bracket
145 - returns something non-committal
146 Eg for [| f ${n}(g x) |], the typechecker
147 - attaches the typechecked term (g x) to the pending splices for n
149 - returns a non-committal type \alpha.
150 Remember that the bracket discards the typechecked term altogether
152 * When DsMeta (used to desugar the body of the bracket) comes across
153 a splice, it looks up the splice's Name, n, in the ds_meta envt,
154 to find an (HsExpr Id) that should be substituted for the splice;
155 it just desugars it to get a CoreExpr (DsMeta.repSplice).
158 Source: f = [| Just $(g 3) |]
159 The [| |] part is a HsBracket
161 Typechecked: f = [| Just ${s7}(g 3) |]{s7 = g Int 3}
162 The [| |] part is a HsBracketOut, containing *renamed*
163 (not typechecked) expression
164 The "s7" is the "splice point"; the (g Int 3) part
165 is a typechecked expression
167 Desugared: f = do { s7 <- g Int 3
168 ; return (ConE "Data.Maybe.Just" s7) }
171 Note [Template Haskell state diagram]
172 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
173 Here are the ThStages, s, their corresponding level numbers
174 (the result of (thLevel s)), and their state transitions.
176 ----------- $ ------------ $
177 | Comp | ---------> | Splice | -----|
179 ----------- ------------
181 $ | | [||] $ | | [||]
183 -------------- ----------------
184 | Brack Comp | | Brack Splice |
186 -------------- ----------------
188 * Normal top-level declarations start in state Comp
190 Annotations start in state Splice, since they are
191 treated very like a splice (only without a '$')
193 * Code compiled in state Splice (and only such code)
194 will be *run at compile time*, with the result replacing
197 * The original paper used level -1 instead of 0, etc.
199 * The original paper did not allow a splice within a
200 splice, but there is no reason not to. This is the
201 $ transition in the top right.
203 Note [Template Haskell levels]
204 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
205 * Imported things are impLevel (= 0)
207 * In GHCi, variables bound by a previous command are treated
208 as impLevel, because we have bytecode for them.
210 * Variables are bound at the "current level"
212 * The current level starts off at outerLevel (= 1)
214 * The level is decremented by splicing $(..)
215 incremented by brackets [| |]
216 incremented by name-quoting 'f
218 When a variable is used, we compare
219 bind: binding level, and
220 use: current level at usage site
223 bind > use Always error (bound later than used)
226 bind = use Always OK (bound same stage as used)
227 [| \x -> $(f [| x |]) |]
229 bind < use Inside brackets, it depends
233 For (bind < use) inside brackets, there are three cases:
234 - Imported things OK f = [| map |]
235 - Top-level things OK g = [| f |]
236 - Non-top-level Only if there is a liftable instance
237 h = \(x:Int) -> [| x |]
239 See Note [What is a top-level Id?]
243 A quoted name 'n is a bit like a quoted expression [| n |], except that we
244 have no cross-stage lifting (c.f. TcExpr.thBrackId). So, after incrementing
245 the use-level to account for the brackets, the cases are:
254 See Note [What is a top-level Id?] in TcEnv. Examples:
256 f 'map -- OK; also for top-level defns of this module
258 \x. f 'x -- Not ok (whereas \x. f [| x |] might have been ok, by
259 -- cross-stage lifting
261 \y. [| \x. $(f 'y) |] -- Not ok (same reason)
263 [| \x. $(f 'x) |] -- OK
266 Note [What is a top-level Id?]
267 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
268 In the level-control criteria above, we need to know what a "top level Id" is.
269 There are three kinds:
270 * Imported from another module (GlobalId, ExternalName)
271 * Bound at the top level of this module (ExternalName)
272 * In GHCi, bound by a previous stmt (GlobalId)
273 It's strange that there is no one criterion tht picks out all three, but that's
274 how it is right now. (The obvious thing is to give an ExternalName to GHCi Ids
275 bound in an earlier Stmt, but what module would you choose? See
276 Note [Interactively-bound Ids in GHCi] in TcRnDriver.)
278 The predicate we use is TcEnv.thTopLevelId.
281 %************************************************************************
283 \subsection{Main interface + stubs for the non-GHCI case
285 %************************************************************************
288 tcBracket :: HsBracket Name -> BoxyRhoType -> TcM (LHsExpr TcId)
289 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
290 tcSpliceExpr :: HsSplice Name -> BoxyRhoType -> TcM (HsExpr TcId)
291 kcSpliceType :: HsSplice Name -> FreeVars -> TcM (HsType Name, TcKind)
292 -- None of these functions add constraints to the LIE
294 lookupThName_maybe :: TH.Name -> TcM (Maybe Name)
296 runQuasiQuoteExpr :: HsQuasiQuote RdrName -> RnM (LHsExpr RdrName)
297 runQuasiQuotePat :: HsQuasiQuote RdrName -> RnM (LPat RdrName)
298 runQuasiQuoteType :: HsQuasiQuote RdrName -> RnM (LHsType RdrName)
299 runQuasiQuoteDecl :: HsQuasiQuote RdrName -> RnM [LHsDecl RdrName]
301 runAnnotation :: CoreAnnTarget -> LHsExpr Name -> TcM Annotation
304 tcBracket x _ = pprPanic "Cant do tcBracket without GHCi" (ppr x)
305 tcSpliceExpr e = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
306 tcSpliceDecls x = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr x)
307 kcSpliceType x fvs = pprPanic "Cant do kcSpliceType without GHCi" (ppr x)
309 lookupThName_maybe n = pprPanic "Cant do lookupThName_maybe without GHCi" (ppr n)
311 runQuasiQuoteExpr q = pprPanic "Cant do runQuasiQuoteExpr without GHCi" (ppr q)
312 runQuasiQuotePat q = pprPanic "Cant do runQuasiQuotePat without GHCi" (ppr q)
313 runQuasiQuoteType q = pprPanic "Cant do runQuasiQuoteType without GHCi" (ppr q)
314 runQuasiQuoteDecl q = pprPanic "Cant do runQuasiQuoteDecl without GHCi" (ppr q)
315 runAnnotation _ q = pprPanic "Cant do runAnnotation without GHCi" (ppr q)
319 %************************************************************************
321 \subsection{Quoting an expression}
323 %************************************************************************
327 -- See Note [How brackets and nested splices are handled]
328 tcBracket brack res_ty
329 = addErrCtxt (hang (ptext (sLit "In the Template Haskell quotation"))
331 do { -- Check for nested brackets
332 cur_stage <- getStage
333 ; checkTc (not (isBrackStage cur_stage)) illegalBracket
335 -- Brackets are desugared to code that mentions the TH package
338 -- Typecheck expr to make sure it is valid,
339 -- but throw away the results. We'll type check
340 -- it again when we actually use it.
341 ; pending_splices <- newMutVar []
342 ; lie_var <- getLIEVar
343 ; let brack_stage = Brack cur_stage pending_splices lie_var
345 ; (meta_ty, lie) <- setStage brack_stage $
347 tc_bracket cur_stage brack
349 ; tcSimplifyBracket lie
351 -- Make the expected type have the right shape
352 ; _ <- boxyUnify meta_ty res_ty
354 -- Return the original expression, not the type-decorated one
355 ; pendings <- readMutVar pending_splices
356 ; return (noLoc (HsBracketOut brack pendings)) }
358 tc_bracket :: ThStage -> HsBracket Name -> TcM TcType
359 tc_bracket outer_stage (VarBr name) -- Note [Quoting names]
360 = do { thing <- tcLookup name
362 AGlobal _ -> return ()
363 ATcId { tct_level = bind_lvl, tct_id = id }
364 | thTopLevelId id -- C.f TcExpr.checkCrossStageLifting
367 -> do { checkTc (thLevel outer_stage + 1 == bind_lvl)
368 (quotedNameStageErr name) }
369 _ -> pprPanic "th_bracket" (ppr name)
371 ; tcMetaTy nameTyConName -- Result type is Var (not Q-monadic)
374 tc_bracket _ (ExpBr expr)
375 = do { any_ty <- newFlexiTyVarTy liftedTypeKind
376 ; _ <- tcMonoExprNC expr any_ty -- NC for no context; tcBracket does that
377 ; tcMetaTy expQTyConName }
378 -- Result type is ExpQ (= Q Exp)
380 tc_bracket _ (TypBr typ)
381 = do { _ <- tcHsSigTypeNC ThBrackCtxt typ
382 ; tcMetaTy typeQTyConName }
383 -- Result type is Type (= Q Typ)
385 tc_bracket _ (DecBrG decls)
386 = do { _ <- tcTopSrcDecls emptyModDetails decls
387 -- Typecheck the declarations, dicarding the result
388 -- We'll get all that stuff later, when we splice it in
390 -- Top-level declarations in the bracket get unqualified names
391 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
393 ; tcMetaTy decsQTyConName } -- Result type is Q [Dec]
395 tc_bracket _ (PatBr pat)
396 = do { any_ty <- newFlexiTyVarTy liftedTypeKind
397 ; _ <- tcPat ThPatQuote pat any_ty unitTy $ \_ ->
399 ; tcMetaTy patQTyConName }
400 -- Result type is PatQ (= Q Pat)
402 tc_bracket _ (DecBrL _)
403 = panic "tc_bracket: Unexpected DecBrL"
405 quotedNameStageErr :: Name -> SDoc
407 = sep [ ptext (sLit "Stage error: the non-top-level quoted name") <+> ppr (VarBr v)
408 , ptext (sLit "must be used at the same stage at which is is bound")]
412 %************************************************************************
414 \subsection{Splicing an expression}
416 %************************************************************************
419 tcSpliceExpr (HsSplice name expr) res_ty
420 = setSrcSpan (getLoc expr) $ do
423 Splice -> tcTopSplice expr res_ty ;
424 Comp -> tcTopSplice expr res_ty ;
426 Brack pop_stage ps_var lie_var -> do
428 -- See Note [How brackets and nested splices are handled]
429 -- A splice inside brackets
430 -- NB: ignore res_ty, apart from zapping it to a mono-type
431 -- e.g. [| reverse $(h 4) |]
432 -- Here (h 4) :: Q Exp
433 -- but $(h 4) :: forall a.a i.e. anything!
436 ; meta_exp_ty <- tcMetaTy expQTyConName
437 ; expr' <- setStage pop_stage $
439 tcMonoExpr expr meta_exp_ty
441 -- Write the pending splice into the bucket
442 ; ps <- readMutVar ps_var
443 ; writeMutVar ps_var ((name,expr') : ps)
445 ; return (panic "tcSpliceExpr") -- The returned expression is ignored
448 tcTopSplice :: LHsExpr Name -> BoxyRhoType -> TcM (HsExpr Id)
449 -- Note [How top-level splices are handled]
450 tcTopSplice expr res_ty
451 = do { meta_exp_ty <- tcMetaTy expQTyConName
453 -- Typecheck the expression
454 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_exp_ty)
456 -- Run the expression
457 ; expr2 <- runMetaE zonked_q_expr
458 ; showSplice "expression" expr (ppr expr2)
460 -- Rename it, but bale out if there are errors
461 -- otherwise the type checker just gives more spurious errors
462 ; addErrCtxt (spliceResultDoc expr) $ do
463 { (exp3, _fvs) <- checkNoErrs (rnLExpr expr2)
465 ; exp4 <- tcMonoExpr exp3 res_ty
466 ; return (unLoc exp4) } }
468 spliceResultDoc :: LHsExpr Name -> SDoc
470 = sep [ ptext (sLit "In the result of the splice:")
471 , nest 2 (char '$' <> pprParendExpr expr)
472 , ptext (sLit "To see what the splice expanded to, use -ddump-splices")]
475 tcTopSpliceExpr :: TcM (LHsExpr Id) -> TcM (LHsExpr Id)
476 -- Note [How top-level splices are handled]
477 -- Type check an expression that is the body of a top-level splice
478 -- (the caller will compile and run it)
479 -- Note that set the level to Splice, regardless of the original level,
480 -- before typechecking the expression. For example:
481 -- f x = $( ...$(g 3) ... )
482 -- The recursive call to tcMonoExpr will simply expand the
483 -- inner escape before dealing with the outer one
485 tcTopSpliceExpr tc_action
486 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
487 -- if the type checker fails!
489 do { -- Typecheck the expression
490 (expr', lie) <- getLIE tc_action
492 -- Solve the constraints
493 ; const_binds <- tcSimplifyTop lie
495 -- Zonk it and tie the knot of dictionary bindings
496 ; zonkTopLExpr (mkHsDictLet const_binds expr') }
500 %************************************************************************
504 %************************************************************************
506 Very like splicing an expression, but we don't yet share code.
509 kcSpliceType splice@(HsSplice name hs_expr) fvs
510 = setSrcSpan (getLoc hs_expr) $ do
513 Splice -> kcTopSpliceType hs_expr ;
514 Comp -> kcTopSpliceType hs_expr ;
516 Brack pop_level ps_var lie_var -> do
517 -- See Note [How brackets and nested splices are handled]
518 -- A splice inside brackets
519 { meta_ty <- tcMetaTy typeQTyConName
520 ; expr' <- setStage pop_level $
522 tcMonoExpr hs_expr meta_ty
524 -- Write the pending splice into the bucket
525 ; ps <- readMutVar ps_var
526 ; writeMutVar ps_var ((name,expr') : ps)
528 -- e.g. [| f (g :: Int -> $(h 4)) |]
529 -- Here (h 4) :: Q Type
530 -- but $(h 4) :: a i.e. any type, of any kind
533 ; return (HsSpliceTy splice fvs kind, kind)
536 kcTopSpliceType :: LHsExpr Name -> TcM (HsType Name, TcKind)
537 -- Note [How top-level splices are handled]
539 = do { meta_ty <- tcMetaTy typeQTyConName
541 -- Typecheck the expression
542 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_ty)
544 -- Run the expression
545 ; hs_ty2 <- runMetaT zonked_q_expr
546 ; showSplice "type" expr (ppr hs_ty2)
548 -- Rename it, but bale out if there are errors
549 -- otherwise the type checker just gives more spurious errors
550 ; addErrCtxt (spliceResultDoc expr) $ do
551 { let doc = ptext (sLit "In the spliced type") <+> ppr hs_ty2
552 ; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)
553 ; (ty4, kind) <- kcLHsType hs_ty3
554 ; return (unLoc ty4, kind) }}
557 %************************************************************************
559 \subsection{Splicing an expression}
561 %************************************************************************
564 -- Note [How top-level splices are handled]
565 -- Always at top level
566 -- Type sig at top of file:
567 -- tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
569 = do { list_q <- tcMetaTy decsQTyConName -- Q [Dec]
570 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr list_q)
572 -- Run the expression
573 ; decls <- runMetaD zonked_q_expr
574 ; showSplice "declarations" expr
575 (ppr (getLoc expr) $$ (vcat (map ppr decls)))
581 %************************************************************************
585 %************************************************************************
588 runAnnotation target expr = do
589 -- Find the classes we want instances for in order to call toAnnotationWrapper
591 data_class <- tcLookupClass dataClassName
592 to_annotation_wrapper_id <- tcLookupId toAnnotationWrapperName
594 -- Check the instances we require live in another module (we want to execute it..)
595 -- and check identifiers live in other modules using TH stage checks. tcSimplifyStagedExpr
596 -- also resolves the LIE constraints to detect e.g. instance ambiguity
597 zonked_wrapped_expr' <- tcTopSpliceExpr $
598 do { (expr', expr_ty) <- tcInferRhoNC expr
599 -- We manually wrap the typechecked expression in a call to toAnnotationWrapper
600 -- By instantiating the call >here< it gets registered in the
601 -- LIE consulted by tcTopSpliceExpr
602 -- and hence ensures the appropriate dictionary is bound by const_binds
603 ; wrapper <- instCall AnnOrigin [expr_ty] [mkClassPred data_class [expr_ty]]
604 ; let specialised_to_annotation_wrapper_expr
605 = L loc (HsWrap wrapper (HsVar to_annotation_wrapper_id))
606 ; return (L loc (HsApp specialised_to_annotation_wrapper_expr expr')) }
608 -- Run the appropriately wrapped expression to get the value of
609 -- the annotation and its dictionaries. The return value is of
610 -- type AnnotationWrapper by construction, so this conversion is
612 flip runMetaAW zonked_wrapped_expr' $ \annotation_wrapper ->
613 case annotation_wrapper of
614 AnnotationWrapper value | let serialized = toSerialized serializeWithData value ->
615 -- Got the value and dictionaries: build the serialized value and
616 -- call it a day. We ensure that we seq the entire serialized value
617 -- in order that any errors in the user-written code for the
618 -- annotation are exposed at this point. This is also why we are
619 -- doing all this stuff inside the context of runMeta: it has the
620 -- facilities to deal with user error in a meta-level expression
621 seqSerialized serialized `seq` Annotation {
623 ann_value = serialized
628 %************************************************************************
632 %************************************************************************
634 Note [Quasi-quote overview]
635 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
636 The GHC "quasi-quote" extension is described by Geoff Mainland's paper
637 "Why it's nice to be quoted: quasiquoting for Haskell" (Haskell
642 and the arbitrary string "stuff" gets parsed by the parser 'p', whose
643 type should be Language.Haskell.TH.Quote.QuasiQuoter. 'p' must be
644 defined in another module, because we are going to run it here. It's
645 a bit like a TH splice:
648 However, you can do this in patterns as well as terms. Becuase of this,
649 the splice is run by the *renamer* rather than the type checker.
651 %************************************************************************
653 \subsubsection{Quasiquotation}
655 %************************************************************************
657 See Note [Quasi-quote overview] in TcSplice.
660 runQuasiQuote :: Outputable hs_syn
661 => HsQuasiQuote RdrName -- Contains term of type QuasiQuoter, and the String
662 -> Name -- Of type QuasiQuoter -> String -> Q th_syn
663 -> Name -- Name of th_syn type
664 -> MetaOps th_syn hs_syn
666 runQuasiQuote (HsQuasiQuote quoter q_span quote) quote_selector meta_ty meta_ops
667 = do { quoter' <- lookupOccRn quoter
668 -- We use lookupOcc rather than lookupGlobalOcc because in the
669 -- erroneous case of \x -> [x| ...|] we get a better error message
670 -- (stage restriction rather than out of scope).
672 ; when (isUnboundName quoter') failM
673 -- If 'quoter' is not in scope, proceed no further
674 -- The error message was generated by lookupOccRn, but it then
675 -- succeeds with an "unbound name", which makes the subsequent
676 -- attempt to run the quote fail in a confusing way
678 -- Check that the quoter is not locally defined, otherwise the TH
679 -- machinery will not be able to run the quasiquote.
680 ; this_mod <- getModule
681 ; let is_local = nameIsLocalOrFrom this_mod quoter'
682 ; checkTc (not is_local) (quoteStageError quoter')
684 ; traceTc (text "runQQ" <+> ppr quoter <+> ppr is_local)
686 -- Build the expression
687 ; let quoterExpr = L q_span $! HsVar $! quoter'
688 ; let quoteExpr = L q_span $! HsLit $! HsString quote
689 ; let expr = L q_span $
691 HsApp (L q_span (HsVar quote_selector)) quoterExpr) quoteExpr
692 ; meta_exp_ty <- tcMetaTy meta_ty
694 -- Typecheck the expression
695 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_exp_ty)
697 -- Run the expression
698 ; result <- runMetaQ meta_ops zonked_q_expr
699 ; showSplice (mt_desc meta_ops) quoteExpr (ppr result)
703 runQuasiQuoteExpr qq = runQuasiQuote qq quoteExpName expQTyConName exprMetaOps
704 runQuasiQuotePat qq = runQuasiQuote qq quotePatName patQTyConName patMetaOps
705 runQuasiQuoteType qq = runQuasiQuote qq quoteTypeName typeQTyConName typeMetaOps
706 runQuasiQuoteDecl qq = runQuasiQuote qq quoteDecName decsQTyConName declMetaOps
708 quoteStageError :: Name -> SDoc
709 quoteStageError quoter
710 = sep [ptext (sLit "GHC stage restriction:") <+> ppr quoter,
711 nest 2 (ptext (sLit "is used in a quasiquote, and must be imported, not defined locally"))]
715 %************************************************************************
717 \subsection{Running an expression}
719 %************************************************************************
722 data MetaOps th_syn hs_syn
723 = MT { mt_desc :: String -- Type of beast (expression, type etc)
724 , mt_show :: th_syn -> String -- How to show the th_syn thing
725 , mt_cvt :: SrcSpan -> th_syn -> Either Message hs_syn
726 -- How to convert to hs_syn
729 exprMetaOps :: MetaOps TH.Exp (LHsExpr RdrName)
730 exprMetaOps = MT { mt_desc = "expression", mt_show = TH.pprint, mt_cvt = convertToHsExpr }
732 patMetaOps :: MetaOps TH.Pat (LPat RdrName)
733 patMetaOps = MT { mt_desc = "pattern", mt_show = TH.pprint, mt_cvt = convertToPat }
735 typeMetaOps :: MetaOps TH.Type (LHsType RdrName)
736 typeMetaOps = MT { mt_desc = "type", mt_show = TH.pprint, mt_cvt = convertToHsType }
738 declMetaOps :: MetaOps [TH.Dec] [LHsDecl RdrName]
739 declMetaOps = MT { mt_desc = "declarations", mt_show = TH.pprint, mt_cvt = convertToHsDecls }
742 runMetaAW :: Outputable output
743 => (AnnotationWrapper -> output)
744 -> LHsExpr Id -- Of type AnnotationWrapper
746 runMetaAW k = runMeta False (\_ -> return . Right . k)
747 -- We turn off showing the code in meta-level exceptions because doing so exposes
748 -- the toAnnotationWrapper function that we slap around the users code
751 runMetaQ :: Outputable hs_syn
752 => MetaOps th_syn hs_syn
755 runMetaQ (MT { mt_show = show_th, mt_cvt = cvt }) expr
756 = runMeta True run_and_cvt expr
758 run_and_cvt expr_span hval
759 = do { th_result <- TH.runQ hval
760 ; traceTc (text "Got TH result:" <+> text (show_th th_result))
761 ; return (cvt expr_span th_result) }
763 runMetaE :: LHsExpr Id -- Of type (Q Exp)
764 -> TcM (LHsExpr RdrName)
765 runMetaE = runMetaQ exprMetaOps
767 runMetaT :: LHsExpr Id -- Of type (Q Type)
768 -> TcM (LHsType RdrName)
769 runMetaT = runMetaQ typeMetaOps
771 runMetaD :: LHsExpr Id -- Of type Q [Dec]
772 -> TcM [LHsDecl RdrName]
773 runMetaD = runMetaQ declMetaOps
776 runMeta :: (Outputable hs_syn)
777 => Bool -- Whether code should be printed in the exception message
778 -> (SrcSpan -> x -> TcM (Either Message hs_syn)) -- How to run x
779 -> LHsExpr Id -- Of type x; typically x = Q TH.Exp, or something like that
780 -> TcM hs_syn -- Of type t
781 runMeta show_code run_and_convert expr
782 = do { traceTc (text "About to run" <+> ppr expr)
785 ; ds_expr <- initDsTc (dsLExpr expr)
786 -- Compile and link it; might fail if linking fails
787 ; hsc_env <- getTopEnv
788 ; src_span <- getSrcSpanM
789 ; either_hval <- tryM $ liftIO $
790 HscMain.compileExpr hsc_env src_span ds_expr
791 ; case either_hval of {
792 Left exn -> failWithTc (mk_msg "compile and link" exn) ;
795 { -- Coerce it to Q t, and run it
797 -- Running might fail if it throws an exception of any kind (hence tryAllM)
798 -- including, say, a pattern-match exception in the code we are running
800 -- We also do the TH -> HS syntax conversion inside the same
801 -- exception-cacthing thing so that if there are any lurking
802 -- exceptions in the data structure returned by hval, we'll
803 -- encounter them inside the try
805 -- See Note [Exceptions in TH]
806 let expr_span = getLoc expr
807 ; either_tval <- tryAllM $
808 setSrcSpan expr_span $ -- Set the span so that qLocation can
809 -- see where this splice is
810 do { mb_result <- run_and_convert expr_span (unsafeCoerce# hval)
812 Left err -> failWithTc err
813 Right result -> do { traceTc (ptext (sLit "Got HsSyn result:") <+> ppr result)
814 ; return $! result } }
816 ; case either_tval of
818 Left se -> case fromException se of
819 Just IOEnvFailure -> failM -- Error already in Tc monad
820 _ -> failWithTc (mk_msg "run" se) -- Exception
823 mk_msg s exn = vcat [text "Exception when trying to" <+> text s <+> text "compile-time code:",
824 nest 2 (text (Panic.showException exn)),
825 if show_code then nest 2 (text "Code:" <+> ppr expr) else empty]
828 Note [Exceptions in TH]
829 ~~~~~~~~~~~~~~~~~~~~~~~
830 Supppose we have something like this
834 f n | n>3 = fail "Too many declarations"
837 The 'fail' is a user-generated failure, and should be displayed as a
838 perfectly ordinary compiler error message, not a panic or anything
839 like that. Here's how it's processed:
841 * 'fail' is the monad fail. The monad instance for Q in TH.Syntax
842 effectively transforms (fail s) to
843 qReport True s >> fail
844 where 'qReport' comes from the Quasi class and fail from its monad
847 * The TcM monad is an instance of Quasi (see TcSplice), and it implements
848 (qReport True s) by using addErr to add an error message to the bag of errors.
849 The 'fail' in TcM raises an IOEnvFailure exception
851 * So, when running a splice, we catch all exceptions; then for
852 - an IOEnvFailure exception, we assume the error is already
853 in the error-bag (above)
854 - other errors, we add an error to the bag
858 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
861 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
862 qNewName s = do { u <- newUnique
864 ; return (TH.mkNameU s i) }
866 qReport True msg = addErr (text msg)
867 qReport False msg = addReport (text msg) empty
869 qLocation = do { m <- getModule
871 ; return (TH.Loc { TH.loc_filename = unpackFS (srcSpanFile l)
872 , TH.loc_module = moduleNameString (moduleName m)
873 , TH.loc_package = packageIdString (modulePackageId m)
874 , TH.loc_start = (srcSpanStartLine l, srcSpanStartCol l)
875 , TH.loc_end = (srcSpanEndLine l, srcSpanEndCol l) }) }
879 -- For qRecover, discard error messages if
880 -- the recovery action is chosen. Otherwise
881 -- we'll only fail higher up. c.f. tryTcLIE_
882 qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main
884 Just val -> do { addMessages msgs -- There might be warnings
886 Nothing -> recover -- Discard all msgs
889 qRunIO io = liftIO io
893 %************************************************************************
895 \subsection{Errors and contexts}
897 %************************************************************************
900 showSplice :: String -> LHsExpr Name -> SDoc -> TcM ()
901 -- Note that 'before' is *renamed* but not *typechecked*
902 -- Reason (a) less typechecking crap
903 -- (b) data constructors after type checking have been
904 -- changed to their *wrappers*, and that makes them
905 -- print always fully qualified
906 showSplice what before after
907 = do { loc <- getSrcSpanM
908 ; traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
909 nest 2 (sep [nest 2 (ppr before),
913 illegalBracket :: SDoc
914 illegalBracket = ptext (sLit "Template Haskell brackets cannot be nested (without intervening splices)")
919 %************************************************************************
923 %************************************************************************
927 reify :: TH.Name -> TcM TH.Info
929 = do { name <- lookupThName th_name
930 ; thing <- tcLookupTh name
931 -- ToDo: this tcLookup could fail, which would give a
932 -- rather unhelpful error message
933 ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
937 ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
938 ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
939 ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
940 ppr_ns _ = panic "reify/ppr_ns"
942 lookupThName :: TH.Name -> TcM Name
943 lookupThName th_name = do
944 mb_name <- lookupThName_maybe th_name
946 Nothing -> failWithTc (notInScope th_name)
947 Just name -> return name
949 lookupThName_maybe th_name
950 = do { names <- mapMaybeM lookup (thRdrNameGuesses th_name)
951 -- Pick the first that works
952 -- E.g. reify (mkName "A") will pick the class A in preference to the data constructor A
953 ; return (listToMaybe names) }
956 = do { -- Repeat much of lookupOccRn, becase we want
957 -- to report errors in a TH-relevant way
958 ; rdr_env <- getLocalRdrEnv
959 ; case lookupLocalRdrEnv rdr_env rdr_name of
960 Just name -> return (Just name)
961 Nothing -> lookupGlobalOccRn_maybe rdr_name }
963 tcLookupTh :: Name -> TcM TcTyThing
964 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
965 -- it gives a reify-related error message on failure, whereas in the normal
966 -- tcLookup, failure is a bug.
968 = do { (gbl_env, lcl_env) <- getEnvs
969 ; case lookupNameEnv (tcl_env lcl_env) name of {
970 Just thing -> return thing;
972 { if nameIsLocalOrFrom (tcg_mod gbl_env) name
973 then -- It's defined in this module
974 case lookupNameEnv (tcg_type_env gbl_env) name of
975 Just thing -> return (AGlobal thing)
976 Nothing -> failWithTc (notInEnv name)
978 else do -- It's imported
979 { (eps,hpt) <- getEpsAndHpt
981 ; case lookupType dflags hpt (eps_PTE eps) name of
982 Just thing -> return (AGlobal thing)
983 Nothing -> do { thing <- tcImportDecl name
984 ; return (AGlobal thing) }
985 -- Imported names should always be findable;
986 -- if not, we fail hard in tcImportDecl
989 notInScope :: TH.Name -> SDoc
990 notInScope th_name = quotes (text (TH.pprint th_name)) <+>
991 ptext (sLit "is not in scope at a reify")
992 -- Ugh! Rather an indirect way to display the name
994 notInEnv :: Name -> SDoc
995 notInEnv name = quotes (ppr name) <+>
996 ptext (sLit "is not in the type environment at a reify")
998 ------------------------------
999 reifyThing :: TcTyThing -> TcM TH.Info
1000 -- The only reason this is monadic is for error reporting,
1001 -- which in turn is mainly for the case when TH can't express
1002 -- some random GHC extension
1004 reifyThing (AGlobal (AnId id))
1005 = do { ty <- reifyType (idType id)
1006 ; fix <- reifyFixity (idName id)
1007 ; let v = reifyName id
1008 ; case idDetails id of
1009 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
1010 _ -> return (TH.VarI v ty Nothing fix)
1013 reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc
1014 reifyThing (AGlobal (AClass cls)) = reifyClass cls
1015 reifyThing (AGlobal (ADataCon dc))
1016 = do { let name = dataConName dc
1017 ; ty <- reifyType (idType (dataConWrapId dc))
1018 ; fix <- reifyFixity name
1019 ; return (TH.DataConI (reifyName name) ty
1020 (reifyName (dataConOrigTyCon dc)) fix)
1023 reifyThing (ATcId {tct_id = id, tct_type = ty})
1024 = do { ty1 <- zonkTcType ty -- Make use of all the info we have, even
1025 -- though it may be incomplete
1026 ; ty2 <- reifyType ty1
1027 ; fix <- reifyFixity (idName id)
1028 ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
1030 reifyThing (ATyVar tv ty)
1031 = do { ty1 <- zonkTcType ty
1032 ; ty2 <- reifyType ty1
1033 ; return (TH.TyVarI (reifyName tv) ty2) }
1035 reifyThing (AThing {}) = panic "reifyThing AThing"
1037 ------------------------------
1038 reifyTyCon :: TyCon -> TcM TH.Info
1041 = return (TH.PrimTyConI (reifyName tc) 2 False)
1043 = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc))
1045 = let flavour = reifyFamFlavour tc
1046 tvs = tyConTyVars tc
1049 | isLiftedTypeKind kind = Nothing
1050 | otherwise = Just $ reifyKind kind
1053 TH.FamilyD flavour (reifyName tc) (reifyTyVars tvs) kind')
1055 = do { let (tvs, rhs) = synTyConDefn tc
1056 ; rhs' <- reifyType rhs
1057 ; return (TH.TyConI $
1058 TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs')
1062 = do { cxt <- reifyCxt (tyConStupidTheta tc)
1063 ; let tvs = tyConTyVars tc
1064 ; cons <- mapM (reifyDataCon (mkTyVarTys tvs)) (tyConDataCons tc)
1065 ; let name = reifyName tc
1066 r_tvs = reifyTyVars tvs
1067 deriv = [] -- Don't know about deriving
1068 decl | isNewTyCon tc = TH.NewtypeD cxt name r_tvs (head cons) deriv
1069 | otherwise = TH.DataD cxt name r_tvs cons deriv
1070 ; return (TH.TyConI decl) }
1072 reifyDataCon :: [Type] -> DataCon -> TcM TH.Con
1073 -- For GADTs etc, see Note [Reifying data constructors]
1075 = do { let (tvs, theta, arg_tys, _) = dataConSig dc
1076 subst = mkTopTvSubst (tvs `zip` tys) -- Dicard ex_tvs
1077 (subst', ex_tvs') = mapAccumL substTyVarBndr subst (dropList tys tvs)
1078 theta' = substTheta subst' theta
1079 arg_tys' = substTys subst' arg_tys
1080 stricts = map reifyStrict (dataConStrictMarks dc)
1081 fields = dataConFieldLabels dc
1084 ; r_arg_tys <- reifyTypes arg_tys'
1086 ; let main_con | not (null fields)
1087 = TH.RecC name (zip3 (map reifyName fields) stricts r_arg_tys)
1089 = ASSERT( length arg_tys == 2 )
1090 TH.InfixC (s1,r_a1) name (s2,r_a2)
1092 = TH.NormalC name (stricts `zip` r_arg_tys)
1093 [r_a1, r_a2] = r_arg_tys
1096 ; ASSERT( length arg_tys == length stricts )
1097 if null ex_tvs' && null theta then
1100 { cxt <- reifyCxt theta'
1101 ; return (TH.ForallC (reifyTyVars ex_tvs') cxt main_con) } }
1103 ------------------------------
1104 reifyClass :: Class -> TcM TH.Info
1106 = do { cxt <- reifyCxt theta
1107 ; ops <- mapM reify_op op_stuff
1108 ; return (TH.ClassI $ TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) fds' ops) }
1110 (tvs, fds, theta, _, _, op_stuff) = classExtraBigSig cls
1111 fds' = map reifyFunDep fds
1112 reify_op (op, _) = do { ty <- reifyType (idType op)
1113 ; return (TH.SigD (reifyName op) ty) }
1115 ------------------------------
1116 reifyType :: TypeRep.Type -> TcM TH.Type
1117 reifyType ty@(ForAllTy _ _) = reify_for_all ty
1118 reifyType ty@(PredTy {} `FunTy` _) = reify_for_all ty -- Types like ((?x::Int) => Char -> Char)
1119 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
1120 reifyType (TyConApp tc tys) = reify_tc_app tc tys -- Do not expand type synonyms here
1121 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
1122 reifyType (FunTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
1123 reifyType ty@(PredTy {}) = pprPanic "reifyType PredTy" (ppr ty)
1125 reify_for_all :: TypeRep.Type -> TcM TH.Type
1127 = do { cxt' <- reifyCxt cxt;
1128 ; tau' <- reifyType tau
1129 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
1131 (tvs, cxt, tau) = tcSplitSigmaTy ty
1133 reifyTypes :: [Type] -> TcM [TH.Type]
1134 reifyTypes = mapM reifyType
1136 reifyKind :: Kind -> TH.Kind
1138 = let (kis, ki') = splitKindFunTys ki
1139 kis_rep = map reifyKind kis
1140 ki'_rep = reifyNonArrowKind ki'
1142 foldr TH.ArrowK ki'_rep kis_rep
1144 reifyNonArrowKind k | isLiftedTypeKind k = TH.StarK
1145 | otherwise = pprPanic "Exotic form of kind"
1148 reifyCxt :: [PredType] -> TcM [TH.Pred]
1149 reifyCxt = mapM reifyPred
1151 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
1152 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
1154 reifyFamFlavour :: TyCon -> TH.FamFlavour
1155 reifyFamFlavour tc | isOpenSynTyCon tc = TH.TypeFam
1156 | isOpenTyCon tc = TH.DataFam
1158 = panic "TcSplice.reifyFamFlavour: not a type family"
1160 reifyTyVars :: [TyVar] -> [TH.TyVarBndr]
1161 reifyTyVars = map reifyTyVar
1163 reifyTyVar tv | isLiftedTypeKind kind = TH.PlainTV name
1164 | otherwise = TH.KindedTV name (reifyKind kind)
1169 reify_tc_app :: TyCon -> [TypeRep.Type] -> TcM TH.Type
1171 = do { tys' <- reifyTypes tys
1172 ; return (foldl TH.AppT r_tc tys') }
1175 r_tc | isTupleTyCon tc = TH.TupleT n_tys
1176 | tc `hasKey` listTyConKey = TH.ListT
1177 | otherwise = TH.ConT (reifyName tc)
1179 reifyPred :: TypeRep.PredType -> TcM TH.Pred
1180 reifyPred (ClassP cls tys)
1181 = do { tys' <- reifyTypes tys
1182 ; return $ TH.ClassP (reifyName cls) tys' }
1184 reifyPred p@(IParam _ _) = noTH (sLit "implicit parameters") (ppr p)
1185 reifyPred (EqPred ty1 ty2)
1186 = do { ty1' <- reifyType ty1
1187 ; ty2' <- reifyType ty2
1188 ; return $ TH.EqualP ty1' ty2'
1192 ------------------------------
1193 reifyName :: NamedThing n => n -> TH.Name
1195 | isExternalName name = mk_varg pkg_str mod_str occ_str
1196 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
1197 -- Many of the things we reify have local bindings, and
1198 -- NameL's aren't supposed to appear in binding positions, so
1199 -- we use NameU. When/if we start to reify nested things, that
1200 -- have free variables, we may need to generate NameL's for them.
1202 name = getName thing
1203 mod = ASSERT( isExternalName name ) nameModule name
1204 pkg_str = packageIdString (modulePackageId mod)
1205 mod_str = moduleNameString (moduleName mod)
1206 occ_str = occNameString occ
1207 occ = nameOccName name
1208 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
1209 | OccName.isVarOcc occ = TH.mkNameG_v
1210 | OccName.isTcOcc occ = TH.mkNameG_tc
1211 | otherwise = pprPanic "reifyName" (ppr name)
1213 ------------------------------
1214 reifyFixity :: Name -> TcM TH.Fixity
1216 = do { fix <- lookupFixityRn name
1217 ; return (conv_fix fix) }
1219 conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
1220 conv_dir BasicTypes.InfixR = TH.InfixR
1221 conv_dir BasicTypes.InfixL = TH.InfixL
1222 conv_dir BasicTypes.InfixN = TH.InfixN
1224 reifyStrict :: BasicTypes.HsBang -> TH.Strict
1225 reifyStrict bang | isBanged bang = TH.IsStrict
1226 | otherwise = TH.NotStrict
1228 ------------------------------
1229 noTH :: LitString -> SDoc -> TcM a
1230 noTH s d = failWithTc (hsep [ptext (sLit "Can't represent") <+> ptext s <+>
1231 ptext (sLit "in Template Haskell:"),
1235 Note [Reifying data constructors]
1236 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1237 Template Haskell syntax is rich enough to express even GADTs,
1238 provided we do so in the equality-predicate form. So a GADT
1245 will appear in TH syntax like this
1247 data T a = forall b. (a ~ [b]) => MkT1 b