2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 TcSplice: Template Haskell splices
9 module TcSplice( tcSpliceExpr, tcSpliceDecls, tcBracket ) where
11 #include "HsVersions.h"
15 -- These imports are the reason that TcSplice
16 -- is very high up the module hierarchy
50 import DsMonad hiding (Splice)
60 import qualified Language.Haskell.TH as TH
61 -- THSyntax gives access to internal functions and data types
62 import qualified Language.Haskell.TH.Syntax as TH
64 import GHC.Exts ( unsafeCoerce#, Int#, Int(..) )
65 import Control.Monad ( liftM )
69 %************************************************************************
71 \subsection{Main interface + stubs for the non-GHCI case
73 %************************************************************************
76 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
77 tcSpliceExpr :: HsSplice Name -> BoxyRhoType -> TcM (HsExpr TcId)
78 kcSpliceType :: HsSplice Name -> TcM (HsType Name, TcKind)
79 -- None of these functions add constraints to the LIE
82 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
83 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
87 %************************************************************************
89 \subsection{Quoting an expression}
91 %************************************************************************
94 tcBracket :: HsBracket Name -> BoxyRhoType -> TcM (LHsExpr TcId)
95 tcBracket brack res_ty
96 = getStage `thenM` \ level ->
97 case bracketOK level of {
98 Nothing -> failWithTc (illegalBracket level) ;
101 -- Typecheck expr to make sure it is valid,
102 -- but throw away the results. We'll type check
103 -- it again when we actually use it.
105 newMutVar [] `thenM` \ pending_splices ->
106 getLIEVar `thenM` \ lie_var ->
108 setStage (Brack next_level pending_splices lie_var) (
109 getLIE (tc_bracket brack)
110 ) `thenM` \ (meta_ty, lie) ->
111 tcSimplifyBracket lie `thenM_`
113 -- Make the expected type have the right shape
114 boxyUnify meta_ty res_ty `thenM_`
116 -- Return the original expression, not the type-decorated one
117 readMutVar pending_splices `thenM` \ pendings ->
118 returnM (noLoc (HsBracketOut brack pendings))
121 tc_bracket :: HsBracket Name -> TcM TcType
123 = tcMetaTy nameTyConName -- Result type is Var (not Q-monadic)
125 tc_bracket (ExpBr expr)
126 = newFlexiTyVarTy liftedTypeKind `thenM` \ any_ty ->
127 tcMonoExpr expr any_ty `thenM_`
128 tcMetaTy expQTyConName
129 -- Result type is Expr (= Q Exp)
131 tc_bracket (TypBr typ)
132 = tcHsSigType ExprSigCtxt typ `thenM_`
133 tcMetaTy typeQTyConName
134 -- Result type is Type (= Q Typ)
136 tc_bracket (DecBr decls)
137 = do { tcTopSrcDecls emptyModDetails decls
138 -- Typecheck the declarations, dicarding the result
139 -- We'll get all that stuff later, when we splice it in
141 ; decl_ty <- tcMetaTy decTyConName
142 ; q_ty <- tcMetaTy qTyConName
143 ; return (mkAppTy q_ty (mkListTy decl_ty))
144 -- Result type is Q [Dec]
148 = failWithTc (ptext SLIT("Tempate Haskell pattern brackets are not supported yet"))
152 %************************************************************************
154 \subsection{Splicing an expression}
156 %************************************************************************
159 tcSpliceExpr (HsSplice name expr) res_ty
160 = setSrcSpan (getLoc expr) $
161 getStage `thenM` \ level ->
162 case spliceOK level of {
163 Nothing -> failWithTc (illegalSplice level) ;
167 Comp -> do { e <- tcTopSplice expr res_ty
168 ; returnM (unLoc e) } ;
169 Brack _ ps_var lie_var ->
171 -- A splice inside brackets
172 -- NB: ignore res_ty, apart from zapping it to a mono-type
173 -- e.g. [| reverse $(h 4) |]
174 -- Here (h 4) :: Q Exp
175 -- but $(h 4) :: forall a.a i.e. anything!
177 unBox res_ty `thenM_`
178 tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
179 setStage (Splice next_level) (
181 tcMonoExpr expr meta_exp_ty
184 -- Write the pending splice into the bucket
185 readMutVar ps_var `thenM` \ ps ->
186 writeMutVar ps_var ((name,expr') : ps) `thenM_`
188 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
191 -- tcTopSplice used to have this:
192 -- Note that we do not decrement the level (to -1) before
193 -- typechecking the expression. For example:
194 -- f x = $( ...$(g 3) ... )
195 -- The recursive call to tcMonoExpr will simply expand the
196 -- inner escape before dealing with the outer one
198 tcTopSplice :: LHsExpr Name -> BoxyRhoType -> TcM (LHsExpr Id)
199 tcTopSplice expr res_ty
200 = tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
202 -- Typecheck the expression
203 tcTopSpliceExpr expr meta_exp_ty `thenM` \ zonked_q_expr ->
205 -- Run the expression
206 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
207 runMetaE convertToHsExpr zonked_q_expr `thenM` \ expr2 ->
209 traceTc (text "Got result" <+> ppr expr2) `thenM_`
211 showSplice "expression"
212 zonked_q_expr (ppr expr2) `thenM_`
214 -- Rename it, but bale out if there are errors
215 -- otherwise the type checker just gives more spurious errors
216 checkNoErrs (rnLExpr expr2) `thenM` \ (exp3, fvs) ->
218 tcMonoExpr exp3 res_ty
221 tcTopSpliceExpr :: LHsExpr Name -> TcType -> TcM (LHsExpr Id)
222 -- Type check an expression that is the body of a top-level splice
223 -- (the caller will compile and run it)
224 tcTopSpliceExpr expr meta_ty
225 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
226 -- if the type checker fails!
228 setStage topSpliceStage $ do
231 do { recordThUse -- Record that TH is used (for pkg depdendency)
233 -- Typecheck the expression
234 ; (expr', lie) <- getLIE (tcMonoExpr expr meta_ty)
236 -- Solve the constraints
237 ; const_binds <- tcSimplifyTop lie
240 ; zonkTopLExpr (mkHsDictLet const_binds expr') }
244 %************************************************************************
248 %************************************************************************
250 Very like splicing an expression, but we don't yet share code.
253 kcSpliceType (HsSplice name hs_expr)
254 = setSrcSpan (getLoc hs_expr) $ do
256 ; case spliceOK level of {
257 Nothing -> failWithTc (illegalSplice level) ;
258 Just next_level -> do
261 Comp -> do { (t,k) <- kcTopSpliceType hs_expr
262 ; return (unLoc t, k) } ;
263 Brack _ ps_var lie_var -> do
265 { -- A splice inside brackets
266 ; meta_ty <- tcMetaTy typeQTyConName
267 ; expr' <- setStage (Splice next_level) $
269 tcMonoExpr hs_expr meta_ty
271 -- Write the pending splice into the bucket
272 ; ps <- readMutVar ps_var
273 ; writeMutVar ps_var ((name,expr') : ps)
275 -- e.g. [| Int -> $(h 4) |]
276 -- Here (h 4) :: Q Type
277 -- but $(h 4) :: forall a.a i.e. any kind
279 ; returnM (panic "kcSpliceType", kind) -- The returned type is ignored
282 kcTopSpliceType :: LHsExpr Name -> TcM (LHsType Name, TcKind)
284 = do { meta_ty <- tcMetaTy typeQTyConName
286 -- Typecheck the expression
287 ; zonked_q_expr <- tcTopSpliceExpr expr meta_ty
289 -- Run the expression
290 ; traceTc (text "About to run" <+> ppr zonked_q_expr)
291 ; hs_ty2 <- runMetaT convertToHsType zonked_q_expr
293 ; traceTc (text "Got result" <+> ppr hs_ty2)
295 ; showSplice "type" zonked_q_expr (ppr hs_ty2)
297 -- Rename it, but bale out if there are errors
298 -- otherwise the type checker just gives more spurious errors
299 ; let doc = ptext SLIT("In the spliced type") <+> ppr hs_ty2
300 ; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)
305 %************************************************************************
307 \subsection{Splicing an expression}
309 %************************************************************************
312 -- Always at top level
313 -- Type sig at top of file:
314 -- tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
316 = do { meta_dec_ty <- tcMetaTy decTyConName
317 ; meta_q_ty <- tcMetaTy qTyConName
318 ; let list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
319 ; zonked_q_expr <- tcTopSpliceExpr expr list_q
321 -- Run the expression
322 ; traceTc (text "About to run" <+> ppr zonked_q_expr)
323 ; decls <- runMetaD convertToHsDecls zonked_q_expr
325 ; traceTc (text "Got result" <+> vcat (map ppr decls))
326 ; showSplice "declarations"
328 (ppr (getLoc expr) $$ (vcat (map ppr decls)))
331 where handleErrors :: [Either a Message] -> TcM [a]
332 handleErrors [] = return []
333 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
334 handleErrors (Right m:xs) = do addErrTc m
339 %************************************************************************
341 \subsection{Running an expression}
343 %************************************************************************
346 runMetaE :: (SrcSpan -> TH.Exp -> Either Message (LHsExpr RdrName))
347 -> LHsExpr Id -- Of type (Q Exp)
348 -> TcM (LHsExpr RdrName)
351 runMetaT :: (SrcSpan -> TH.Type -> Either Message (LHsType RdrName))
352 -> LHsExpr Id -- Of type (Q Type)
353 -> TcM (LHsType RdrName)
356 runMetaD :: (SrcSpan -> [TH.Dec] -> Either Message [LHsDecl RdrName])
357 -> LHsExpr Id -- Of type Q [Dec]
358 -> TcM [LHsDecl RdrName]
361 runMeta :: (SrcSpan -> th_syn -> Either Message hs_syn)
362 -> LHsExpr Id -- Of type X
363 -> TcM hs_syn -- Of type t
366 ds_expr <- initDsTc (dsLExpr expr)
368 -- Compile and link it; might fail if linking fails
369 ; hsc_env <- getTopEnv
370 ; src_span <- getSrcSpanM
371 ; either_hval <- tryM $ ioToTcRn $
372 HscMain.compileExpr hsc_env src_span ds_expr
373 ; case either_hval of {
374 Left exn -> failWithTc (mk_msg "compile and link" exn) ;
377 { -- Coerce it to Q t, and run it
378 -- Running might fail if it throws an exception of any kind (hence tryAllM)
379 -- including, say, a pattern-match exception in the code we are running
381 -- We also do the TH -> HS syntax conversion inside the same
382 -- exception-cacthing thing so that if there are any lurking
383 -- exceptions in the data structure returned by hval, we'll
384 -- encounter them inside the try
385 either_tval <- tryAllM $ do
386 { th_syn <- TH.runQ (unsafeCoerce# hval)
387 ; case convert (getLoc expr) th_syn of
388 Left err -> do { addErrTc err; return Nothing }
389 Right hs_syn -> return (Just hs_syn) }
391 ; case either_tval of
392 Right (Just v) -> return v
393 Right Nothing -> failM -- Error already in Tc monad
394 Left exn -> failWithTc (mk_msg "run" exn) -- Exception
397 mk_msg s exn = vcat [text "Exception when trying to" <+> text s <+> text "compile-time code:",
398 nest 2 (text (Panic.showException exn)),
399 nest 2 (text "Code:" <+> ppr expr)]
402 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
405 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
406 qNewName s = do { u <- newUnique
408 ; return (TH.mkNameU s i) }
410 qReport True msg = addErr (text msg)
411 qReport False msg = addReport (text msg)
413 qCurrentModule = do { m <- getModule;
414 return (moduleNameString (moduleName m)) }
415 -- ToDo: is throwing away the package name ok here?
419 -- For qRecover, discard error messages if
420 -- the recovery action is chosen. Otherwise
421 -- we'll only fail higher up. c.f. tryTcLIE_
422 qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main
424 Just val -> do { addMessages msgs -- There might be warnings
426 Nothing -> recover -- Discard all msgs
429 qRunIO io = ioToTcRn io
433 %************************************************************************
435 \subsection{Errors and contexts}
437 %************************************************************************
440 showSplice :: String -> LHsExpr Id -> SDoc -> TcM ()
441 showSplice what before after
442 = getSrcSpanM `thenM` \ loc ->
443 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
444 nest 2 (sep [nest 2 (ppr before),
449 = ptext SLIT("Illegal bracket at level") <+> ppr level
452 = ptext SLIT("Illegal splice at level") <+> ppr level
458 %************************************************************************
462 %************************************************************************
466 reify :: TH.Name -> TcM TH.Info
468 = do { name <- lookupThName th_name
469 ; thing <- tcLookupTh name
470 -- ToDo: this tcLookup could fail, which would give a
471 -- rather unhelpful error message
472 ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
476 ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
477 ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
478 ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
480 lookupThName :: TH.Name -> TcM Name
481 lookupThName th_name@(TH.Name occ flavour)
482 = do { let rdr_name = thRdrName guessed_ns occ_str flavour
484 -- Repeat much of lookupOccRn, becase we want
485 -- to report errors in a TH-relevant way
486 ; rdr_env <- getLocalRdrEnv
487 ; case lookupLocalRdrEnv rdr_env rdr_name of
488 Just name -> return name
489 Nothing | not (isSrcRdrName rdr_name) -- Exact, Orig
490 -> lookupImportedName rdr_name
491 | otherwise -- Unqual, Qual
493 mb_name <- lookupSrcOcc_maybe rdr_name
495 Just name -> return name
496 Nothing -> failWithTc (notInScope th_name) }
499 -- guessed_ns is the name space guessed from looking at the TH name
500 guessed_ns | isLexCon (mkFastString occ_str) = OccName.dataName
501 | otherwise = OccName.varName
502 occ_str = TH.occString occ
504 tcLookupTh :: Name -> TcM TcTyThing
505 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
506 -- it gives a reify-related error message on failure, whereas in the normal
507 -- tcLookup, failure is a bug.
509 = do { (gbl_env, lcl_env) <- getEnvs
510 ; case lookupNameEnv (tcl_env lcl_env) name of {
511 Just thing -> returnM thing;
513 { if nameIsLocalOrFrom (tcg_mod gbl_env) name
514 then -- It's defined in this module
515 case lookupNameEnv (tcg_type_env gbl_env) name of
516 Just thing -> return (AGlobal thing)
517 Nothing -> failWithTc (notInEnv name)
519 else do -- It's imported
520 { (eps,hpt) <- getEpsAndHpt
522 ; case lookupType dflags hpt (eps_PTE eps) name of
523 Just thing -> return (AGlobal thing)
524 Nothing -> do { thing <- tcImportDecl name
525 ; return (AGlobal thing) }
526 -- Imported names should always be findable;
527 -- if not, we fail hard in tcImportDecl
530 notInScope :: TH.Name -> SDoc
531 notInScope th_name = quotes (text (TH.pprint th_name)) <+>
532 ptext SLIT("is not in scope at a reify")
533 -- Ugh! Rather an indirect way to display the name
535 notInEnv :: Name -> SDoc
536 notInEnv name = quotes (ppr name) <+>
537 ptext SLIT("is not in the type environment at a reify")
539 ------------------------------
540 reifyThing :: TcTyThing -> TcM TH.Info
541 -- The only reason this is monadic is for error reporting,
542 -- which in turn is mainly for the case when TH can't express
543 -- some random GHC extension
545 reifyThing (AGlobal (AnId id))
546 = do { ty <- reifyType (idType id)
547 ; fix <- reifyFixity (idName id)
548 ; let v = reifyName id
549 ; case globalIdDetails id of
550 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
551 other -> return (TH.VarI v ty Nothing fix)
554 reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc
555 reifyThing (AGlobal (AClass cls)) = reifyClass cls
556 reifyThing (AGlobal (ADataCon dc))
557 = do { let name = dataConName dc
558 ; ty <- reifyType (idType (dataConWrapId dc))
559 ; fix <- reifyFixity name
560 ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
562 reifyThing (ATcId {tct_id = id, tct_type = ty})
563 = do { ty1 <- zonkTcType ty -- Make use of all the info we have, even
564 -- though it may be incomplete
565 ; ty2 <- reifyType ty1
566 ; fix <- reifyFixity (idName id)
567 ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
569 reifyThing (ATyVar tv ty)
570 = do { ty1 <- zonkTcType ty
571 ; ty2 <- reifyType ty1
572 ; return (TH.TyVarI (reifyName tv) ty2) }
574 ------------------------------
575 reifyTyCon :: TyCon -> TcM TH.Info
577 | isFunTyCon tc = return (TH.PrimTyConI (reifyName tc) 2 False)
578 | isPrimTyCon tc = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc))
580 = do { let (tvs, rhs) = synTyConDefn tc
581 ; rhs' <- reifyType rhs
582 ; return (TH.TyConI $
583 TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
586 = do { cxt <- reifyCxt (tyConStupidTheta tc)
587 ; cons <- mapM reifyDataCon (tyConDataCons tc)
588 ; let name = reifyName tc
589 tvs = reifyTyVars (tyConTyVars tc)
590 deriv = [] -- Don't know about deriving
591 decl | isNewTyCon tc = TH.NewtypeD cxt name tvs (head cons) deriv
592 | otherwise = TH.DataD cxt name tvs cons deriv
593 ; return (TH.TyConI decl) }
595 reifyDataCon :: DataCon -> TcM TH.Con
597 | isVanillaDataCon dc
598 = do { arg_tys <- reifyTypes (dataConOrigArgTys dc)
599 ; let stricts = map reifyStrict (dataConStrictMarks dc)
600 fields = dataConFieldLabels dc
604 ; ASSERT( length arg_tys == length stricts )
605 if not (null fields) then
606 return (TH.RecC name (zip3 (map reifyName fields) stricts arg_tys))
608 if dataConIsInfix dc then
609 ASSERT( length arg_tys == 2 )
610 return (TH.InfixC (s1,a1) name (s2,a2))
612 return (TH.NormalC name (stricts `zip` arg_tys)) }
614 = failWithTc (ptext SLIT("Can't reify a non-Haskell-98 data constructor:")
617 ------------------------------
618 reifyClass :: Class -> TcM TH.Info
620 = do { cxt <- reifyCxt theta
621 ; ops <- mapM reify_op op_stuff
622 ; return (TH.ClassI $ TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) fds' ops) }
624 (tvs, fds, theta, _, _, op_stuff) = classExtraBigSig cls
625 fds' = map reifyFunDep fds
626 reify_op (op, _) = do { ty <- reifyType (idType op)
627 ; return (TH.SigD (reifyName op) ty) }
629 ------------------------------
630 reifyType :: TypeRep.Type -> TcM TH.Type
631 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
632 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
633 reifyType (NoteTy _ ty) = reifyType ty
634 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
635 reifyType (FunTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
636 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt;
637 ; tau' <- reifyType tau
638 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
640 (tvs, cxt, tau) = tcSplitSigmaTy ty
641 reifyTypes = mapM reifyType
642 reifyCxt = mapM reifyPred
644 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
645 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
647 reifyTyVars :: [TyVar] -> [TH.Name]
648 reifyTyVars = map reifyName
650 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
651 reify_tc_app tc tys = do { tys' <- reifyTypes tys
652 ; return (foldl TH.AppT (TH.ConT tc) tys') }
654 reifyPred :: TypeRep.PredType -> TcM TH.Type
655 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
656 reifyPred p@(IParam _ _) = noTH SLIT("implicit parameters") (ppr p)
659 ------------------------------
660 reifyName :: NamedThing n => n -> TH.Name
662 | isExternalName name = mk_varg pkg_str mod_str occ_str
663 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
664 -- Many of the things we reify have local bindings, and
665 -- NameL's aren't supposed to appear in binding positions, so
666 -- we use NameU. When/if we start to reify nested things, that
667 -- have free variables, we may need to generate NameL's for them.
670 mod = nameModule name
671 pkg_str = packageIdString (modulePackageId mod)
672 mod_str = moduleNameString (moduleName mod)
673 occ_str = occNameString occ
674 occ = nameOccName name
675 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
676 | OccName.isVarOcc occ = TH.mkNameG_v
677 | OccName.isTcOcc occ = TH.mkNameG_tc
678 | otherwise = pprPanic "reifyName" (ppr name)
680 ------------------------------
681 reifyFixity :: Name -> TcM TH.Fixity
683 = do { fix <- lookupFixityRn name
684 ; return (conv_fix fix) }
686 conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
687 conv_dir BasicTypes.InfixR = TH.InfixR
688 conv_dir BasicTypes.InfixL = TH.InfixL
689 conv_dir BasicTypes.InfixN = TH.InfixN
691 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
692 reifyStrict MarkedStrict = TH.IsStrict
693 reifyStrict MarkedUnboxed = TH.IsStrict
694 reifyStrict NotMarkedStrict = TH.NotStrict
696 ------------------------------
697 noTH :: LitString -> SDoc -> TcM a
698 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+>
699 ptext SLIT("in Template Haskell:"),