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 )
80 import Control.Monad ( when )
82 import qualified Language.Haskell.TH as TH
83 -- THSyntax gives access to internal functions and data types
84 import qualified Language.Haskell.TH.Syntax as TH
87 -- Because GHC.Desugar might not be in the base library of the bootstrapping compiler
88 import GHC.Desugar ( AnnotationWrapper(..) )
91 import GHC.Exts ( unsafeCoerce#, Int#, Int(..) )
92 import System.IO.Error
95 Note [How top-level splices are handled]
96 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
97 Top-level splices (those not inside a [| .. |] quotation bracket) are handled
98 very straightforwardly:
100 1. tcTopSpliceExpr: typecheck the body e of the splice $(e)
102 2. runMetaT: desugar, compile, run it, and convert result back to
103 HsSyn RdrName (of the appropriate flavour, eg HsType RdrName,
106 3. treat the result as if that's what you saw in the first place
107 e.g for HsType, rename and kind-check
108 for HsExpr, rename and type-check
110 (The last step is different for decls, becuase they can *only* be
111 top-level: we return the result of step 2.)
113 Note [How brackets and nested splices are handled]
114 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
115 Nested splices (those inside a [| .. |] quotation bracket), are treated
118 * After typechecking, the bracket [| |] carries
120 a) A mutable list of PendingSplice
121 type PendingSplice = (Name, LHsExpr Id)
123 b) The quoted expression e, *renamed*: (HsExpr Name)
124 The expression e has been typechecked, but the result of
125 that typechecking is discarded.
127 * The brakcet is desugared by DsMeta.dsBracket. It
129 a) Extends the ds_meta environment with the PendingSplices
130 attached to the bracket
132 b) Converts the quoted (HsExpr Name) to a CoreExpr that, when
133 run, will produce a suitable TH expression/type/decl. This
134 is why we leave the *renamed* expression attached to the bracket:
135 the quoted expression should not be decorated with all the goop
136 added by the type checker
138 * Each splice carries a unique Name, called a "splice point", thus
139 ${n}(e). The name is initialised to an (Unqual "splice") when the
140 splice is created; the renamer gives it a unique.
142 * When the type checker type-checks a nested splice ${n}(e), it
144 - adds the typechecked expression (of type (HsExpr Id))
145 as a pending splice to the enclosing bracket
146 - returns something non-committal
147 Eg for [| f ${n}(g x) |], the typechecker
148 - attaches the typechecked term (g x) to the pending splices for n
150 - returns a non-committal type \alpha.
151 Remember that the bracket discards the typechecked term altogether
153 * When DsMeta (used to desugar the body of the bracket) comes across
154 a splice, it looks up the splice's Name, n, in the ds_meta envt,
155 to find an (HsExpr Id) that should be substituted for the splice;
156 it just desugars it to get a CoreExpr (DsMeta.repSplice).
159 Source: f = [| Just $(g 3) |]
160 The [| |] part is a HsBracket
162 Typechecked: f = [| Just ${s7}(g 3) |]{s7 = g Int 3}
163 The [| |] part is a HsBracketOut, containing *renamed*
164 (not typechecked) expression
165 The "s7" is the "splice point"; the (g Int 3) part
166 is a typechecked expression
168 Desugared: f = do { s7 <- g Int 3
169 ; return (ConE "Data.Maybe.Just" s7) }
172 Note [Template Haskell state diagram]
173 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
174 Here are the ThStages, s, their corresponding level numbers
175 (the result of (thLevel s)), and their state transitions.
177 ----------- $ ------------ $
178 | Comp | ---------> | Splice | -----|
180 ----------- ------------
182 $ | | [||] $ | | [||]
184 -------------- ----------------
185 | Brack Comp | | Brack Splice |
187 -------------- ----------------
189 * Normal top-level declarations start in state Comp
191 Annotations start in state Splice, since they are
192 treated very like a splice (only without a '$')
194 * Code compiled in state Splice (and only such code)
195 will be *run at compile time*, with the result replacing
198 * The original paper used level -1 instead of 0, etc.
200 * The original paper did not allow a splice within a
201 splice, but there is no reason not to. This is the
202 $ transition in the top right.
204 Note [Template Haskell levels]
205 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
206 * Imported things are impLevel (= 0)
208 * In GHCi, variables bound by a previous command are treated
209 as impLevel, because we have bytecode for them.
211 * Variables are bound at the "current level"
213 * The current level starts off at outerLevel (= 1)
215 * The level is decremented by splicing $(..)
216 incremented by brackets [| |]
217 incremented by name-quoting 'f
219 When a variable is used, we compare
220 bind: binding level, and
221 use: current level at usage site
224 bind > use Always error (bound later than used)
227 bind = use Always OK (bound same stage as used)
228 [| \x -> $(f [| x |]) |]
230 bind < use Inside brackets, it depends
234 For (bind < use) inside brackets, there are three cases:
235 - Imported things OK f = [| map |]
236 - Top-level things OK g = [| f |]
237 - Non-top-level Only if there is a liftable instance
238 h = \(x:Int) -> [| x |]
240 See Note [What is a top-level Id?]
244 A quoted name 'n is a bit like a quoted expression [| n |], except that we
245 have no cross-stage lifting (c.f. TcExpr.thBrackId). So, after incrementing
246 the use-level to account for the brackets, the cases are:
255 See Note [What is a top-level Id?] in TcEnv. Examples:
257 f 'map -- OK; also for top-level defns of this module
259 \x. f 'x -- Not ok (whereas \x. f [| x |] might have been ok, by
260 -- cross-stage lifting
262 \y. [| \x. $(f 'y) |] -- Not ok (same reason)
264 [| \x. $(f 'x) |] -- OK
267 Note [What is a top-level Id?]
268 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
269 In the level-control criteria above, we need to know what a "top level Id" is.
270 There are three kinds:
271 * Imported from another module (GlobalId, ExternalName)
272 * Bound at the top level of this module (ExternalName)
273 * In GHCi, bound by a previous stmt (GlobalId)
274 It's strange that there is no one criterion tht picks out all three, but that's
275 how it is right now. (The obvious thing is to give an ExternalName to GHCi Ids
276 bound in an earlier Stmt, but what module would you choose? See
277 Note [Interactively-bound Ids in GHCi] in TcRnDriver.)
279 The predicate we use is TcEnv.thTopLevelId.
282 %************************************************************************
284 \subsection{Main interface + stubs for the non-GHCI case
286 %************************************************************************
289 tcBracket :: HsBracket Name -> TcRhoType -> TcM (LHsExpr TcId)
290 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
291 tcSpliceExpr :: HsSplice Name -> TcRhoType -> TcM (HsExpr TcId)
292 kcSpliceType :: HsSplice Name -> FreeVars -> TcM (HsType Name, TcKind)
293 -- None of these functions add constraints to the LIE
295 lookupThName_maybe :: TH.Name -> TcM (Maybe Name)
297 runQuasiQuoteExpr :: HsQuasiQuote RdrName -> RnM (LHsExpr RdrName)
298 runQuasiQuotePat :: HsQuasiQuote RdrName -> RnM (LPat RdrName)
299 runQuasiQuoteType :: HsQuasiQuote RdrName -> RnM (LHsType RdrName)
300 runQuasiQuoteDecl :: HsQuasiQuote RdrName -> RnM [LHsDecl RdrName]
302 runAnnotation :: CoreAnnTarget -> LHsExpr Name -> TcM Annotation
305 tcBracket x _ = pprPanic "Cant do tcBracket without GHCi" (ppr x)
306 tcSpliceExpr e = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
307 tcSpliceDecls x = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr x)
308 kcSpliceType x fvs = pprPanic "Cant do kcSpliceType without GHCi" (ppr x)
310 lookupThName_maybe n = pprPanic "Cant do lookupThName_maybe without GHCi" (ppr n)
312 runQuasiQuoteExpr q = pprPanic "Cant do runQuasiQuoteExpr without GHCi" (ppr q)
313 runQuasiQuotePat q = pprPanic "Cant do runQuasiQuotePat without GHCi" (ppr q)
314 runQuasiQuoteType q = pprPanic "Cant do runQuasiQuoteType without GHCi" (ppr q)
315 runQuasiQuoteDecl q = pprPanic "Cant do runQuasiQuoteDecl without GHCi" (ppr q)
316 runAnnotation _ q = pprPanic "Cant do runAnnotation without GHCi" (ppr q)
320 %************************************************************************
322 \subsection{Quoting an expression}
324 %************************************************************************
328 -- See Note [How brackets and nested splices are handled]
329 tcBracket brack res_ty
330 = addErrCtxt (hang (ptext (sLit "In the Template Haskell quotation"))
332 do { -- Check for nested brackets
333 cur_stage <- getStage
334 ; checkTc (not (isBrackStage cur_stage)) illegalBracket
336 -- Brackets are desugared to code that mentions the TH package
339 -- Typecheck expr to make sure it is valid,
340 -- but throw away the results. We'll type check
341 -- it again when we actually use it.
342 ; pending_splices <- newMutVar []
343 ; lie_var <- getConstraintVar
344 ; let brack_stage = Brack cur_stage pending_splices lie_var
346 -- We want to check that there aren't any constraints that
347 -- can't be satisfied (e.g. Show Foo, where Foo has no Show
348 -- instance), but we aren't otherwise interested in the
349 -- results. Nor do we care about ambiguous dictionaries etc.
350 -- We will type check this bracket again at its usage site.
352 -- We build a single implication constraint with a BracketSkol;
353 -- that in turn tells simplifyCheck to report only definite
355 ; (_,lie) <- captureConstraints $
356 newImplication BracketSkol [] [] $
357 setStage brack_stage $
358 do { meta_ty <- tc_bracket cur_stage brack
359 ; unifyType meta_ty res_ty }
361 -- It's best to simplify the constraint now, even though in
362 -- principle some later unification might be useful for it,
363 -- because we don't want these essentially-junk TH implication
364 -- contraints floating around nested inside other constraints
365 -- See for example Trac #4949
366 ; _ <- simplifyTop lie
368 -- Return the original expression, not the type-decorated one
369 ; pendings <- readMutVar pending_splices
370 ; return (noLoc (HsBracketOut brack pendings)) }
372 tc_bracket :: ThStage -> HsBracket Name -> TcM TcType
373 tc_bracket outer_stage (VarBr name) -- Note [Quoting names]
374 = do { thing <- tcLookup name
376 AGlobal _ -> return ()
377 ATcId { tct_level = bind_lvl, tct_id = id }
378 | thTopLevelId id -- C.f TcExpr.checkCrossStageLifting
381 -> do { checkTc (thLevel outer_stage + 1 == bind_lvl)
382 (quotedNameStageErr name) }
383 _ -> pprPanic "th_bracket" (ppr name)
385 ; tcMetaTy nameTyConName -- Result type is Var (not Q-monadic)
388 tc_bracket _ (ExpBr expr)
389 = do { any_ty <- newFlexiTyVarTy openTypeKind
390 ; _ <- tcMonoExprNC expr any_ty -- NC for no context; tcBracket does that
391 ; tcMetaTy expQTyConName }
392 -- Result type is ExpQ (= Q Exp)
394 tc_bracket _ (TypBr typ)
395 = do { _ <- tcHsSigTypeNC ThBrackCtxt typ
396 ; tcMetaTy typeQTyConName }
397 -- Result type is Type (= Q Typ)
399 tc_bracket _ (DecBrG decls)
400 = do { _ <- tcTopSrcDecls emptyModDetails decls
401 -- Typecheck the declarations, dicarding the result
402 -- We'll get all that stuff later, when we splice it in
404 -- Top-level declarations in the bracket get unqualified names
405 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
407 ; tcMetaTy decsQTyConName } -- Result type is Q [Dec]
409 tc_bracket _ (PatBr pat)
410 = do { any_ty <- newFlexiTyVarTy openTypeKind
411 ; _ <- tcPat ThPatQuote pat any_ty $
413 ; tcMetaTy patQTyConName }
414 -- Result type is PatQ (= Q Pat)
416 tc_bracket _ (DecBrL _)
417 = panic "tc_bracket: Unexpected DecBrL"
419 quotedNameStageErr :: Name -> SDoc
421 = sep [ ptext (sLit "Stage error: the non-top-level quoted name") <+> ppr (VarBr v)
422 , ptext (sLit "must be used at the same stage at which is is bound")]
426 %************************************************************************
428 \subsection{Splicing an expression}
430 %************************************************************************
433 tcSpliceExpr (HsSplice name expr) res_ty
434 = setSrcSpan (getLoc expr) $ do
437 Splice -> tcTopSplice expr res_ty ;
438 Comp -> tcTopSplice expr res_ty ;
440 Brack pop_stage ps_var lie_var -> do
442 -- See Note [How brackets and nested splices are handled]
443 -- A splice inside brackets
444 -- NB: ignore res_ty, apart from zapping it to a mono-type
445 -- e.g. [| reverse $(h 4) |]
446 -- Here (h 4) :: Q Exp
447 -- but $(h 4) :: forall a.a i.e. anything!
449 { meta_exp_ty <- tcMetaTy expQTyConName
450 ; expr' <- setStage pop_stage $
451 setConstraintVar lie_var $
452 tcMonoExpr expr meta_exp_ty
454 -- Write the pending splice into the bucket
455 ; ps <- readMutVar ps_var
456 ; writeMutVar ps_var ((name,expr') : ps)
458 ; return (panic "tcSpliceExpr") -- The returned expression is ignored
461 tcTopSplice :: LHsExpr Name -> TcRhoType -> TcM (HsExpr Id)
462 -- Note [How top-level splices are handled]
463 tcTopSplice expr res_ty
464 = do { meta_exp_ty <- tcMetaTy expQTyConName
466 -- Typecheck the expression
467 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_exp_ty)
469 -- Run the expression
470 ; expr2 <- runMetaE zonked_q_expr
471 ; showSplice "expression" expr (ppr expr2)
473 -- Rename it, but bale out if there are errors
474 -- otherwise the type checker just gives more spurious errors
475 ; addErrCtxt (spliceResultDoc expr) $ do
476 { (exp3, _fvs) <- checkNoErrs (rnLExpr expr2)
478 ; exp4 <- tcMonoExpr exp3 res_ty
479 ; return (unLoc exp4) } }
481 spliceResultDoc :: LHsExpr Name -> SDoc
483 = sep [ ptext (sLit "In the result of the splice:")
484 , nest 2 (char '$' <> pprParendExpr expr)
485 , ptext (sLit "To see what the splice expanded to, use -ddump-splices")]
488 tcTopSpliceExpr :: TcM (LHsExpr Id) -> TcM (LHsExpr Id)
489 -- Note [How top-level splices are handled]
490 -- Type check an expression that is the body of a top-level splice
491 -- (the caller will compile and run it)
492 -- Note that set the level to Splice, regardless of the original level,
493 -- before typechecking the expression. For example:
494 -- f x = $( ...$(g 3) ... )
495 -- The recursive call to tcMonoExpr will simply expand the
496 -- inner escape before dealing with the outer one
498 tcTopSpliceExpr tc_action
499 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
500 -- if the type checker fails!
502 do { -- Typecheck the expression
503 (expr', lie) <- captureConstraints tc_action
505 -- Solve the constraints
506 ; const_binds <- simplifyTop lie
508 -- Zonk it and tie the knot of dictionary bindings
509 ; zonkTopLExpr (mkHsDictLet (EvBinds const_binds) expr') }
513 %************************************************************************
517 %************************************************************************
519 Very like splicing an expression, but we don't yet share code.
522 kcSpliceType splice@(HsSplice name hs_expr) fvs
523 = setSrcSpan (getLoc hs_expr) $ do
526 Splice -> kcTopSpliceType hs_expr ;
527 Comp -> kcTopSpliceType hs_expr ;
529 Brack pop_level ps_var lie_var -> do
530 -- See Note [How brackets and nested splices are handled]
531 -- A splice inside brackets
532 { meta_ty <- tcMetaTy typeQTyConName
533 ; expr' <- setStage pop_level $
534 setConstraintVar lie_var $
535 tcMonoExpr hs_expr meta_ty
537 -- Write the pending splice into the bucket
538 ; ps <- readMutVar ps_var
539 ; writeMutVar ps_var ((name,expr') : ps)
541 -- e.g. [| f (g :: Int -> $(h 4)) |]
542 -- Here (h 4) :: Q Type
543 -- but $(h 4) :: a i.e. any type, of any kind
546 ; return (HsSpliceTy splice fvs kind, kind)
549 kcTopSpliceType :: LHsExpr Name -> TcM (HsType Name, TcKind)
550 -- Note [How top-level splices are handled]
552 = do { meta_ty <- tcMetaTy typeQTyConName
554 -- Typecheck the expression
555 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_ty)
557 -- Run the expression
558 ; hs_ty2 <- runMetaT zonked_q_expr
559 ; showSplice "type" expr (ppr hs_ty2)
561 -- Rename it, but bale out if there are errors
562 -- otherwise the type checker just gives more spurious errors
563 ; addErrCtxt (spliceResultDoc expr) $ do
564 { let doc = ptext (sLit "In the spliced type") <+> ppr hs_ty2
565 ; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)
566 ; (ty4, kind) <- kcLHsType hs_ty3
567 ; return (unLoc ty4, kind) }}
570 %************************************************************************
572 \subsection{Splicing an expression}
574 %************************************************************************
577 -- Note [How top-level splices are handled]
578 -- Always at top level
579 -- Type sig at top of file:
580 -- tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
582 = do { list_q <- tcMetaTy decsQTyConName -- Q [Dec]
583 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr list_q)
585 -- Run the expression
586 ; decls <- runMetaD zonked_q_expr
587 ; showSplice "declarations" expr
588 (ppr (getLoc expr) $$ (vcat (map ppr decls)))
594 %************************************************************************
598 %************************************************************************
601 runAnnotation target expr = do
602 -- Find the classes we want instances for in order to call toAnnotationWrapper
604 data_class <- tcLookupClass dataClassName
605 to_annotation_wrapper_id <- tcLookupId toAnnotationWrapperName
607 -- Check the instances we require live in another module (we want to execute it..)
608 -- and check identifiers live in other modules using TH stage checks. tcSimplifyStagedExpr
609 -- also resolves the LIE constraints to detect e.g. instance ambiguity
610 zonked_wrapped_expr' <- tcTopSpliceExpr $
611 do { (expr', expr_ty) <- tcInferRhoNC expr
612 -- We manually wrap the typechecked expression in a call to toAnnotationWrapper
613 -- By instantiating the call >here< it gets registered in the
614 -- LIE consulted by tcTopSpliceExpr
615 -- and hence ensures the appropriate dictionary is bound by const_binds
616 ; wrapper <- instCall AnnOrigin [expr_ty] [mkClassPred data_class [expr_ty]]
617 ; let specialised_to_annotation_wrapper_expr
618 = L loc (HsWrap wrapper (HsVar to_annotation_wrapper_id))
619 ; return (L loc (HsApp specialised_to_annotation_wrapper_expr expr')) }
621 -- Run the appropriately wrapped expression to get the value of
622 -- the annotation and its dictionaries. The return value is of
623 -- type AnnotationWrapper by construction, so this conversion is
625 flip runMetaAW zonked_wrapped_expr' $ \annotation_wrapper ->
626 case annotation_wrapper of
627 AnnotationWrapper value | let serialized = toSerialized serializeWithData value ->
628 -- Got the value and dictionaries: build the serialized value and
629 -- call it a day. We ensure that we seq the entire serialized value
630 -- in order that any errors in the user-written code for the
631 -- annotation are exposed at this point. This is also why we are
632 -- doing all this stuff inside the context of runMeta: it has the
633 -- facilities to deal with user error in a meta-level expression
634 seqSerialized serialized `seq` Annotation {
636 ann_value = serialized
641 %************************************************************************
645 %************************************************************************
647 Note [Quasi-quote overview]
648 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
649 The GHC "quasi-quote" extension is described by Geoff Mainland's paper
650 "Why it's nice to be quoted: quasiquoting for Haskell" (Haskell
655 and the arbitrary string "stuff" gets parsed by the parser 'p', whose
656 type should be Language.Haskell.TH.Quote.QuasiQuoter. 'p' must be
657 defined in another module, because we are going to run it here. It's
658 a bit like a TH splice:
661 However, you can do this in patterns as well as terms. Becuase of this,
662 the splice is run by the *renamer* rather than the type checker.
664 %************************************************************************
666 \subsubsection{Quasiquotation}
668 %************************************************************************
670 See Note [Quasi-quote overview] in TcSplice.
673 runQuasiQuote :: Outputable hs_syn
674 => HsQuasiQuote RdrName -- Contains term of type QuasiQuoter, and the String
675 -> Name -- Of type QuasiQuoter -> String -> Q th_syn
676 -> Name -- Name of th_syn type
677 -> MetaOps th_syn hs_syn
679 runQuasiQuote (HsQuasiQuote quoter q_span quote) quote_selector meta_ty meta_ops
680 = do { -- Drop the leading "$" from the quoter name, if present
681 -- This is old-style syntax, now deprecated
682 -- NB: when removing this backward-compat, remove
683 -- the matching code in Lexer.x (around line 310)
684 let occ_str = occNameString (rdrNameOcc quoter)
685 ; quoter <- ASSERT( not (null occ_str) ) -- Lexer ensures this
686 if head occ_str /= '$' then return quoter
687 else do { addWarn (deprecatedDollar quoter)
688 ; return (mkRdrUnqual (mkVarOcc (tail occ_str))) }
690 ; quoter' <- lookupOccRn quoter
691 -- We use lookupOcc rather than lookupGlobalOcc because in the
692 -- erroneous case of \x -> [x| ...|] we get a better error message
693 -- (stage restriction rather than out of scope).
695 ; when (isUnboundName quoter') failM
696 -- If 'quoter' is not in scope, proceed no further
697 -- The error message was generated by lookupOccRn, but it then
698 -- succeeds with an "unbound name", which makes the subsequent
699 -- attempt to run the quote fail in a confusing way
701 -- Check that the quoter is not locally defined, otherwise the TH
702 -- machinery will not be able to run the quasiquote.
703 ; this_mod <- getModule
704 ; let is_local = nameIsLocalOrFrom this_mod quoter'
705 ; checkTc (not is_local) (quoteStageError quoter')
707 ; traceTc "runQQ" (ppr quoter <+> ppr is_local)
709 -- Build the expression
710 ; let quoterExpr = L q_span $! HsVar $! quoter'
711 ; let quoteExpr = L q_span $! HsLit $! HsString quote
712 ; let expr = L q_span $
714 HsApp (L q_span (HsVar quote_selector)) quoterExpr) quoteExpr
715 ; meta_exp_ty <- tcMetaTy meta_ty
717 -- Typecheck the expression
718 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_exp_ty)
720 -- Run the expression
721 ; result <- runMetaQ meta_ops zonked_q_expr
722 ; showSplice (mt_desc meta_ops) quoteExpr (ppr result)
726 runQuasiQuoteExpr qq = runQuasiQuote qq quoteExpName expQTyConName exprMetaOps
727 runQuasiQuotePat qq = runQuasiQuote qq quotePatName patQTyConName patMetaOps
728 runQuasiQuoteType qq = runQuasiQuote qq quoteTypeName typeQTyConName typeMetaOps
729 runQuasiQuoteDecl qq = runQuasiQuote qq quoteDecName decsQTyConName declMetaOps
731 quoteStageError :: Name -> SDoc
732 quoteStageError quoter
733 = sep [ptext (sLit "GHC stage restriction:") <+> ppr quoter,
734 nest 2 (ptext (sLit "is used in a quasiquote, and must be imported, not defined locally"))]
736 deprecatedDollar :: RdrName -> SDoc
737 deprecatedDollar quoter
738 = hang (ptext (sLit "Deprecated syntax:"))
739 2 (ptext (sLit "quasiquotes no longer need a dollar sign:")
744 %************************************************************************
746 \subsection{Running an expression}
748 %************************************************************************
751 data MetaOps th_syn hs_syn
752 = MT { mt_desc :: String -- Type of beast (expression, type etc)
753 , mt_show :: th_syn -> String -- How to show the th_syn thing
754 , mt_cvt :: SrcSpan -> th_syn -> Either Message hs_syn
755 -- How to convert to hs_syn
758 exprMetaOps :: MetaOps TH.Exp (LHsExpr RdrName)
759 exprMetaOps = MT { mt_desc = "expression", mt_show = TH.pprint, mt_cvt = convertToHsExpr }
761 patMetaOps :: MetaOps TH.Pat (LPat RdrName)
762 patMetaOps = MT { mt_desc = "pattern", mt_show = TH.pprint, mt_cvt = convertToPat }
764 typeMetaOps :: MetaOps TH.Type (LHsType RdrName)
765 typeMetaOps = MT { mt_desc = "type", mt_show = TH.pprint, mt_cvt = convertToHsType }
767 declMetaOps :: MetaOps [TH.Dec] [LHsDecl RdrName]
768 declMetaOps = MT { mt_desc = "declarations", mt_show = TH.pprint, mt_cvt = convertToHsDecls }
771 runMetaAW :: Outputable output
772 => (AnnotationWrapper -> output)
773 -> LHsExpr Id -- Of type AnnotationWrapper
775 runMetaAW k = runMeta False (\_ -> return . Right . k)
776 -- We turn off showing the code in meta-level exceptions because doing so exposes
777 -- the toAnnotationWrapper function that we slap around the users code
780 runMetaQ :: Outputable hs_syn
781 => MetaOps th_syn hs_syn
784 runMetaQ (MT { mt_show = show_th, mt_cvt = cvt }) expr
785 = runMeta True run_and_cvt expr
787 run_and_cvt expr_span hval
788 = do { th_result <- TH.runQ hval
789 ; traceTc "Got TH result:" (text (show_th th_result))
790 ; return (cvt expr_span th_result) }
792 runMetaE :: LHsExpr Id -- Of type (Q Exp)
793 -> TcM (LHsExpr RdrName)
794 runMetaE = runMetaQ exprMetaOps
796 runMetaT :: LHsExpr Id -- Of type (Q Type)
797 -> TcM (LHsType RdrName)
798 runMetaT = runMetaQ typeMetaOps
800 runMetaD :: LHsExpr Id -- Of type Q [Dec]
801 -> TcM [LHsDecl RdrName]
802 runMetaD = runMetaQ declMetaOps
805 runMeta :: (Outputable hs_syn)
806 => Bool -- Whether code should be printed in the exception message
807 -> (SrcSpan -> x -> TcM (Either Message hs_syn)) -- How to run x
808 -> LHsExpr Id -- Of type x; typically x = Q TH.Exp, or something like that
809 -> TcM hs_syn -- Of type t
810 runMeta show_code run_and_convert expr
811 = do { traceTc "About to run" (ppr expr)
814 ; ds_expr <- initDsTc (dsLExpr expr)
815 -- Compile and link it; might fail if linking fails
816 ; hsc_env <- getTopEnv
817 ; src_span <- getSrcSpanM
818 ; either_hval <- tryM $ liftIO $
819 HscMain.hscCompileCoreExpr hsc_env src_span ds_expr
820 ; case either_hval of {
821 Left exn -> failWithTc (mk_msg "compile and link" exn) ;
824 { -- Coerce it to Q t, and run it
826 -- Running might fail if it throws an exception of any kind (hence tryAllM)
827 -- including, say, a pattern-match exception in the code we are running
829 -- We also do the TH -> HS syntax conversion inside the same
830 -- exception-cacthing thing so that if there are any lurking
831 -- exceptions in the data structure returned by hval, we'll
832 -- encounter them inside the try
834 -- See Note [Exceptions in TH]
835 let expr_span = getLoc expr
836 ; either_tval <- tryAllM $
837 setSrcSpan expr_span $ -- Set the span so that qLocation can
838 -- see where this splice is
839 do { mb_result <- run_and_convert expr_span (unsafeCoerce# hval)
841 Left err -> failWithTc err
842 Right result -> do { traceTc "Got HsSyn result:" (ppr result)
843 ; return $! result } }
845 ; case either_tval of
847 Left se -> case fromException se of
848 Just IOEnvFailure -> failM -- Error already in Tc monad
849 _ -> failWithTc (mk_msg "run" se) -- Exception
852 mk_msg s exn = vcat [text "Exception when trying to" <+> text s <+> text "compile-time code:",
853 nest 2 (text (Panic.showException exn)),
854 if show_code then nest 2 (text "Code:" <+> ppr expr) else empty]
857 Note [Exceptions in TH]
858 ~~~~~~~~~~~~~~~~~~~~~~~
859 Supppose we have something like this
863 f n | n>3 = fail "Too many declarations"
866 The 'fail' is a user-generated failure, and should be displayed as a
867 perfectly ordinary compiler error message, not a panic or anything
868 like that. Here's how it's processed:
870 * 'fail' is the monad fail. The monad instance for Q in TH.Syntax
871 effectively transforms (fail s) to
872 qReport True s >> fail
873 where 'qReport' comes from the Quasi class and fail from its monad
876 * The TcM monad is an instance of Quasi (see TcSplice), and it implements
877 (qReport True s) by using addErr to add an error message to the bag of errors.
878 The 'fail' in TcM raises an IOEnvFailure exception
880 * So, when running a splice, we catch all exceptions; then for
881 - an IOEnvFailure exception, we assume the error is already
882 in the error-bag (above)
883 - other errors, we add an error to the bag
887 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
890 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
891 qNewName s = do { u <- newUnique
893 ; return (TH.mkNameU s i) }
895 qReport True msg = addErr (text msg)
896 qReport False msg = addReport (text msg) empty
898 qLocation = do { m <- getModule
900 ; return (TH.Loc { TH.loc_filename = unpackFS (srcSpanFile l)
901 , TH.loc_module = moduleNameString (moduleName m)
902 , TH.loc_package = packageIdString (modulePackageId m)
903 , TH.loc_start = (srcSpanStartLine l, srcSpanStartCol l)
904 , TH.loc_end = (srcSpanEndLine l, srcSpanEndCol l) }) }
907 qClassInstances = lookupClassInstances
909 -- For qRecover, discard error messages if
910 -- the recovery action is chosen. Otherwise
911 -- we'll only fail higher up. c.f. tryTcLIE_
912 qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main
914 Just val -> do { addMessages msgs -- There might be warnings
916 Nothing -> recover -- Discard all msgs
919 qRunIO io = liftIO io
923 %************************************************************************
925 \subsection{Errors and contexts}
927 %************************************************************************
930 showSplice :: String -> LHsExpr Name -> SDoc -> TcM ()
931 -- Note that 'before' is *renamed* but not *typechecked*
932 -- Reason (a) less typechecking crap
933 -- (b) data constructors after type checking have been
934 -- changed to their *wrappers*, and that makes them
935 -- print always fully qualified
936 showSplice what before after
937 = do { loc <- getSrcSpanM
938 ; traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
939 nest 2 (sep [nest 2 (ppr before),
943 illegalBracket :: SDoc
944 illegalBracket = ptext (sLit "Template Haskell brackets cannot be nested (without intervening splices)")
949 %************************************************************************
953 %************************************************************************
956 lookupClassInstances :: TH.Name -> [TH.Type] -> TcM [TH.ClassInstance]
957 lookupClassInstances c ts
958 = do { loc <- getSrcSpanM
959 ; case convertToHsPred loc (TH.ClassP c ts) of {
960 Left msg -> failWithTc msg;
962 { rn_pred <- rnLPred doc rdr_pred -- Rename
963 ; kc_pred <- kcHsLPred rn_pred -- Kind check
964 ; ClassP cls tys <- dsHsLPred kc_pred -- Type check
966 -- Now look up instances
967 ; inst_envs <- tcGetInstEnvs
968 ; let (matches, unifies) = lookupInstEnv inst_envs cls tys
969 ; mapM reifyClassInstance (map fst matches ++ unifies) } } }
971 doc = ptext (sLit "TcSplice.classInstances")
975 %************************************************************************
979 %************************************************************************
983 reify :: TH.Name -> TcM TH.Info
985 = do { name <- lookupThName th_name
986 ; thing <- tcLookupTh name
987 -- ToDo: this tcLookup could fail, which would give a
988 -- rather unhelpful error message
989 ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
993 ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
994 ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
995 ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
996 ppr_ns _ = panic "reify/ppr_ns"
998 lookupThName :: TH.Name -> TcM Name
999 lookupThName th_name = do
1000 mb_name <- lookupThName_maybe th_name
1002 Nothing -> failWithTc (notInScope th_name)
1003 Just name -> return name
1005 lookupThName_maybe th_name
1006 = do { names <- mapMaybeM lookup (thRdrNameGuesses th_name)
1007 -- Pick the first that works
1008 -- E.g. reify (mkName "A") will pick the class A in preference to the data constructor A
1009 ; return (listToMaybe names) }
1012 = do { -- Repeat much of lookupOccRn, becase we want
1013 -- to report errors in a TH-relevant way
1014 ; rdr_env <- getLocalRdrEnv
1015 ; case lookupLocalRdrEnv rdr_env rdr_name of
1016 Just name -> return (Just name)
1017 Nothing -> lookupGlobalOccRn_maybe rdr_name }
1019 tcLookupTh :: Name -> TcM TcTyThing
1020 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
1021 -- it gives a reify-related error message on failure, whereas in the normal
1022 -- tcLookup, failure is a bug.
1024 = do { (gbl_env, lcl_env) <- getEnvs
1025 ; case lookupNameEnv (tcl_env lcl_env) name of {
1026 Just thing -> return thing;
1028 { if nameIsLocalOrFrom (tcg_mod gbl_env) name
1029 then -- It's defined in this module
1030 case lookupNameEnv (tcg_type_env gbl_env) name of
1031 Just thing -> return (AGlobal thing)
1032 Nothing -> failWithTc (notInEnv name)
1034 else do -- It's imported
1035 { (eps,hpt) <- getEpsAndHpt
1036 ; dflags <- getDOpts
1037 ; case lookupType dflags hpt (eps_PTE eps) name of
1038 Just thing -> return (AGlobal thing)
1039 Nothing -> do { thing <- tcImportDecl name
1040 ; return (AGlobal thing) }
1041 -- Imported names should always be findable;
1042 -- if not, we fail hard in tcImportDecl
1045 notInScope :: TH.Name -> SDoc
1046 notInScope th_name = quotes (text (TH.pprint th_name)) <+>
1047 ptext (sLit "is not in scope at a reify")
1048 -- Ugh! Rather an indirect way to display the name
1050 notInEnv :: Name -> SDoc
1051 notInEnv name = quotes (ppr name) <+>
1052 ptext (sLit "is not in the type environment at a reify")
1054 ------------------------------
1055 reifyThing :: TcTyThing -> TcM TH.Info
1056 -- The only reason this is monadic is for error reporting,
1057 -- which in turn is mainly for the case when TH can't express
1058 -- some random GHC extension
1060 reifyThing (AGlobal (AnId id))
1061 = do { ty <- reifyType (idType id)
1062 ; fix <- reifyFixity (idName id)
1063 ; let v = reifyName id
1064 ; case idDetails id of
1065 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
1066 _ -> return (TH.VarI v ty Nothing fix)
1069 reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc
1070 reifyThing (AGlobal (AClass cls)) = reifyClass cls
1071 reifyThing (AGlobal (ADataCon dc))
1072 = do { let name = dataConName dc
1073 ; ty <- reifyType (idType (dataConWrapId dc))
1074 ; fix <- reifyFixity name
1075 ; return (TH.DataConI (reifyName name) ty
1076 (reifyName (dataConOrigTyCon dc)) fix)
1079 reifyThing (ATcId {tct_id = id})
1080 = do { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
1081 -- though it may be incomplete
1082 ; ty2 <- reifyType ty1
1083 ; fix <- reifyFixity (idName id)
1084 ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
1086 reifyThing (ATyVar tv ty)
1087 = do { ty1 <- zonkTcType ty
1088 ; ty2 <- reifyType ty1
1089 ; return (TH.TyVarI (reifyName tv) ty2) }
1091 reifyThing (AThing {}) = panic "reifyThing AThing"
1093 ------------------------------
1094 reifyTyCon :: TyCon -> TcM TH.Info
1097 = return (TH.PrimTyConI (reifyName tc) 2 False)
1099 = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc))
1101 = let flavour = reifyFamFlavour tc
1102 tvs = tyConTyVars tc
1105 | isLiftedTypeKind kind = Nothing
1106 | otherwise = Just $ reifyKind kind
1109 TH.FamilyD flavour (reifyName tc) (reifyTyVars tvs) kind')
1111 = do { let (tvs, rhs) = synTyConDefn tc
1112 ; rhs' <- reifyType rhs
1113 ; return (TH.TyConI $
1114 TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs')
1118 = do { cxt <- reifyCxt (tyConStupidTheta tc)
1119 ; let tvs = tyConTyVars tc
1120 ; cons <- mapM (reifyDataCon (mkTyVarTys tvs)) (tyConDataCons tc)
1121 ; let name = reifyName tc
1122 r_tvs = reifyTyVars tvs
1123 deriv = [] -- Don't know about deriving
1124 decl | isNewTyCon tc = TH.NewtypeD cxt name r_tvs (head cons) deriv
1125 | otherwise = TH.DataD cxt name r_tvs cons deriv
1126 ; return (TH.TyConI decl) }
1128 reifyDataCon :: [Type] -> DataCon -> TcM TH.Con
1129 -- For GADTs etc, see Note [Reifying data constructors]
1131 = do { let (tvs, theta, arg_tys, _) = dataConSig dc
1132 subst = mkTopTvSubst (tvs `zip` tys) -- Dicard ex_tvs
1133 (subst', ex_tvs') = mapAccumL substTyVarBndr subst (dropList tys tvs)
1134 theta' = substTheta subst' theta
1135 arg_tys' = substTys subst' arg_tys
1136 stricts = map reifyStrict (dataConStrictMarks dc)
1137 fields = dataConFieldLabels dc
1140 ; r_arg_tys <- reifyTypes arg_tys'
1142 ; let main_con | not (null fields)
1143 = TH.RecC name (zip3 (map reifyName fields) stricts r_arg_tys)
1145 = ASSERT( length arg_tys == 2 )
1146 TH.InfixC (s1,r_a1) name (s2,r_a2)
1148 = TH.NormalC name (stricts `zip` r_arg_tys)
1149 [r_a1, r_a2] = r_arg_tys
1152 ; ASSERT( length arg_tys == length stricts )
1153 if null ex_tvs' && null theta then
1156 { cxt <- reifyCxt theta'
1157 ; return (TH.ForallC (reifyTyVars ex_tvs') cxt main_con) } }
1159 ------------------------------
1160 reifyClass :: Class -> TcM TH.Info
1162 = do { cxt <- reifyCxt theta
1163 ; inst_envs <- tcGetInstEnvs
1164 ; insts <- mapM reifyClassInstance (InstEnv.classInstances inst_envs cls)
1165 ; ops <- mapM reify_op op_stuff
1166 ; let dec = TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) fds' ops
1167 ; return (TH.ClassI dec insts ) }
1169 (tvs, fds, theta, _, _, op_stuff) = classExtraBigSig cls
1170 fds' = map reifyFunDep fds
1171 reify_op (op, _) = do { ty <- reifyType (idType op)
1172 ; return (TH.SigD (reifyName op) ty) }
1174 ------------------------------
1175 reifyClassInstance :: Instance -> TcM TH.ClassInstance
1176 reifyClassInstance i
1177 = do { cxt <- reifyCxt theta
1178 ; thtypes <- reifyTypes types
1179 ; return $ (TH.ClassInstance {
1180 TH.ci_tvs = reifyTyVars tvs,
1182 TH.ci_tys = thtypes,
1183 TH.ci_cls = reifyName cls,
1184 TH.ci_dfun = reifyName (is_dfun i) }) }
1186 (tvs, theta, cls, types) = instanceHead i
1188 ------------------------------
1189 reifyType :: TypeRep.Type -> TcM TH.Type
1190 -- Monadic only because of failure
1191 reifyType ty@(ForAllTy _ _) = reify_for_all ty
1192 reifyType ty@(PredTy {} `FunTy` _) = reify_for_all ty -- Types like ((?x::Int) => Char -> Char)
1193 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
1194 reifyType (TyConApp tc tys) = reify_tc_app tc tys -- Do not expand type synonyms here
1195 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
1196 reifyType (FunTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
1197 reifyType ty@(PredTy {}) = pprPanic "reifyType PredTy" (ppr ty)
1199 reify_for_all :: TypeRep.Type -> TcM TH.Type
1201 = do { cxt' <- reifyCxt cxt;
1202 ; tau' <- reifyType tau
1203 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
1205 (tvs, cxt, tau) = tcSplitSigmaTy ty
1207 reifyTypes :: [Type] -> TcM [TH.Type]
1208 reifyTypes = mapM reifyType
1210 reifyKind :: Kind -> TH.Kind
1212 = let (kis, ki') = splitKindFunTys ki
1213 kis_rep = map reifyKind kis
1214 ki'_rep = reifyNonArrowKind ki'
1216 foldr TH.ArrowK ki'_rep kis_rep
1218 reifyNonArrowKind k | isLiftedTypeKind k = TH.StarK
1219 | otherwise = pprPanic "Exotic form of kind"
1222 reifyCxt :: [PredType] -> TcM [TH.Pred]
1223 reifyCxt = mapM reifyPred
1225 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
1226 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
1228 reifyFamFlavour :: TyCon -> TH.FamFlavour
1229 reifyFamFlavour tc | isSynFamilyTyCon tc = TH.TypeFam
1230 | isFamilyTyCon tc = TH.DataFam
1232 = panic "TcSplice.reifyFamFlavour: not a type family"
1234 reifyTyVars :: [TyVar] -> [TH.TyVarBndr]
1235 reifyTyVars = map reifyTyVar
1237 reifyTyVar tv | isLiftedTypeKind kind = TH.PlainTV name
1238 | otherwise = TH.KindedTV name (reifyKind kind)
1243 reify_tc_app :: TyCon -> [TypeRep.Type] -> TcM TH.Type
1245 = do { tys' <- reifyTypes tys
1246 ; return (foldl TH.AppT r_tc tys') }
1249 r_tc | isTupleTyCon tc = TH.TupleT n_tys
1250 | tc `hasKey` listTyConKey = TH.ListT
1251 | otherwise = TH.ConT (reifyName tc)
1253 reifyPred :: TypeRep.PredType -> TcM TH.Pred
1254 reifyPred (ClassP cls tys)
1255 = do { tys' <- reifyTypes tys
1256 ; return $ TH.ClassP (reifyName cls) tys' }
1258 reifyPred p@(IParam _ _) = noTH (sLit "implicit parameters") (ppr p)
1259 reifyPred (EqPred ty1 ty2)
1260 = do { ty1' <- reifyType ty1
1261 ; ty2' <- reifyType ty2
1262 ; return $ TH.EqualP ty1' ty2'
1266 ------------------------------
1267 reifyName :: NamedThing n => n -> TH.Name
1269 | isExternalName name = mk_varg pkg_str mod_str occ_str
1270 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
1271 -- Many of the things we reify have local bindings, and
1272 -- NameL's aren't supposed to appear in binding positions, so
1273 -- we use NameU. When/if we start to reify nested things, that
1274 -- have free variables, we may need to generate NameL's for them.
1276 name = getName thing
1277 mod = ASSERT( isExternalName name ) nameModule name
1278 pkg_str = packageIdString (modulePackageId mod)
1279 mod_str = moduleNameString (moduleName mod)
1280 occ_str = occNameString occ
1281 occ = nameOccName name
1282 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
1283 | OccName.isVarOcc occ = TH.mkNameG_v
1284 | OccName.isTcOcc occ = TH.mkNameG_tc
1285 | otherwise = pprPanic "reifyName" (ppr name)
1287 ------------------------------
1288 reifyFixity :: Name -> TcM TH.Fixity
1290 = do { fix <- lookupFixityRn name
1291 ; return (conv_fix fix) }
1293 conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
1294 conv_dir BasicTypes.InfixR = TH.InfixR
1295 conv_dir BasicTypes.InfixL = TH.InfixL
1296 conv_dir BasicTypes.InfixN = TH.InfixN
1298 reifyStrict :: BasicTypes.HsBang -> TH.Strict
1299 reifyStrict bang | isBanged bang = TH.IsStrict
1300 | otherwise = TH.NotStrict
1302 ------------------------------
1303 noTH :: LitString -> SDoc -> TcM a
1304 noTH s d = failWithTc (hsep [ptext (sLit "Can't represent") <+> ptext s <+>
1305 ptext (sLit "in Template Haskell:"),
1309 Note [Reifying data constructors]
1310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1311 Template Haskell syntax is rich enough to express even GADTs,
1312 provided we do so in the equality-predicate form. So a GADT
1319 will appear in TH syntax like this
1321 data T a = forall b. (a ~ [b]) => MkT1 b