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, tcWithTempInstEnv )
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{Quoting an expression}
68 %************************************************************************
71 tcBracket :: HsBracket Name -> TcM TcType
73 = getStage `thenM` \ level ->
74 case bracketOK level of {
75 Nothing -> failWithTc (illegalBracket level) ;
78 -- Typecheck expr to make sure it is valid,
79 -- but throw away the results. We'll type check
80 -- it again when we actually use it.
81 newMutVar [] `thenM` \ pending_splices ->
82 getLIEVar `thenM` \ lie_var ->
84 setStage (Brack next_level pending_splices lie_var) (
85 getLIE (tc_bracket brack)
86 ) `thenM` \ (meta_ty, lie) ->
87 tcSimplifyBracket lie `thenM_`
89 unifyTauTy res_ty meta_ty `thenM_`
91 -- Return the original expression, not the type-decorated one
92 readMutVar pending_splices `thenM` \ pendings ->
93 returnM (HsBracketOut brack pendings)
96 tc_bracket (ExpBr expr)
97 = newTyVarTy openTypeKind `thenM` \ any_ty ->
98 tcMonoExpr expr any_ty `thenM_`
99 tcMetaTy exprTyConName
100 -- Result type is Expr (= Q Exp)
102 tc_bracket (DecBr decls)
103 = tcWithTempInstEnv (tcTopSrcDecls decls) `thenM_`
104 -- Typecheck the declarations, dicarding any side effects
105 -- on the instance environment (which is in a mutable variable)
106 -- and the extended environment. We'll get all that stuff
107 -- later, when we splice it in
109 tcMetaTy decTyConName `thenM` \ decl_ty ->
110 tcMetaTy qTyConName `thenM` \ q_ty ->
111 returnM (mkAppTy q_ty (mkListTy decl_ty))
112 -- Result type is Q [Dec]
116 %************************************************************************
118 \subsection{Splicing an expression}
120 %************************************************************************
123 tcSpliceExpr name expr res_ty
124 = getStage `thenM` \ level ->
125 case spliceOK level of {
126 Nothing -> failWithTc (illegalSplice level) ;
130 Comp -> tcTopSplice expr res_ty ;
131 Brack _ ps_var lie_var ->
133 -- A splice inside brackets
134 -- NB: ignore res_ty, apart from zapping it to a mono-type
135 -- e.g. [| reverse $(h 4) |]
136 -- Here (h 4) :: Q Exp
137 -- but $(h 4) :: forall a.a i.e. anything!
139 zapToType res_ty `thenM_`
140 tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
141 setStage (Splice next_level) (
143 tcMonoExpr expr meta_exp_ty
146 -- Write the pending splice into the bucket
147 readMutVar ps_var `thenM` \ ps ->
148 writeMutVar ps_var ((name,expr') : ps) `thenM_`
150 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
153 -- tcTopSplice used to have this:
154 -- Note that we do not decrement the level (to -1) before
155 -- typechecking the expression. For example:
156 -- f x = $( ...$(g 3) ... )
157 -- The recursive call to tcMonoExpr will simply expand the
158 -- inner escape before dealing with the outer one
160 tcTopSplice expr res_ty
161 = tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
163 -- Typecheck the expression
164 tcTopSpliceExpr expr meta_exp_ty `thenM` \ zonked_q_expr ->
166 -- Run the expression
167 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
168 runMetaE zonked_q_expr `thenM` \ simple_expr ->
171 -- simple_expr :: Meta.Exp
173 expr2 :: RdrNameHsExpr
174 expr2 = convertToHsExpr simple_expr
176 traceTc (text "Got result" <+> ppr expr2) `thenM_`
178 showSplice "expression"
179 zonked_q_expr (ppr expr2) `thenM_`
180 initRn SourceMode (rnExpr expr2) `thenM` \ (exp3, fvs) ->
181 importSupportingDecls fvs `thenM` \ env ->
183 setGblEnv env (tcMonoExpr exp3 res_ty)
186 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
187 -- Type check an expression that is the body of a top-level splice
188 -- (the caller will compile and run it)
189 tcTopSpliceExpr expr meta_ty
190 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
191 -- if the type checker fails!
193 setStage topSpliceStage $
195 -- Typecheck the expression
196 getLIE (tcMonoExpr expr meta_ty) `thenM` \ (expr', lie) ->
198 -- Solve the constraints
199 tcSimplifyTop lie `thenM` \ const_binds ->
202 zonkTopExpr (mkHsLet const_binds expr')
206 %************************************************************************
208 \subsection{Splicing an expression}
210 %************************************************************************
213 -- Always at top level
215 = tcMetaTy decTyConName `thenM` \ meta_dec_ty ->
216 tcMetaTy qTyConName `thenM` \ meta_q_ty ->
218 list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
220 tcTopSpliceExpr expr list_q `thenM` \ zonked_q_expr ->
222 -- Run the expression
223 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
224 runMetaD zonked_q_expr `thenM` \ simple_expr ->
225 -- simple_expr :: [Meta.Dec]
226 -- decls :: [RdrNameHsDecl]
227 handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
228 traceTc (text "Got result" <+> vcat (map ppr decls)) `thenM_`
229 showSplice "declarations"
230 zonked_q_expr (vcat (map ppr decls)) `thenM_`
233 where handleErrors :: [Either a Message] -> TcM [a]
234 handleErrors [] = return []
235 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
236 handleErrors (Right m:xs) = do addErrTc m
241 %************************************************************************
243 \subsection{Running an expression}
245 %************************************************************************
248 runMetaE :: TypecheckedHsExpr -- Of type (Q Exp)
249 -> TcM Meta.Exp -- Of type Exp
250 runMetaE e = runMeta e
252 runMetaD :: TypecheckedHsExpr -- Of type Q [Dec]
253 -> TcM [Meta.Dec] -- Of type [Dec]
254 runMetaD e = runMeta e
256 runMeta :: TypecheckedHsExpr -- Of type X
257 -> TcM t -- Of type t
259 = getTopEnv `thenM` \ top_env ->
260 getGblEnv `thenM` \ tcg_env ->
261 getEps `thenM` \ eps ->
262 getNameCache `thenM` \ name_cache ->
263 getModule `thenM` \ this_mod ->
265 ghci_mode = top_mode top_env
267 hsc_env = HscEnv { hsc_mode = ghci_mode, hsc_HPT = top_hpt top_env,
268 hsc_dflags = top_dflags top_env }
270 pcs = PCS { pcs_nc = name_cache, pcs_EPS = eps }
272 type_env = tcg_type_env tcg_env
273 rdr_env = tcg_rdr_env tcg_env
275 -- Wrap the compile-and-run in an exception-catcher
276 -- Compiling might fail if linking fails
277 -- Running might fail if it throws an exception
279 hval <- HscMain.compileExpr
281 rdr_env type_env expr
282 Meta.runQ (unsafeCoerce# hval) -- Coerce it to Q t, and run it
283 )) `thenM` \ either_tval ->
286 Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:",
287 nest 4 (vcat [text "Code:" <+> ppr expr,
288 text ("Exn: " ++ Panic.showException exn)])])
294 -----------------------------------
299 import Lib( g :: Int -> M Exp )
301 f x y = [| \z -> (x, $(g y), z, map, h) |]
303 h p = $( (\q r -> if q then [| \s -> (p,r,s) |]
308 f :: Liftable a => a -> Int -> M Exp
309 f = /\a -> \d::Liftable a ->
310 \ x y -> genSym "z" `bindM` \ z::String ->
311 g y `bindM` \ vv::Exp ->
312 Lam z (Tup [lift d x, v, Var z,
313 Glob "Prelude" "map",
317 h :: Tree Int -> M Exp
318 h = \p -> \s' -> (p,3,s')
323 map: C0 C1 (top-level/imp)
335 f x y = lam "z" (tup [lift x, g y, var "z",
336 [| map |], [| h |] ])
339 f = \x y -> lam "z" (tup [lift d x, g y, var "z",
340 return (Glob "Prelude" "map"),
341 return (Glob "Foo" "h")])
350 h v = [| \x -> map $v x |]
352 g :: Tree Int -> M Exp
355 g x = \x' -> map x x'
357 *** Simon claims x does not have to be liftable! **
361 Level 2 code returned by run time (generation time)
363 Non-top-level variables
366 bound at level 0 --> x
367 bound at level 1 --> var "x"
369 not inside brackets --> x
373 bound at level 0 --> x
374 bound at level 1 --> var "x"
378 Two successive brackets aren't allowed
381 %************************************************************************
383 \subsection{Errors and contexts}
385 %************************************************************************
388 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
389 showSplice what before after
390 = getSrcLocM `thenM` \ loc ->
391 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
392 nest 2 (sep [nest 2 (ppr before),
397 = ptext SLIT("Illegal bracket at level") <+> ppr level
400 = ptext SLIT("Illegal splice at level") <+> ppr level