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)
61 import qualified Language.Haskell.TH as TH
62 -- THSyntax gives access to internal functions and data types
63 import qualified Language.Haskell.TH.Syntax as TH
65 import GHC.Exts ( unsafeCoerce#, Int#, Int(..) )
66 import Control.Monad ( liftM )
70 %************************************************************************
72 \subsection{Main interface + stubs for the non-GHCI case
74 %************************************************************************
77 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
78 tcSpliceExpr :: HsSplice Name -> BoxyRhoType -> TcM (HsExpr TcId)
79 kcSpliceType :: HsSplice Name -> TcM (HsType Name, TcKind)
80 -- None of these functions add constraints to the LIE
83 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
84 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
88 %************************************************************************
90 \subsection{Quoting an expression}
92 %************************************************************************
95 tcBracket :: HsBracket Name -> BoxyRhoType -> TcM (LHsExpr TcId)
96 tcBracket brack res_ty
97 = getStage `thenM` \ level ->
98 case bracketOK level of {
99 Nothing -> failWithTc (illegalBracket level) ;
102 -- Typecheck expr to make sure it is valid,
103 -- but throw away the results. We'll type check
104 -- it again when we actually use it.
106 newMutVar [] `thenM` \ pending_splices ->
107 getLIEVar `thenM` \ lie_var ->
109 setStage (Brack next_level pending_splices lie_var) (
110 getLIE (tc_bracket brack)
111 ) `thenM` \ (meta_ty, lie) ->
112 tcSimplifyBracket lie `thenM_`
114 -- Make the expected type have the right shape
115 boxyUnify meta_ty res_ty `thenM_`
117 -- Return the original expression, not the type-decorated one
118 readMutVar pending_splices `thenM` \ pendings ->
119 returnM (noLoc (HsBracketOut brack pendings))
122 tc_bracket :: HsBracket Name -> TcM TcType
124 = tcMetaTy nameTyConName -- Result type is Var (not Q-monadic)
126 tc_bracket (ExpBr expr)
127 = newFlexiTyVarTy liftedTypeKind `thenM` \ any_ty ->
128 tcMonoExpr expr any_ty `thenM_`
129 tcMetaTy expQTyConName
130 -- Result type is Expr (= Q Exp)
132 tc_bracket (TypBr typ)
133 = tcHsSigType ExprSigCtxt typ `thenM_`
134 tcMetaTy typeQTyConName
135 -- Result type is Type (= Q Typ)
137 tc_bracket (DecBr decls)
138 = do { tcTopSrcDecls emptyModDetails decls
139 -- Typecheck the declarations, dicarding the result
140 -- We'll get all that stuff later, when we splice it in
142 ; decl_ty <- tcMetaTy decTyConName
143 ; q_ty <- tcMetaTy qTyConName
144 ; return (mkAppTy q_ty (mkListTy decl_ty))
145 -- Result type is Q [Dec]
149 = failWithTc (ptext SLIT("Tempate Haskell pattern brackets are not supported yet"))
153 %************************************************************************
155 \subsection{Splicing an expression}
157 %************************************************************************
160 tcSpliceExpr (HsSplice name expr) res_ty
161 = setSrcSpan (getLoc expr) $
162 getStage `thenM` \ level ->
163 case spliceOK level of {
164 Nothing -> failWithTc (illegalSplice level) ;
168 Comp -> do { e <- tcTopSplice expr res_ty
169 ; returnM (unLoc e) } ;
170 Brack _ ps_var lie_var ->
172 -- A splice inside brackets
173 -- NB: ignore res_ty, apart from zapping it to a mono-type
174 -- e.g. [| reverse $(h 4) |]
175 -- Here (h 4) :: Q Exp
176 -- but $(h 4) :: forall a.a i.e. anything!
178 unBox res_ty `thenM_`
179 tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
180 setStage (Splice next_level) (
182 tcMonoExpr expr meta_exp_ty
185 -- Write the pending splice into the bucket
186 readMutVar ps_var `thenM` \ ps ->
187 writeMutVar ps_var ((name,expr') : ps) `thenM_`
189 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
192 -- tcTopSplice used to have this:
193 -- Note that we do not decrement the level (to -1) before
194 -- typechecking the expression. For example:
195 -- f x = $( ...$(g 3) ... )
196 -- The recursive call to tcMonoExpr will simply expand the
197 -- inner escape before dealing with the outer one
199 tcTopSplice :: LHsExpr Name -> BoxyRhoType -> TcM (LHsExpr Id)
200 tcTopSplice expr res_ty
201 = tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
203 -- Typecheck the expression
204 tcTopSpliceExpr expr meta_exp_ty `thenM` \ zonked_q_expr ->
206 -- Run the expression
207 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
208 runMetaE convertToHsExpr zonked_q_expr `thenM` \ expr2 ->
210 traceTc (text "Got result" <+> ppr expr2) `thenM_`
212 showSplice "expression"
213 zonked_q_expr (ppr expr2) `thenM_`
215 -- Rename it, but bale out if there are errors
216 -- otherwise the type checker just gives more spurious errors
217 checkNoErrs (rnLExpr expr2) `thenM` \ (exp3, fvs) ->
219 tcMonoExpr exp3 res_ty
222 tcTopSpliceExpr :: LHsExpr Name -> TcType -> TcM (LHsExpr Id)
223 -- Type check an expression that is the body of a top-level splice
224 -- (the caller will compile and run it)
225 tcTopSpliceExpr expr meta_ty
226 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
227 -- if the type checker fails!
229 setStage topSpliceStage $ do
232 do { recordThUse -- Record that TH is used (for pkg depdendency)
234 -- Typecheck the expression
235 ; (expr', lie) <- getLIE (tcMonoExpr expr meta_ty)
237 -- Solve the constraints
238 ; const_binds <- tcSimplifyTop lie
241 ; zonkTopLExpr (mkHsDictLet const_binds expr') }
245 %************************************************************************
249 %************************************************************************
251 Very like splicing an expression, but we don't yet share code.
254 kcSpliceType (HsSplice name hs_expr)
255 = setSrcSpan (getLoc hs_expr) $ do
257 ; case spliceOK level of {
258 Nothing -> failWithTc (illegalSplice level) ;
259 Just next_level -> do
262 Comp -> do { (t,k) <- kcTopSpliceType hs_expr
263 ; return (unLoc t, k) } ;
264 Brack _ ps_var lie_var -> do
266 { -- A splice inside brackets
267 ; meta_ty <- tcMetaTy typeQTyConName
268 ; expr' <- setStage (Splice next_level) $
270 tcMonoExpr hs_expr meta_ty
272 -- Write the pending splice into the bucket
273 ; ps <- readMutVar ps_var
274 ; writeMutVar ps_var ((name,expr') : ps)
276 -- e.g. [| Int -> $(h 4) |]
277 -- Here (h 4) :: Q Type
278 -- but $(h 4) :: forall a.a i.e. any kind
280 ; returnM (panic "kcSpliceType", kind) -- The returned type is ignored
283 kcTopSpliceType :: LHsExpr Name -> TcM (LHsType Name, TcKind)
285 = do { meta_ty <- tcMetaTy typeQTyConName
287 -- Typecheck the expression
288 ; zonked_q_expr <- tcTopSpliceExpr expr meta_ty
290 -- Run the expression
291 ; traceTc (text "About to run" <+> ppr zonked_q_expr)
292 ; hs_ty2 <- runMetaT convertToHsType zonked_q_expr
294 ; traceTc (text "Got result" <+> ppr hs_ty2)
296 ; showSplice "type" zonked_q_expr (ppr hs_ty2)
298 -- Rename it, but bale out if there are errors
299 -- otherwise the type checker just gives more spurious errors
300 ; let doc = ptext SLIT("In the spliced type") <+> ppr hs_ty2
301 ; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)
306 %************************************************************************
308 \subsection{Splicing an expression}
310 %************************************************************************
313 -- Always at top level
314 -- Type sig at top of file:
315 -- tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
317 = do { meta_dec_ty <- tcMetaTy decTyConName
318 ; meta_q_ty <- tcMetaTy qTyConName
319 ; let list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
320 ; zonked_q_expr <- tcTopSpliceExpr expr list_q
322 -- Run the expression
323 ; traceTc (text "About to run" <+> ppr zonked_q_expr)
324 ; decls <- runMetaD convertToHsDecls zonked_q_expr
326 ; traceTc (text "Got result" <+> vcat (map ppr decls))
327 ; showSplice "declarations"
329 (ppr (getLoc expr) $$ (vcat (map ppr decls)))
332 where handleErrors :: [Either a Message] -> TcM [a]
333 handleErrors [] = return []
334 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
335 handleErrors (Right m:xs) = do addErrTc m
340 %************************************************************************
342 \subsection{Running an expression}
344 %************************************************************************
347 runMetaE :: (SrcSpan -> TH.Exp -> Either Message (LHsExpr RdrName))
348 -> LHsExpr Id -- Of type (Q Exp)
349 -> TcM (LHsExpr RdrName)
352 runMetaT :: (SrcSpan -> TH.Type -> Either Message (LHsType RdrName))
353 -> LHsExpr Id -- Of type (Q Type)
354 -> TcM (LHsType RdrName)
357 runMetaD :: (SrcSpan -> [TH.Dec] -> Either Message [LHsDecl RdrName])
358 -> LHsExpr Id -- Of type Q [Dec]
359 -> TcM [LHsDecl RdrName]
362 runMeta :: (SrcSpan -> th_syn -> Either Message hs_syn)
363 -> LHsExpr Id -- Of type X
364 -> TcM hs_syn -- Of type t
367 #if defined(GHCI) && defined(DEBUGGER)
368 ds_expr <- unsetOptM Opt_Debugging $ initDsTc (dsLExpr expr)
370 ds_expr <- initDsTc (dsLExpr expr)
372 -- Compile and link it; might fail if linking fails
373 ; hsc_env <- getTopEnv
374 ; src_span <- getSrcSpanM
375 ; either_hval <- tryM $ ioToTcRn $
376 HscMain.compileExpr hsc_env src_span ds_expr
377 ; case either_hval of {
378 Left exn -> failWithTc (mk_msg "compile and link" exn) ;
381 { -- Coerce it to Q t, and run it
382 -- Running might fail if it throws an exception of any kind (hence tryAllM)
383 -- including, say, a pattern-match exception in the code we are running
385 -- We also do the TH -> HS syntax conversion inside the same
386 -- exception-cacthing thing so that if there are any lurking
387 -- exceptions in the data structure returned by hval, we'll
388 -- encounter them inside the try
389 either_tval <- tryAllM $ do
390 { th_syn <- TH.runQ (unsafeCoerce# hval)
391 ; case convert (getLoc expr) th_syn of
392 Left err -> do { addErrTc err; return Nothing }
393 Right hs_syn -> return (Just hs_syn) }
395 ; case either_tval of
396 Right (Just v) -> return v
397 Right Nothing -> failM -- Error already in Tc monad
398 Left exn -> failWithTc (mk_msg "run" exn) -- Exception
401 mk_msg s exn = vcat [text "Exception when trying to" <+> text s <+> text "compile-time code:",
402 nest 2 (text (Panic.showException exn)),
403 nest 2 (text "Code:" <+> ppr expr)]
406 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
409 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
410 qNewName s = do { u <- newUnique
412 ; return (TH.mkNameU s i) }
414 qReport True msg = addErr (text msg)
415 qReport False msg = addReport (text msg)
417 qCurrentModule = do { m <- getModule;
418 return (moduleNameString (moduleName m)) }
419 -- ToDo: is throwing away the package name ok here?
423 -- For qRecover, discard error messages if
424 -- the recovery action is chosen. Otherwise
425 -- we'll only fail higher up. c.f. tryTcLIE_
426 qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main
428 Just val -> do { addMessages msgs -- There might be warnings
430 Nothing -> recover -- Discard all msgs
433 qRunIO io = ioToTcRn io
437 %************************************************************************
439 \subsection{Errors and contexts}
441 %************************************************************************
444 showSplice :: String -> LHsExpr Id -> SDoc -> TcM ()
445 showSplice what before after
446 = getSrcSpanM `thenM` \ loc ->
447 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
448 nest 2 (sep [nest 2 (ppr before),
453 = ptext SLIT("Illegal bracket at level") <+> ppr level
456 = ptext SLIT("Illegal splice at level") <+> ppr level
462 %************************************************************************
466 %************************************************************************
470 reify :: TH.Name -> TcM TH.Info
472 = do { name <- lookupThName th_name
473 ; thing <- tcLookupTh name
474 -- ToDo: this tcLookup could fail, which would give a
475 -- rather unhelpful error message
476 ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
480 ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
481 ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
482 ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
484 lookupThName :: TH.Name -> TcM Name
485 lookupThName th_name@(TH.Name occ flavour)
486 = do { let rdr_name = thRdrName guessed_ns occ_str flavour
488 -- Repeat much of lookupOccRn, becase we want
489 -- to report errors in a TH-relevant way
490 ; rdr_env <- getLocalRdrEnv
491 ; case lookupLocalRdrEnv rdr_env rdr_name of
492 Just name -> return name
493 Nothing | not (isSrcRdrName rdr_name) -- Exact, Orig
494 -> lookupImportedName rdr_name
495 | otherwise -- Unqual, Qual
497 mb_name <- lookupSrcOcc_maybe rdr_name
499 Just name -> return name
500 Nothing -> failWithTc (notInScope th_name) }
503 -- guessed_ns is the name space guessed from looking at the TH name
504 guessed_ns | isLexCon (mkFastString occ_str) = OccName.dataName
505 | otherwise = OccName.varName
506 occ_str = TH.occString occ
508 tcLookupTh :: Name -> TcM TcTyThing
509 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
510 -- it gives a reify-related error message on failure, whereas in the normal
511 -- tcLookup, failure is a bug.
513 = do { (gbl_env, lcl_env) <- getEnvs
514 ; case lookupNameEnv (tcl_env lcl_env) name of {
515 Just thing -> returnM thing;
517 { if nameIsLocalOrFrom (tcg_mod gbl_env) name
518 then -- It's defined in this module
519 case lookupNameEnv (tcg_type_env gbl_env) name of
520 Just thing -> return (AGlobal thing)
521 Nothing -> failWithTc (notInEnv name)
523 else do -- It's imported
524 { (eps,hpt) <- getEpsAndHpt
526 ; case lookupType dflags hpt (eps_PTE eps) name of
527 Just thing -> return (AGlobal thing)
528 Nothing -> do { thing <- tcImportDecl name
529 ; return (AGlobal thing) }
530 -- Imported names should always be findable;
531 -- if not, we fail hard in tcImportDecl
534 notInScope :: TH.Name -> SDoc
535 notInScope th_name = quotes (text (TH.pprint th_name)) <+>
536 ptext SLIT("is not in scope at a reify")
537 -- Ugh! Rather an indirect way to display the name
539 notInEnv :: Name -> SDoc
540 notInEnv name = quotes (ppr name) <+>
541 ptext SLIT("is not in the type environment at a reify")
543 ------------------------------
544 reifyThing :: TcTyThing -> TcM TH.Info
545 -- The only reason this is monadic is for error reporting,
546 -- which in turn is mainly for the case when TH can't express
547 -- some random GHC extension
549 reifyThing (AGlobal (AnId id))
550 = do { ty <- reifyType (idType id)
551 ; fix <- reifyFixity (idName id)
552 ; let v = reifyName id
553 ; case globalIdDetails id of
554 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
555 other -> return (TH.VarI v ty Nothing fix)
558 reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc
559 reifyThing (AGlobal (AClass cls)) = reifyClass cls
560 reifyThing (AGlobal (ADataCon dc))
561 = do { let name = dataConName dc
562 ; ty <- reifyType (idType (dataConWrapId dc))
563 ; fix <- reifyFixity name
564 ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
566 reifyThing (ATcId {tct_id = id, tct_type = ty})
567 = do { ty1 <- zonkTcType ty -- Make use of all the info we have, even
568 -- though it may be incomplete
569 ; ty2 <- reifyType ty1
570 ; fix <- reifyFixity (idName id)
571 ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
573 reifyThing (ATyVar tv ty)
574 = do { ty1 <- zonkTcType ty
575 ; ty2 <- reifyType ty1
576 ; return (TH.TyVarI (reifyName tv) ty2) }
578 ------------------------------
579 reifyTyCon :: TyCon -> TcM TH.Info
581 | isFunTyCon tc = return (TH.PrimTyConI (reifyName tc) 2 False)
582 | isPrimTyCon tc = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc))
584 = do { let (tvs, rhs) = synTyConDefn tc
585 ; rhs' <- reifyType rhs
586 ; return (TH.TyConI $
587 TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
590 = do { cxt <- reifyCxt (tyConStupidTheta tc)
591 ; cons <- mapM reifyDataCon (tyConDataCons tc)
592 ; let name = reifyName tc
593 tvs = reifyTyVars (tyConTyVars tc)
594 deriv = [] -- Don't know about deriving
595 decl | isNewTyCon tc = TH.NewtypeD cxt name tvs (head cons) deriv
596 | otherwise = TH.DataD cxt name tvs cons deriv
597 ; return (TH.TyConI decl) }
599 reifyDataCon :: DataCon -> TcM TH.Con
601 | isVanillaDataCon dc
602 = do { arg_tys <- reifyTypes (dataConOrigArgTys dc)
603 ; let stricts = map reifyStrict (dataConStrictMarks dc)
604 fields = dataConFieldLabels dc
608 ; ASSERT( length arg_tys == length stricts )
609 if not (null fields) then
610 return (TH.RecC name (zip3 (map reifyName fields) stricts arg_tys))
612 if dataConIsInfix dc then
613 ASSERT( length arg_tys == 2 )
614 return (TH.InfixC (s1,a1) name (s2,a2))
616 return (TH.NormalC name (stricts `zip` arg_tys)) }
618 = failWithTc (ptext SLIT("Can't reify a non-Haskell-98 data constructor:")
621 ------------------------------
622 reifyClass :: Class -> TcM TH.Info
624 = do { cxt <- reifyCxt theta
625 ; ops <- mapM reify_op op_stuff
626 ; return (TH.ClassI $ TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) fds' ops) }
628 (tvs, fds, theta, _, _, op_stuff) = classExtraBigSig cls
629 fds' = map reifyFunDep fds
630 reify_op (op, _) = do { ty <- reifyType (idType op)
631 ; return (TH.SigD (reifyName op) ty) }
633 ------------------------------
634 reifyType :: TypeRep.Type -> TcM TH.Type
635 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
636 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
637 reifyType (NoteTy _ ty) = reifyType ty
638 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
639 reifyType (FunTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
640 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt;
641 ; tau' <- reifyType tau
642 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
644 (tvs, cxt, tau) = tcSplitSigmaTy ty
645 reifyTypes = mapM reifyType
646 reifyCxt = mapM reifyPred
648 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
649 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
651 reifyTyVars :: [TyVar] -> [TH.Name]
652 reifyTyVars = map reifyName
654 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
655 reify_tc_app tc tys = do { tys' <- reifyTypes tys
656 ; return (foldl TH.AppT (TH.ConT tc) tys') }
658 reifyPred :: TypeRep.PredType -> TcM TH.Type
659 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
660 reifyPred p@(IParam _ _) = noTH SLIT("implicit parameters") (ppr p)
663 ------------------------------
664 reifyName :: NamedThing n => n -> TH.Name
666 | isExternalName name = mk_varg pkg_str mod_str occ_str
667 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
668 -- Many of the things we reify have local bindings, and
669 -- NameL's aren't supposed to appear in binding positions, so
670 -- we use NameU. When/if we start to reify nested things, that
671 -- have free variables, we may need to generate NameL's for them.
674 mod = nameModule name
675 pkg_str = packageIdString (modulePackageId mod)
676 mod_str = moduleNameString (moduleName mod)
677 occ_str = occNameString occ
678 occ = nameOccName name
679 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
680 | OccName.isVarOcc occ = TH.mkNameG_v
681 | OccName.isTcOcc occ = TH.mkNameG_tc
682 | otherwise = pprPanic "reifyName" (ppr name)
684 ------------------------------
685 reifyFixity :: Name -> TcM TH.Fixity
687 = do { fix <- lookupFixityRn name
688 ; return (conv_fix fix) }
690 conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
691 conv_dir BasicTypes.InfixR = TH.InfixR
692 conv_dir BasicTypes.InfixL = TH.InfixL
693 conv_dir BasicTypes.InfixN = TH.InfixN
695 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
696 reifyStrict MarkedStrict = TH.IsStrict
697 reifyStrict MarkedUnboxed = TH.IsStrict
698 reifyStrict NotMarkedStrict = TH.NotStrict
700 ------------------------------
701 noTH :: LitString -> SDoc -> TcM a
702 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+>
703 ptext SLIT("in Template Haskell:"),