2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcSplice]{Template Haskell splices}
7 module TcSplice( tcSpliceExpr, tcSpliceDecls, tcBracket ) where
9 #include "HsVersions.h"
11 import HscMain ( compileExpr )
12 import TcRnDriver ( importSupportingDecls, tcTopSrcDecls )
13 -- These imports are the reason that TcSplice
14 -- is very high up the module hierarchy
16 import qualified Language.Haskell.THSyntax as Meta
18 import HscTypes ( HscEnv(..), GhciMode(..), PersistentCompilerState(..), unQualInScope )
19 import HsSyn ( HsBracket(..) )
20 import Convert ( convertToHsExpr, convertToHsDecls )
21 import RnExpr ( rnExpr )
22 import RdrHsSyn ( RdrNameHsExpr, RdrNameHsDecl )
23 import RnHsSyn ( RenamedHsExpr )
24 import TcExpr ( tcMonoExpr )
25 import TcHsSyn ( TcExpr, TypecheckedHsExpr, mkHsLet, zonkTopExpr )
26 import TcSimplify ( tcSimplifyTop )
27 import TcType ( TcType, openTypeKind, mkAppTy )
28 import TcEnv ( spliceOK, tcMetaTy )
29 import TcRnTypes ( TopEnv(..) )
30 import TcMType ( newTyVarTy, zapToType )
34 import TysWiredIn ( mkListTy )
35 import DsMeta ( exprTyConName, declTyConName, decTyConName, qTyConName )
36 import ErrUtils (Message)
38 import Panic ( showException )
39 import GHC.Base ( unsafeCoerce# ) -- Should have a better home in the module hierarchy
44 %************************************************************************
46 \subsection{Main interface + stubs for the non-GHCI case
48 %************************************************************************
51 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
59 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
60 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
64 %************************************************************************
66 \subsection{Splicing an expression}
68 %************************************************************************
71 tcBracket :: HsBracket Name -> TcM TcType
72 tcBracket (ExpBr expr)
73 = newTyVarTy openTypeKind `thenM` \ any_ty ->
74 tcMonoExpr expr any_ty `thenM_`
75 tcMetaTy exprTyConName
76 -- Result type is Expr (= Q Exp)
78 tcBracket (DecBr decls)
79 = tcTopSrcDecls decls `thenM_`
80 tcMetaTy decTyConName `thenM` \ decl_ty ->
81 tcMetaTy qTyConName `thenM` \ q_ty ->
82 returnM (mkAppTy q_ty (mkListTy decl_ty))
83 -- Result type is Q [Dec]
87 %************************************************************************
89 \subsection{Splicing an expression}
91 %************************************************************************
94 tcSpliceExpr name expr res_ty
95 = getStage `thenM` \ level ->
96 case spliceOK level of {
97 Nothing -> failWithTc (illegalSplice level) ;
101 Comp -> tcTopSplice expr res_ty ;
102 Brack _ ps_var lie_var ->
104 -- A splice inside brackets
105 -- NB: ignore res_ty, apart from zapping it to a mono-type
106 -- e.g. [| reverse $(h 4) |]
107 -- Here (h 4) :: Q Exp
108 -- but $(h 4) :: forall a.a i.e. anything!
110 zapToType res_ty `thenM_`
111 tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
112 setStage (Splice next_level) (
114 tcMonoExpr expr meta_exp_ty
117 -- Write the pending splice into the bucket
118 readMutVar ps_var `thenM` \ ps ->
119 writeMutVar ps_var ((name,expr') : ps) `thenM_`
121 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
124 -- tcTopSplice used to have this:
125 -- Note that we do not decrement the level (to -1) before
126 -- typechecking the expression. For example:
127 -- f x = $( ...$(g 3) ... )
128 -- The recursive call to tcMonoExpr will simply expand the
129 -- inner escape before dealing with the outer one
131 tcTopSplice expr res_ty
132 = tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
134 -- Typecheck the expression
135 tcTopSpliceExpr expr meta_exp_ty `thenM` \ zonked_q_expr ->
137 -- Run the expression
138 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
139 runMetaE zonked_q_expr `thenM` \ simple_expr ->
142 -- simple_expr :: Meta.Exp
144 expr2 :: RdrNameHsExpr
145 expr2 = convertToHsExpr simple_expr
147 traceTc (text "Got result" <+> ppr expr2) `thenM_`
149 showSplice "expression"
150 zonked_q_expr (ppr expr2) `thenM_`
151 initRn SourceMode (rnExpr expr2) `thenM` \ (exp3, fvs) ->
152 importSupportingDecls fvs `thenM` \ env ->
154 setGblEnv env (tcMonoExpr exp3 res_ty)
157 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
158 -- Type check an expression that is the body of a top-level splice
159 -- (the caller will compile and run it)
160 tcTopSpliceExpr expr meta_ty
161 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
162 -- if the type checker fails!
164 setStage topSpliceStage $
166 -- Typecheck the expression
167 getLIE (tcMonoExpr expr meta_ty) `thenM` \ (expr', lie) ->
169 -- Solve the constraints
170 tcSimplifyTop lie `thenM` \ const_binds ->
173 zonkTopExpr (mkHsLet const_binds expr')
177 %************************************************************************
179 \subsection{Splicing an expression}
181 %************************************************************************
184 -- Always at top level
186 = tcMetaTy decTyConName `thenM` \ meta_dec_ty ->
187 tcMetaTy qTyConName `thenM` \ meta_q_ty ->
189 list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
191 tcTopSpliceExpr expr list_q `thenM` \ zonked_q_expr ->
193 -- Run the expression
194 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
195 runMetaD zonked_q_expr `thenM` \ simple_expr ->
196 -- simple_expr :: [Meta.Dec]
197 -- decls :: [RdrNameHsDecl]
198 handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
199 traceTc (text "Got result" <+> vcat (map ppr decls)) `thenM_`
200 showSplice "declarations"
201 zonked_q_expr (vcat (map ppr decls)) `thenM_`
204 where handleErrors :: [Either a Message] -> TcM [a]
205 handleErrors [] = return []
206 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
207 handleErrors (Right m:xs) = do addErrTc m
212 %************************************************************************
214 \subsection{Running an expression}
216 %************************************************************************
219 runMetaE :: TypecheckedHsExpr -- Of type (Q Exp)
220 -> TcM Meta.Exp -- Of type Exp
221 runMetaE e = runMeta e
223 runMetaD :: TypecheckedHsExpr -- Of type Q [Dec]
224 -> TcM [Meta.Dec] -- Of type [Dec]
225 runMetaD e = runMeta e
227 runMeta :: TypecheckedHsExpr -- Of type X
228 -> TcM t -- Of type t
230 = getTopEnv `thenM` \ top_env ->
231 getGblEnv `thenM` \ tcg_env ->
232 getEps `thenM` \ eps ->
233 getNameCache `thenM` \ name_cache ->
234 getModule `thenM` \ this_mod ->
236 ghci_mode = top_mode top_env
238 hsc_env = HscEnv { hsc_mode = ghci_mode, hsc_HPT = top_hpt top_env,
239 hsc_dflags = top_dflags top_env }
241 pcs = PCS { pcs_nc = name_cache, pcs_EPS = eps }
243 type_env = tcg_type_env tcg_env
244 rdr_env = tcg_rdr_env tcg_env
246 -- Wrap the compile-and-run in an exception-catcher
247 -- Compiling might fail if linking fails
248 -- Running might fail if it throws an exception
250 hval <- HscMain.compileExpr
252 rdr_env type_env expr
253 Meta.runQ (unsafeCoerce# hval) -- Coerce it to Q t, and run it
254 )) `thenM` \ either_tval ->
257 Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:",
258 nest 4 (vcat [text "Code:" <+> ppr expr,
259 text ("Exn: " ++ Panic.showException exn)])])
265 -----------------------------------
270 import Lib( g :: Int -> M Exp )
272 f x y = [| \z -> (x, $(g y), z, map, h) |]
274 h p = $( (\q r -> if q then [| \s -> (p,r,s) |]
279 f :: Liftable a => a -> Int -> M Exp
280 f = /\a -> \d::Liftable a ->
281 \ x y -> genSym "z" `bindM` \ z::String ->
282 g y `bindM` \ vv::Exp ->
283 Lam z (Tup [lift d x, v, Var z,
284 Glob "Prelude" "map",
288 h :: Tree Int -> M Exp
289 h = \p -> \s' -> (p,3,s')
294 map: C0 C1 (top-level/imp)
306 f x y = lam "z" (tup [lift x, g y, var "z",
307 [| map |], [| h |] ])
310 f = \x y -> lam "z" (tup [lift d x, g y, var "z",
311 return (Glob "Prelude" "map"),
312 return (Glob "Foo" "h")])
321 h v = [| \x -> map $v x |]
323 g :: Tree Int -> M Exp
326 g x = \x' -> map x x'
328 *** Simon claims x does not have to be liftable! **
332 Level 2 code returned by run time (generation time)
334 Non-top-level variables
337 bound at level 0 --> x
338 bound at level 1 --> var "x"
340 not inside brackets --> x
344 bound at level 0 --> x
345 bound at level 1 --> var "x"
349 Two successive brackets aren't allowed
352 %************************************************************************
354 \subsection{Errors and contexts}
356 %************************************************************************
359 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
360 showSplice what before after
361 = getSrcLocM `thenM` \ loc ->
362 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
363 nest 2 (sep [nest 2 (ppr before),
368 = ptext SLIT("Illegal splice at level") <+> ppr level