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, runAnnotation ) where
21 #include "HsVersions.h"
25 -- These imports are the reason that TcSplice
26 -- is very high up the module hierarchy
62 import DsMonad hiding (Splice)
74 import qualified Language.Haskell.TH as TH
75 -- THSyntax gives access to internal functions and data types
76 import qualified Language.Haskell.TH.Syntax as TH
79 -- Because GHC.Desugar might not be in the base library of the bootstrapping compiler
80 import GHC.Desugar ( AnnotationWrapper(..) )
83 import GHC.Exts ( unsafeCoerce#, Int#, Int(..) )
84 import System.IO.Error
87 Note [How top-level splices are handled]
88 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
89 Top-level splices (those not inside a [| .. |] quotation bracket) are handled
90 very straightforwardly:
92 1. tcTopSpliceExpr: typecheck the body e of the splice $(e)
94 2. runMetaT: desugar, compile, run it, and convert result back to
95 HsSyn RdrName (of the appropriate flavour, eg HsType RdrName,
98 3. treat the result as if that's what you saw in the first place
99 e.g for HsType, rename and kind-check
100 for HsExpr, rename and type-check
102 (The last step is different for decls, becuase they can *only* be
103 top-level: we return the result of step 2.)
105 Note [How brackets and nested splices are handled]
106 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107 Nested splices (those inside a [| .. |] quotation bracket), are treated
110 * After typechecking, the bracket [| |] carries
112 a) A mutable list of PendingSplice
113 type PendingSplice = (Name, LHsExpr Id)
115 b) The quoted expression e, *renamed*: (HsExpr Name)
116 The expression e has been typechecked, but the result of
117 that typechecking is discarded.
119 * The brakcet is desugared by DsMeta.dsBracket. It
121 a) Extends the ds_meta environment with the PendingSplices
122 attached to the bracket
124 b) Converts the quoted (HsExpr Name) to a CoreExpr that, when
125 run, will produce a suitable TH expression/type/decl. This
126 is why we leave the *renamed* expression attached to the bracket:
127 the quoted expression should not be decorated with all the goop
128 added by the type checker
130 * Each splice carries a unique Name, called a "splice point", thus
131 ${n}(e). The name is initialised to an (Unqual "splice") when the
132 splice is created; the renamer gives it a unique.
134 * When the type checker type-checks a nested splice ${n}(e), it
136 - adds the typechecked expression (of type (HsExpr Id))
137 as a pending splice to the enclosing bracket
138 - returns something non-committal
139 Eg for [| f ${n}(g x) |], the typechecker
140 - attaches the typechecked term (g x) to the pending splices for n
142 - returns a non-committal type \alpha.
143 Remember that the bracket discards the typechecked term altogether
145 * When DsMeta (used to desugar the body of the bracket) comes across
146 a splice, it looks up the splice's Name, n, in the ds_meta envt,
147 to find an (HsExpr Id) that should be substituted for the splice;
148 it just desugars it to get a CoreExpr (DsMeta.repSplice).
151 Source: f = [| Just $(g 3) |]
152 The [| |] part is a HsBracket
154 Typechecked: f = [| Just ${s7}(g 3) |]{s7 = g Int 3}
155 The [| |] part is a HsBracketOut, containing *renamed*
156 (not typechecked) expression
157 The "s7" is the "splice point"; the (g Int 3) part
158 is a typechecked expression
160 Desugared: f = do { s7 <- g Int 3
161 ; return (ConE "Data.Maybe.Just" s7) }
164 Note [Template Haskell state diagram]
165 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
166 Here are the ThStages, s, their corresponding level numbers
167 (the result of (thLevel s)), and their state transitions.
169 ----------- $ ------------ $
170 | Comp | ---------> | Splice | -----|
172 ----------- ------------
174 $ | | [||] $ | | [||]
176 -------------- ----------------
177 | Brack Comp | | Brack Splice |
179 -------------- ----------------
181 * Normal top-level declarations start in state Comp
183 Annotations start in state Splice, since they are
184 treated very like a splice (only without a '$')
186 * Code compiled in state Splice (and only such code)
187 will be *run at compile time*, with the result replacing
190 * The original paper used level -1 instead of 0, etc.
192 * The original paper did not allow a splice within a
193 splice, but there is no reason not to. This is the
194 $ transition in the top right.
196 Note [Template Haskell levels]
197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
198 * Imported things are impLevel (= 0)
200 * In GHCi, variables bound by a previous command are treated
201 as impLevel, because we have bytecode for them.
203 * Variables are bound at the "current level"
205 * The current level starts off at outerLevel (= 1)
207 * The level is decremented by splicing $(..)
208 incremented by brackets [| |]
209 incremented by name-quoting 'f
211 When a variable is used, we compare
212 bind: binding level, and
213 use: current level at usage site
216 bind > use Always error (bound later than used)
219 bind = use Always OK (bound same stage as used)
220 [| \x -> $(f [| x |]) |]
222 bind < use Inside brackets, it depends
226 For (bind < use) inside brackets, there are three cases:
227 - Imported things OK f = [| map |]
228 - Top-level things OK g = [| f |]
229 - Non-top-level Only if there is a liftable instance
230 h = \(x:Int) -> [| x |]
232 See Note [What is a top-level Id?]
236 A quoted name 'n is a bit like a quoted expression [| n |], except that we
237 have no cross-stage lifting (c.f. TcExpr.thBrackId). So, after incrementing
238 the use-level to account for the brackets, the cases are:
247 See Note [What is a top-level Id?] in TcEnv. Examples:
249 f 'map -- OK; also for top-level defns of this module
251 \x. f 'x -- Not ok (whereas \x. f [| x |] might have been ok, by
252 -- cross-stage lifting
254 \y. [| \x. $(f 'y) |] -- Not ok (same reason)
256 [| \x. $(f 'x) |] -- OK
259 Note [What is a top-level Id?]
260 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261 In the level-control criteria above, we need to know what a "top level Id" is.
262 There are three kinds:
263 * Imported from another module (GlobalId, ExternalName)
264 * Bound at the top level of this module (ExternalName)
265 * In GHCi, bound by a previous stmt (GlobalId)
266 It's strange that there is no one criterion tht picks out all three, but that's
267 how it is right now. (The obvious thing is to give an ExternalName to GHCi Ids
268 bound in an earlier Stmt, but what module would you choose? See
269 Note [Interactively-bound Ids in GHCi] in TcRnDriver.)
271 The predicate we use is TcEnv.thTopLevelId.
274 %************************************************************************
276 \subsection{Main interface + stubs for the non-GHCI case
278 %************************************************************************
281 tcBracket :: HsBracket Name -> BoxyRhoType -> TcM (LHsExpr TcId)
282 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
283 tcSpliceExpr :: HsSplice Name -> BoxyRhoType -> TcM (HsExpr TcId)
284 kcSpliceType :: HsSplice Name -> TcM (HsType Name, TcKind)
285 -- None of these functions add constraints to the LIE
287 lookupThName_maybe :: TH.Name -> TcM (Maybe Name)
289 runQuasiQuoteExpr :: HsQuasiQuote Name -> TcM (LHsExpr RdrName)
290 runQuasiQuotePat :: HsQuasiQuote Name -> TcM (LPat RdrName)
291 runAnnotation :: CoreAnnTarget -> LHsExpr Name -> TcM Annotation
294 tcBracket x _ = pprPanic "Cant do tcBracket without GHCi" (ppr x)
295 tcSpliceExpr e = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
296 tcSpliceDecls x = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr x)
297 kcSpliceType x = pprPanic "Cant do kcSpliceType without GHCi" (ppr x)
299 lookupThName_maybe n = pprPanic "Cant do lookupThName_maybe without GHCi" (ppr n)
301 runQuasiQuoteExpr q = pprPanic "Cant do runQuasiQuoteExpr without GHCi" (ppr q)
302 runQuasiQuotePat q = pprPanic "Cant do runQuasiQuotePat without GHCi" (ppr q)
303 runAnnotation _ q = pprPanic "Cant do runAnnotation without GHCi" (ppr q)
307 %************************************************************************
309 \subsection{Quoting an expression}
311 %************************************************************************
315 -- See Note [How brackets and nested splices are handled]
316 tcBracket brack res_ty
317 = addErrCtxt (hang (ptext (sLit "In the Template Haskell quotation"))
319 do { -- Check for nested brackets
320 cur_stage <- getStage
321 ; checkTc (not (isBrackStage cur_stage)) illegalBracket
323 -- Brackets are desugared to code that mentions the TH package
326 -- Typecheck expr to make sure it is valid,
327 -- but throw away the results. We'll type check
328 -- it again when we actually use it.
329 ; pending_splices <- newMutVar []
330 ; lie_var <- getLIEVar
332 ; (meta_ty, lie) <- setStage (Brack cur_stage pending_splices lie_var)
333 (getLIE (tc_bracket cur_stage brack))
334 ; tcSimplifyBracket lie
336 -- Make the expected type have the right shape
337 ; _ <- boxyUnify meta_ty res_ty
339 -- Return the original expression, not the type-decorated one
340 ; pendings <- readMutVar pending_splices
341 ; return (noLoc (HsBracketOut brack pendings)) }
343 tc_bracket :: ThStage -> HsBracket Name -> TcM TcType
344 tc_bracket outer_stage (VarBr name) -- Note [Quoting names]
345 = do { thing <- tcLookup name
347 AGlobal _ -> return ()
348 ATcId { tct_level = bind_lvl, tct_id = id }
349 | thTopLevelId id -- C.f TcExpr.checkCrossStageLifting
352 -> do { checkTc (thLevel outer_stage + 1 == bind_lvl)
353 (quotedNameStageErr name) }
354 _ -> pprPanic "th_bracket" (ppr name)
356 ; tcMetaTy nameTyConName -- Result type is Var (not Q-monadic)
359 tc_bracket _ (ExpBr expr)
360 = do { any_ty <- newFlexiTyVarTy liftedTypeKind
361 ; _ <- tcMonoExprNC expr any_ty -- NC for no context; tcBracket does that
362 ; tcMetaTy expQTyConName }
363 -- Result type is Expr (= Q Exp)
365 tc_bracket _ (TypBr typ)
366 = do { _ <- tcHsSigTypeNC ThBrackCtxt typ
367 ; tcMetaTy typeQTyConName }
368 -- Result type is Type (= Q Typ)
370 tc_bracket _ (DecBr decls)
371 = do { _ <- tcTopSrcDecls emptyModDetails decls
372 -- Typecheck the declarations, dicarding the result
373 -- We'll get all that stuff later, when we splice it in
375 ; decl_ty <- tcMetaTy decTyConName
376 ; q_ty <- tcMetaTy qTyConName
377 ; return (mkAppTy q_ty (mkListTy decl_ty))
378 -- Result type is Q [Dec]
381 tc_bracket _ (PatBr _)
382 = failWithTc (ptext (sLit "Tempate Haskell pattern brackets are not supported yet"))
384 quotedNameStageErr :: Name -> SDoc
386 = sep [ ptext (sLit "Stage error: the non-top-level quoted name") <+> ppr (VarBr v)
387 , ptext (sLit "must be used at the same stage at which is is bound")]
391 %************************************************************************
393 \subsection{Splicing an expression}
395 %************************************************************************
398 tcSpliceExpr (HsSplice name expr) res_ty
399 = setSrcSpan (getLoc expr) $ do
402 Splice -> tcTopSplice expr res_ty ;
403 Comp -> tcTopSplice expr res_ty ;
405 Brack pop_stage ps_var lie_var -> do
407 -- See Note [How brackets and nested splices are handled]
408 -- A splice inside brackets
409 -- NB: ignore res_ty, apart from zapping it to a mono-type
410 -- e.g. [| reverse $(h 4) |]
411 -- Here (h 4) :: Q Exp
412 -- but $(h 4) :: forall a.a i.e. anything!
415 ; meta_exp_ty <- tcMetaTy expQTyConName
416 ; expr' <- setStage pop_stage $
418 tcMonoExpr expr meta_exp_ty
420 -- Write the pending splice into the bucket
421 ; ps <- readMutVar ps_var
422 ; writeMutVar ps_var ((name,expr') : ps)
424 ; return (panic "tcSpliceExpr") -- The returned expression is ignored
427 tcTopSplice :: LHsExpr Name -> BoxyRhoType -> TcM (HsExpr Id)
428 -- Note [How top-level splices are handled]
429 tcTopSplice expr res_ty
430 = do { meta_exp_ty <- tcMetaTy expQTyConName
432 -- Typecheck the expression
433 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_exp_ty)
435 -- Run the expression
436 ; expr2 <- runMetaE zonked_q_expr
437 ; showSplice "expression" expr (ppr expr2)
439 -- Rename it, but bale out if there are errors
440 -- otherwise the type checker just gives more spurious errors
441 ; addErrCtxt (spliceResultDoc expr) $ do
442 { (exp3, _fvs) <- checkNoErrs (rnLExpr expr2)
444 ; exp4 <- tcMonoExpr exp3 res_ty
445 ; return (unLoc exp4) } }
447 spliceResultDoc :: LHsExpr Name -> SDoc
449 = sep [ ptext (sLit "In the result of the splice:")
450 , nest 2 (char '$' <> pprParendExpr expr)
451 , ptext (sLit "To see what the splice expanded to, use -ddump-splices")]
454 tcTopSpliceExpr :: TcM (LHsExpr Id) -> TcM (LHsExpr Id)
455 -- Note [How top-level splices are handled]
456 -- Type check an expression that is the body of a top-level splice
457 -- (the caller will compile and run it)
458 -- Note that set the level to Splice, regardless of the original level,
459 -- before typechecking the expression. For example:
460 -- f x = $( ...$(g 3) ... )
461 -- The recursive call to tcMonoExpr will simply expand the
462 -- inner escape before dealing with the outer one
464 tcTopSpliceExpr tc_action
465 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
466 -- if the type checker fails!
468 do { -- Typecheck the expression
469 (expr', lie) <- getLIE tc_action
471 -- Solve the constraints
472 ; const_binds <- tcSimplifyTop lie
474 -- Zonk it and tie the knot of dictionary bindings
475 ; zonkTopLExpr (mkHsDictLet const_binds expr') }
479 %************************************************************************
483 %************************************************************************
485 Very like splicing an expression, but we don't yet share code.
488 kcSpliceType (HsSplice name hs_expr)
489 = setSrcSpan (getLoc hs_expr) $ do
492 Splice -> kcTopSpliceType hs_expr ;
493 Comp -> kcTopSpliceType hs_expr ;
495 Brack pop_level ps_var lie_var -> do
496 -- See Note [How brackets and nested splices are handled]
497 -- A splice inside brackets
498 { meta_ty <- tcMetaTy typeQTyConName
499 ; expr' <- setStage pop_level $
501 tcMonoExpr hs_expr meta_ty
503 -- Write the pending splice into the bucket
504 ; ps <- readMutVar ps_var
505 ; writeMutVar ps_var ((name,expr') : ps)
507 -- e.g. [| f (g :: Int -> $(h 4)) |]
508 -- Here (h 4) :: Q Type
509 -- but $(h 4) :: a i.e. any type, of any kind
511 -- We return a HsSpliceTyOut, which serves to convey the kind to
512 -- the ensuing TcHsType.dsHsType, which makes up a non-committal
513 -- type variable of a suitable kind
515 ; return (HsSpliceTyOut kind, kind)
518 kcTopSpliceType :: LHsExpr Name -> TcM (HsType Name, TcKind)
519 -- Note [How top-level splices are handled]
521 = do { meta_ty <- tcMetaTy typeQTyConName
523 -- Typecheck the expression
524 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_ty)
526 -- Run the expression
527 ; hs_ty2 <- runMetaT zonked_q_expr
528 ; showSplice "type" expr (ppr hs_ty2)
530 -- Rename it, but bale out if there are errors
531 -- otherwise the type checker just gives more spurious errors
532 ; addErrCtxt (spliceResultDoc expr) $ do
533 { let doc = ptext (sLit "In the spliced type") <+> ppr hs_ty2
534 ; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)
535 ; (ty4, kind) <- kcLHsType hs_ty3
536 ; return (unLoc ty4, kind) }}
539 %************************************************************************
541 \subsection{Splicing an expression}
543 %************************************************************************
546 -- Note [How top-level splices are handled]
547 -- Always at top level
548 -- Type sig at top of file:
549 -- tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
551 = do { meta_dec_ty <- tcMetaTy decTyConName
552 ; meta_q_ty <- tcMetaTy qTyConName
553 ; let list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
554 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr list_q)
556 -- Run the expression
557 ; decls <- runMetaD zonked_q_expr
558 ; showSplice "declarations" expr
559 (ppr (getLoc expr) $$ (vcat (map ppr decls)))
565 %************************************************************************
569 %************************************************************************
572 runAnnotation target expr = do
573 -- Find the classes we want instances for in order to call toAnnotationWrapper
575 data_class <- tcLookupClass dataClassName
576 to_annotation_wrapper_id <- tcLookupId toAnnotationWrapperName
578 -- Check the instances we require live in another module (we want to execute it..)
579 -- and check identifiers live in other modules using TH stage checks. tcSimplifyStagedExpr
580 -- also resolves the LIE constraints to detect e.g. instance ambiguity
581 zonked_wrapped_expr' <- tcTopSpliceExpr $
582 do { (expr', expr_ty) <- tcInferRhoNC expr
583 -- We manually wrap the typechecked expression in a call to toAnnotationWrapper
584 -- By instantiating the call >here< it gets registered in the
585 -- LIE consulted by tcTopSpliceExpr
586 -- and hence ensures the appropriate dictionary is bound by const_binds
587 ; wrapper <- instCall AnnOrigin [expr_ty] [mkClassPred data_class [expr_ty]]
588 ; let specialised_to_annotation_wrapper_expr
589 = L loc (HsWrap wrapper (HsVar to_annotation_wrapper_id))
590 ; return (L loc (HsApp specialised_to_annotation_wrapper_expr expr')) }
592 -- Run the appropriately wrapped expression to get the value of
593 -- the annotation and its dictionaries. The return value is of
594 -- type AnnotationWrapper by construction, so this conversion is
596 flip runMetaAW zonked_wrapped_expr' $ \annotation_wrapper ->
597 case annotation_wrapper of
598 AnnotationWrapper value | let serialized = toSerialized serializeWithData value ->
599 -- Got the value and dictionaries: build the serialized value and
600 -- call it a day. We ensure that we seq the entire serialized value
601 -- in order that any errors in the user-written code for the
602 -- annotation are exposed at this point. This is also why we are
603 -- doing all this stuff inside the context of runMeta: it has the
604 -- facilities to deal with user error in a meta-level expression
605 seqSerialized serialized `seq` Annotation {
607 ann_value = serialized
612 %************************************************************************
616 %************************************************************************
618 Note [Quasi-quote overview]
619 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
620 The GHC "quasi-quote" extension is described by Geoff Mainland's paper
621 "Why it's nice to be quoted: quasiquoting for Haskell" (Haskell
626 and the arbitrary string "stuff" gets parsed by the parser 'p', whose
627 type should be Language.Haskell.TH.Quote.QuasiQuoter. 'p' must be
628 defined in another module, because we are going to run it here. It's
629 a bit like a TH splice:
632 However, you can do this in patterns as well as terms. Becuase of this,
633 the splice is run by the *renamer* rather than the type checker.
636 runQuasiQuote :: Outputable hs_syn
637 => HsQuasiQuote Name -- Contains term of type QuasiQuoter, and the String
638 -> Name -- Of type QuasiQuoter -> String -> Q th_syn
639 -> Name -- Name of th_syn type
640 -> MetaOps th_syn hs_syn
642 runQuasiQuote (HsQuasiQuote _name quoter q_span quote) quote_selector meta_ty meta_ops
643 = do { -- Check that the quoter is not locally defined, otherwise the TH
644 -- machinery will not be able to run the quasiquote.
645 ; this_mod <- getModule
646 ; let is_local = case nameModule_maybe quoter of
647 Just mod | mod == this_mod -> True
650 ; traceTc (text "runQQ" <+> ppr quoter <+> ppr is_local)
651 ; checkTc (not is_local) (quoteStageError quoter)
653 -- Build the expression
654 ; let quoterExpr = L q_span $! HsVar $! quoter
655 ; let quoteExpr = L q_span $! HsLit $! HsString quote
656 ; let expr = L q_span $
658 HsApp (L q_span (HsVar quote_selector)) quoterExpr) quoteExpr
659 ; meta_exp_ty <- tcMetaTy meta_ty
661 -- Typecheck the expression
662 ; zonked_q_expr <- tcTopSpliceExpr (tcMonoExpr expr meta_exp_ty)
664 -- Run the expression
665 ; result <- runMetaQ meta_ops zonked_q_expr
666 ; showSplice (mt_desc meta_ops) quoteExpr (ppr result)
670 runQuasiQuoteExpr quasiquote = runQuasiQuote quasiquote quoteExpName expQTyConName exprMetaOps
671 runQuasiQuotePat quasiquote = runQuasiQuote quasiquote quotePatName patQTyConName patMetaOps
673 quoteStageError :: Name -> SDoc
674 quoteStageError quoter
675 = sep [ptext (sLit "GHC stage restriction:") <+> ppr quoter,
676 nest 2 (ptext (sLit "is used in a quasiquote, and must be imported, not defined locally"))]
680 %************************************************************************
682 \subsection{Running an expression}
684 %************************************************************************
687 data MetaOps th_syn hs_syn
688 = MT { mt_desc :: String -- Type of beast (expression, type etc)
689 , mt_show :: th_syn -> String -- How to show the th_syn thing
690 , mt_cvt :: SrcSpan -> th_syn -> Either Message hs_syn
691 -- How to convert to hs_syn
694 exprMetaOps :: MetaOps TH.Exp (LHsExpr RdrName)
695 exprMetaOps = MT { mt_desc = "expression", mt_show = TH.pprint, mt_cvt = convertToHsExpr }
697 patMetaOps :: MetaOps TH.Pat (LPat RdrName)
698 patMetaOps = MT { mt_desc = "pattern", mt_show = TH.pprint, mt_cvt = convertToPat }
700 typeMetaOps :: MetaOps TH.Type (LHsType RdrName)
701 typeMetaOps = MT { mt_desc = "type", mt_show = TH.pprint, mt_cvt = convertToHsType }
703 declMetaOps :: MetaOps [TH.Dec] [LHsDecl RdrName]
704 declMetaOps = MT { mt_desc = "declarations", mt_show = TH.pprint, mt_cvt = convertToHsDecls }
707 runMetaAW :: Outputable output
708 => (AnnotationWrapper -> output)
709 -> LHsExpr Id -- Of type AnnotationWrapper
711 runMetaAW k = runMeta False (\_ -> return . Right . k)
712 -- We turn off showing the code in meta-level exceptions because doing so exposes
713 -- the toAnnotationWrapper function that we slap around the users code
716 runMetaQ :: Outputable hs_syn
717 => MetaOps th_syn hs_syn
720 runMetaQ (MT { mt_show = show_th, mt_cvt = cvt }) expr
721 = runMeta True run_and_cvt expr
723 run_and_cvt expr_span hval
724 = do { th_result <- TH.runQ hval
725 ; traceTc (text "Got TH result:" <+> text (show_th th_result))
726 ; return (cvt expr_span th_result) }
728 runMetaE :: LHsExpr Id -- Of type (Q Exp)
729 -> TcM (LHsExpr RdrName)
730 runMetaE = runMetaQ exprMetaOps
732 runMetaT :: LHsExpr Id -- Of type (Q Type)
733 -> TcM (LHsType RdrName)
734 runMetaT = runMetaQ typeMetaOps
736 runMetaD :: LHsExpr Id -- Of type Q [Dec]
737 -> TcM [LHsDecl RdrName]
738 runMetaD = runMetaQ declMetaOps
741 runMeta :: (Outputable hs_syn)
742 => Bool -- Whether code should be printed in the exception message
743 -> (SrcSpan -> x -> TcM (Either Message hs_syn)) -- How to run x
744 -> LHsExpr Id -- Of type x; typically x = Q TH.Exp, or something like that
745 -> TcM hs_syn -- Of type t
746 runMeta show_code run_and_convert expr
747 = do { traceTc (text "About to run" <+> ppr expr)
750 ; ds_expr <- initDsTc (dsLExpr expr)
751 -- Compile and link it; might fail if linking fails
752 ; hsc_env <- getTopEnv
753 ; src_span <- getSrcSpanM
754 ; either_hval <- tryM $ liftIO $
755 HscMain.compileExpr hsc_env src_span ds_expr
756 ; case either_hval of {
757 Left exn -> failWithTc (mk_msg "compile and link" exn) ;
760 { -- Coerce it to Q t, and run it
762 -- Running might fail if it throws an exception of any kind (hence tryAllM)
763 -- including, say, a pattern-match exception in the code we are running
765 -- We also do the TH -> HS syntax conversion inside the same
766 -- exception-cacthing thing so that if there are any lurking
767 -- exceptions in the data structure returned by hval, we'll
768 -- encounter them inside the try
770 -- See Note [Exceptions in TH]
771 let expr_span = getLoc expr
772 ; either_tval <- tryAllM $
773 setSrcSpan expr_span $ -- Set the span so that qLocation can
774 -- see where this splice is
775 do { mb_result <- run_and_convert expr_span (unsafeCoerce# hval)
777 Left err -> failWithTc err
778 Right result -> do { traceTc (ptext (sLit "Got HsSyn result:") <+> ppr result)
779 ; return $! result } }
781 ; case either_tval of
783 Left se -> case fromException se of
784 Just IOEnvFailure -> failM -- Error already in Tc monad
785 _ -> failWithTc (mk_msg "run" se) -- Exception
788 mk_msg s exn = vcat [text "Exception when trying to" <+> text s <+> text "compile-time code:",
789 nest 2 (text (Panic.showException exn)),
790 if show_code then nest 2 (text "Code:" <+> ppr expr) else empty]
793 Note [Exceptions in TH]
794 ~~~~~~~~~~~~~~~~~~~~~~~
795 Supppose we have something like this
799 f n | n>3 = fail "Too many declarations"
802 The 'fail' is a user-generated failure, and should be displayed as a
803 perfectly ordinary compiler error message, not a panic or anything
804 like that. Here's how it's processed:
806 * 'fail' is the monad fail. The monad instance for Q in TH.Syntax
807 effectively transforms (fail s) to
808 qReport True s >> fail
809 where 'qReport' comes from the Quasi class and fail from its monad
812 * The TcM monad is an instance of Quasi (see TcSplice), and it implements
813 (qReport True s) by using addErr to add an error message to the bag of errors.
814 The 'fail' in TcM raises an IOEnvFailure exception
816 * So, when running a splice, we catch all exceptions; then for
817 - an IOEnvFailure exception, we assume the error is already
818 in the error-bag (above)
819 - other errors, we add an error to the bag
823 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
826 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
827 qNewName s = do { u <- newUnique
829 ; return (TH.mkNameU s i) }
831 qReport True msg = addErr (text msg)
832 qReport False msg = addReport (text msg) empty
834 qLocation = do { m <- getModule
836 ; return (TH.Loc { TH.loc_filename = unpackFS (srcSpanFile l)
837 , TH.loc_module = moduleNameString (moduleName m)
838 , TH.loc_package = packageIdString (modulePackageId m)
839 , TH.loc_start = (srcSpanStartLine l, srcSpanStartCol l)
840 , TH.loc_end = (srcSpanEndLine l, srcSpanEndCol l) }) }
844 -- For qRecover, discard error messages if
845 -- the recovery action is chosen. Otherwise
846 -- we'll only fail higher up. c.f. tryTcLIE_
847 qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main
849 Just val -> do { addMessages msgs -- There might be warnings
851 Nothing -> recover -- Discard all msgs
854 qRunIO io = liftIO io
858 %************************************************************************
860 \subsection{Errors and contexts}
862 %************************************************************************
865 showSplice :: String -> LHsExpr Name -> SDoc -> TcM ()
866 -- Note that 'before' is *renamed* but not *typechecked*
867 -- Reason (a) less typechecking crap
868 -- (b) data constructors after type checking have been
869 -- changed to their *wrappers*, and that makes them
870 -- print always fully qualified
871 showSplice what before after
872 = do { loc <- getSrcSpanM
873 ; traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
874 nest 2 (sep [nest 2 (ppr before),
878 illegalBracket :: SDoc
879 illegalBracket = ptext (sLit "Template Haskell brackets cannot be nested (without intervening splices)")
884 %************************************************************************
888 %************************************************************************
892 reify :: TH.Name -> TcM TH.Info
894 = do { name <- lookupThName th_name
895 ; thing <- tcLookupTh name
896 -- ToDo: this tcLookup could fail, which would give a
897 -- rather unhelpful error message
898 ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
902 ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
903 ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
904 ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
905 ppr_ns _ = panic "reify/ppr_ns"
907 lookupThName :: TH.Name -> TcM Name
908 lookupThName th_name = do
909 mb_name <- lookupThName_maybe th_name
911 Nothing -> failWithTc (notInScope th_name)
912 Just name -> return name
914 lookupThName_maybe th_name
915 = do { names <- mapMaybeM lookup (thRdrNameGuesses th_name)
916 -- Pick the first that works
917 -- E.g. reify (mkName "A") will pick the class A in preference to the data constructor A
918 ; return (listToMaybe names) }
921 = do { -- Repeat much of lookupOccRn, becase we want
922 -- to report errors in a TH-relevant way
923 ; rdr_env <- getLocalRdrEnv
924 ; case lookupLocalRdrEnv rdr_env rdr_name of
925 Just name -> return (Just name)
926 Nothing -> lookupGlobalOccRn_maybe rdr_name }
928 tcLookupTh :: Name -> TcM TcTyThing
929 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
930 -- it gives a reify-related error message on failure, whereas in the normal
931 -- tcLookup, failure is a bug.
933 = do { (gbl_env, lcl_env) <- getEnvs
934 ; case lookupNameEnv (tcl_env lcl_env) name of {
935 Just thing -> return thing;
937 { if nameIsLocalOrFrom (tcg_mod gbl_env) name
938 then -- It's defined in this module
939 case lookupNameEnv (tcg_type_env gbl_env) name of
940 Just thing -> return (AGlobal thing)
941 Nothing -> failWithTc (notInEnv name)
943 else do -- It's imported
944 { (eps,hpt) <- getEpsAndHpt
946 ; case lookupType dflags hpt (eps_PTE eps) name of
947 Just thing -> return (AGlobal thing)
948 Nothing -> do { thing <- tcImportDecl name
949 ; return (AGlobal thing) }
950 -- Imported names should always be findable;
951 -- if not, we fail hard in tcImportDecl
954 notInScope :: TH.Name -> SDoc
955 notInScope th_name = quotes (text (TH.pprint th_name)) <+>
956 ptext (sLit "is not in scope at a reify")
957 -- Ugh! Rather an indirect way to display the name
959 notInEnv :: Name -> SDoc
960 notInEnv name = quotes (ppr name) <+>
961 ptext (sLit "is not in the type environment at a reify")
963 ------------------------------
964 reifyThing :: TcTyThing -> TcM TH.Info
965 -- The only reason this is monadic is for error reporting,
966 -- which in turn is mainly for the case when TH can't express
967 -- some random GHC extension
969 reifyThing (AGlobal (AnId id))
970 = do { ty <- reifyType (idType id)
971 ; fix <- reifyFixity (idName id)
972 ; let v = reifyName id
973 ; case idDetails id of
974 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
975 _ -> return (TH.VarI v ty Nothing fix)
978 reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc
979 reifyThing (AGlobal (AClass cls)) = reifyClass cls
980 reifyThing (AGlobal (ADataCon dc))
981 = do { let name = dataConName dc
982 ; ty <- reifyType (idType (dataConWrapId dc))
983 ; fix <- reifyFixity name
984 ; return (TH.DataConI (reifyName name) ty
985 (reifyName (dataConOrigTyCon dc)) fix)
988 reifyThing (ATcId {tct_id = id, tct_type = ty})
989 = do { ty1 <- zonkTcType ty -- Make use of all the info we have, even
990 -- though it may be incomplete
991 ; ty2 <- reifyType ty1
992 ; fix <- reifyFixity (idName id)
993 ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
995 reifyThing (ATyVar tv ty)
996 = do { ty1 <- zonkTcType ty
997 ; ty2 <- reifyType ty1
998 ; return (TH.TyVarI (reifyName tv) ty2) }
1000 reifyThing (AThing {}) = panic "reifyThing AThing"
1002 ------------------------------
1003 reifyTyCon :: TyCon -> TcM TH.Info
1006 = return (TH.PrimTyConI (reifyName tc) 2 False)
1008 = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc))
1010 = let flavour = reifyFamFlavour tc
1011 tvs = tyConTyVars tc
1014 | isLiftedTypeKind kind = Nothing
1015 | otherwise = Just $ reifyKind kind
1018 TH.FamilyD flavour (reifyName tc) (reifyTyVars tvs) kind')
1020 = do { let (tvs, rhs) = synTyConDefn tc
1021 ; rhs' <- reifyType rhs
1022 ; return (TH.TyConI $
1023 TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs')
1027 = do { cxt <- reifyCxt (tyConStupidTheta tc)
1028 ; let tvs = tyConTyVars tc
1029 ; cons <- mapM (reifyDataCon (mkTyVarTys tvs)) (tyConDataCons tc)
1030 ; let name = reifyName tc
1031 r_tvs = reifyTyVars tvs
1032 deriv = [] -- Don't know about deriving
1033 decl | isNewTyCon tc = TH.NewtypeD cxt name r_tvs (head cons) deriv
1034 | otherwise = TH.DataD cxt name r_tvs cons deriv
1035 ; return (TH.TyConI decl) }
1037 reifyDataCon :: [Type] -> DataCon -> TcM TH.Con
1039 | isVanillaDataCon dc
1040 = do { arg_tys <- reifyTypes (dataConInstOrigArgTys dc tys)
1041 ; let stricts = map reifyStrict (dataConStrictMarks dc)
1042 fields = dataConFieldLabels dc
1046 ; ASSERT( length arg_tys == length stricts )
1047 if not (null fields) then
1048 return (TH.RecC name (zip3 (map reifyName fields) stricts arg_tys))
1050 if dataConIsInfix dc then
1051 ASSERT( length arg_tys == 2 )
1052 return (TH.InfixC (s1,a1) name (s2,a2))
1054 return (TH.NormalC name (stricts `zip` arg_tys)) }
1056 = failWithTc (ptext (sLit "Can't reify a GADT data constructor:")
1057 <+> quotes (ppr dc))
1059 ------------------------------
1060 reifyClass :: Class -> TcM TH.Info
1062 = do { cxt <- reifyCxt theta
1063 ; ops <- mapM reify_op op_stuff
1064 ; return (TH.ClassI $ TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) fds' ops) }
1066 (tvs, fds, theta, _, _, op_stuff) = classExtraBigSig cls
1067 fds' = map reifyFunDep fds
1068 reify_op (op, _) = do { ty <- reifyType (idType op)
1069 ; return (TH.SigD (reifyName op) ty) }
1071 ------------------------------
1072 reifyType :: TypeRep.Type -> TcM TH.Type
1073 reifyType ty@(ForAllTy _ _) = reify_for_all ty
1074 reifyType ty@(PredTy {} `FunTy` _) = reify_for_all ty -- Types like ((?x::Int) => Char -> Char)
1075 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
1076 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys -- Do not expand type synonyms here
1077 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
1078 reifyType (FunTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
1079 reifyType ty@(PredTy {}) = pprPanic "reifyType PredTy" (ppr ty)
1081 reify_for_all :: TypeRep.Type -> TcM TH.Type
1083 = do { cxt' <- reifyCxt cxt;
1084 ; tau' <- reifyType tau
1085 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
1087 (tvs, cxt, tau) = tcSplitSigmaTy ty
1089 reifyTypes :: [Type] -> TcM [TH.Type]
1090 reifyTypes = mapM reifyType
1092 reifyKind :: Kind -> TH.Kind
1094 = let (kis, ki') = splitKindFunTys ki
1095 kis_rep = map reifyKind kis
1096 ki'_rep = reifyNonArrowKind ki'
1098 foldl TH.ArrowK ki'_rep kis_rep
1100 reifyNonArrowKind k | isLiftedTypeKind k = TH.StarK
1101 | otherwise = pprPanic "Exotic form of kind"
1104 reifyCxt :: [PredType] -> TcM [TH.Pred]
1105 reifyCxt = mapM reifyPred
1107 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
1108 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
1110 reifyFamFlavour :: TyCon -> TH.FamFlavour
1111 reifyFamFlavour tc | isOpenSynTyCon tc = TH.TypeFam
1112 | isOpenTyCon tc = TH.DataFam
1114 = panic "TcSplice.reifyFamFlavour: not a type family"
1116 reifyTyVars :: [TyVar] -> [TH.TyVarBndr]
1117 reifyTyVars = map reifyTyVar
1119 reifyTyVar tv | isLiftedTypeKind kind = TH.PlainTV name
1120 | otherwise = TH.KindedTV name (reifyKind kind)
1125 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
1126 reify_tc_app tc tys = do { tys' <- reifyTypes tys
1127 ; return (foldl TH.AppT (TH.ConT tc) tys') }
1129 reifyPred :: TypeRep.PredType -> TcM TH.Pred
1130 reifyPred (ClassP cls tys)
1131 = do { tys' <- reifyTypes tys
1132 ; return $ TH.ClassP (reifyName cls) tys'
1134 reifyPred p@(IParam _ _) = noTH (sLit "implicit parameters") (ppr p)
1135 reifyPred (EqPred ty1 ty2)
1136 = do { ty1' <- reifyType ty1
1137 ; ty2' <- reifyType ty2
1138 ; return $ TH.EqualP ty1' ty2'
1142 ------------------------------
1143 reifyName :: NamedThing n => n -> TH.Name
1145 | isExternalName name = mk_varg pkg_str mod_str occ_str
1146 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
1147 -- Many of the things we reify have local bindings, and
1148 -- NameL's aren't supposed to appear in binding positions, so
1149 -- we use NameU. When/if we start to reify nested things, that
1150 -- have free variables, we may need to generate NameL's for them.
1152 name = getName thing
1153 mod = ASSERT( isExternalName name ) nameModule name
1154 pkg_str = packageIdString (modulePackageId mod)
1155 mod_str = moduleNameString (moduleName mod)
1156 occ_str = occNameString occ
1157 occ = nameOccName name
1158 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
1159 | OccName.isVarOcc occ = TH.mkNameG_v
1160 | OccName.isTcOcc occ = TH.mkNameG_tc
1161 | otherwise = pprPanic "reifyName" (ppr name)
1163 ------------------------------
1164 reifyFixity :: Name -> TcM TH.Fixity
1166 = do { fix <- lookupFixityRn name
1167 ; return (conv_fix fix) }
1169 conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
1170 conv_dir BasicTypes.InfixR = TH.InfixR
1171 conv_dir BasicTypes.InfixL = TH.InfixL
1172 conv_dir BasicTypes.InfixN = TH.InfixN
1174 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
1175 reifyStrict MarkedStrict = TH.IsStrict
1176 reifyStrict MarkedUnboxed = TH.IsStrict
1177 reifyStrict NotMarkedStrict = TH.NotStrict
1179 ------------------------------
1180 noTH :: LitString -> SDoc -> TcM a
1181 noTH s d = failWithTc (hsep [ptext (sLit "Can't represent") <+> ptext s <+>
1182 ptext (sLit "in Template Haskell:"),