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(..), HsExpr(..) )
20 import Convert ( convertToHsExpr, convertToHsDecls )
21 import RnExpr ( rnExpr )
22 import RdrHsSyn ( RdrNameHsExpr, RdrNameHsDecl )
23 import RnHsSyn ( RenamedHsExpr )
24 import TcExpr ( tcCheckRho )
25 import TcHsSyn ( TcExpr, TypecheckedHsExpr, mkHsLet, zonkTopExpr )
26 import TcSimplify ( tcSimplifyTop, tcSimplifyBracket )
27 import TcUnify ( unifyTauTy )
28 import TcType ( TcType, openTypeKind, mkAppTy )
29 import TcEnv ( spliceOK, tcMetaTy, tcWithTempInstEnv, bracketOK )
30 import TcRnTypes ( TopEnv(..) )
31 import TcMType ( newTyVarTy, zapToType, UserTypeCtxt(ExprSigCtxt) )
32 import TcMonoType ( tcHsSigType )
36 import TysWiredIn ( mkListTy )
37 import DsMeta ( exprTyConName, declTyConName, typeTyConName, decTyConName, qTyConName )
38 import ErrUtils (Message)
40 import Panic ( showException )
41 import GHC.Base ( unsafeCoerce# ) -- Should have a better home in the module hierarchy
46 %************************************************************************
48 \subsection{Main interface + stubs for the non-GHCI case
50 %************************************************************************
53 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
61 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
62 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
66 %************************************************************************
68 \subsection{Quoting an expression}
70 %************************************************************************
73 tcBracket :: HsBracket Name -> TcType -> TcM TcExpr
74 tcBracket brack res_ty
75 = getStage `thenM` \ level ->
76 case bracketOK level of {
77 Nothing -> failWithTc (illegalBracket level) ;
80 -- Typecheck expr to make sure it is valid,
81 -- but throw away the results. We'll type check
82 -- it again when we actually use it.
83 newMutVar [] `thenM` \ pending_splices ->
84 getLIEVar `thenM` \ lie_var ->
86 setStage (Brack next_level pending_splices lie_var) (
87 getLIE (tc_bracket brack)
88 ) `thenM` \ (meta_ty, lie) ->
89 tcSimplifyBracket lie `thenM_`
91 unifyTauTy res_ty meta_ty `thenM_`
93 -- Return the original expression, not the type-decorated one
94 readMutVar pending_splices `thenM` \ pendings ->
95 returnM (HsBracketOut brack pendings)
98 tc_bracket :: HsBracket Name -> TcM TcType
99 tc_bracket (ExpBr expr)
100 = newTyVarTy openTypeKind `thenM` \ any_ty ->
101 tcCheckRho expr any_ty `thenM_`
102 tcMetaTy exprTyConName
103 -- Result type is Expr (= Q Exp)
105 tc_bracket (TypBr typ)
106 = tcHsSigType ExprSigCtxt typ `thenM_`
107 tcMetaTy typeTyConName
108 -- Result type is Type (= Q Typ)
110 tc_bracket (DecBr decls)
111 = tcWithTempInstEnv (tcTopSrcDecls decls) `thenM_`
112 -- Typecheck the declarations, dicarding any side effects
113 -- on the instance environment (which is in a mutable variable)
114 -- and the extended environment. We'll get all that stuff
115 -- later, when we splice it in
117 tcMetaTy decTyConName `thenM` \ decl_ty ->
118 tcMetaTy qTyConName `thenM` \ q_ty ->
119 returnM (mkAppTy q_ty (mkListTy decl_ty))
120 -- Result type is Q [Dec]
124 %************************************************************************
126 \subsection{Splicing an expression}
128 %************************************************************************
131 tcSpliceExpr name expr res_ty
132 = getStage `thenM` \ level ->
133 case spliceOK level of {
134 Nothing -> failWithTc (illegalSplice level) ;
138 Comp -> tcTopSplice expr res_ty ;
139 Brack _ ps_var lie_var ->
141 -- A splice inside brackets
142 -- NB: ignore res_ty, apart from zapping it to a mono-type
143 -- e.g. [| reverse $(h 4) |]
144 -- Here (h 4) :: Q Exp
145 -- but $(h 4) :: forall a.a i.e. anything!
147 zapToType res_ty `thenM_`
148 tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
149 setStage (Splice next_level) (
151 tcCheckRho expr meta_exp_ty
154 -- Write the pending splice into the bucket
155 readMutVar ps_var `thenM` \ ps ->
156 writeMutVar ps_var ((name,expr') : ps) `thenM_`
158 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
161 -- tcTopSplice used to have this:
162 -- Note that we do not decrement the level (to -1) before
163 -- typechecking the expression. For example:
164 -- f x = $( ...$(g 3) ... )
165 -- The recursive call to tcCheckRho will simply expand the
166 -- inner escape before dealing with the outer one
168 tcTopSplice expr res_ty
169 = tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
171 -- Typecheck the expression
172 tcTopSpliceExpr expr meta_exp_ty `thenM` \ zonked_q_expr ->
174 -- Run the expression
175 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
176 runMetaE zonked_q_expr `thenM` \ simple_expr ->
179 -- simple_expr :: Meta.Exp
181 expr2 :: RdrNameHsExpr
182 expr2 = convertToHsExpr simple_expr
184 traceTc (text "Got result" <+> ppr expr2) `thenM_`
186 showSplice "expression"
187 zonked_q_expr (ppr expr2) `thenM_`
188 initRn SourceMode (rnExpr expr2) `thenM` \ (exp3, fvs) ->
189 importSupportingDecls fvs `thenM` \ env ->
191 setGblEnv env (tcCheckRho exp3 res_ty)
194 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
195 -- Type check an expression that is the body of a top-level splice
196 -- (the caller will compile and run it)
197 tcTopSpliceExpr expr meta_ty
198 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
199 -- if the type checker fails!
201 setStage topSpliceStage $
203 -- Typecheck the expression
204 getLIE (tcCheckRho expr meta_ty) `thenM` \ (expr', lie) ->
206 -- Solve the constraints
207 tcSimplifyTop lie `thenM` \ const_binds ->
210 zonkTopExpr (mkHsLet const_binds expr')
214 %************************************************************************
216 \subsection{Splicing an expression}
218 %************************************************************************
221 -- Always at top level
223 = tcMetaTy decTyConName `thenM` \ meta_dec_ty ->
224 tcMetaTy qTyConName `thenM` \ meta_q_ty ->
226 list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
228 tcTopSpliceExpr expr list_q `thenM` \ zonked_q_expr ->
230 -- Run the expression
231 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
232 runMetaD zonked_q_expr `thenM` \ simple_expr ->
233 -- simple_expr :: [Meta.Dec]
234 -- decls :: [RdrNameHsDecl]
235 handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
236 traceTc (text "Got result" <+> vcat (map ppr decls)) `thenM_`
237 showSplice "declarations"
238 zonked_q_expr (vcat (map ppr decls)) `thenM_`
241 where handleErrors :: [Either a Message] -> TcM [a]
242 handleErrors [] = return []
243 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
244 handleErrors (Right m:xs) = do addErrTc m
249 %************************************************************************
251 \subsection{Running an expression}
253 %************************************************************************
256 runMetaE :: TypecheckedHsExpr -- Of type (Q Exp)
257 -> TcM Meta.Exp -- Of type Exp
258 runMetaE e = runMeta e
260 runMetaD :: TypecheckedHsExpr -- Of type Q [Dec]
261 -> TcM [Meta.Dec] -- Of type [Dec]
262 runMetaD e = runMeta e
264 runMeta :: TypecheckedHsExpr -- Of type X
265 -> TcM t -- Of type t
267 = getTopEnv `thenM` \ top_env ->
268 getGblEnv `thenM` \ tcg_env ->
269 getEps `thenM` \ eps ->
270 getNameCache `thenM` \ name_cache ->
271 getModule `thenM` \ this_mod ->
273 ghci_mode = top_mode top_env
275 hsc_env = HscEnv { hsc_mode = ghci_mode, hsc_HPT = top_hpt top_env,
276 hsc_dflags = top_dflags top_env }
278 pcs = PCS { pcs_nc = name_cache, pcs_EPS = eps }
280 type_env = tcg_type_env tcg_env
281 rdr_env = tcg_rdr_env tcg_env
283 -- Wrap the compile-and-run in an exception-catcher
284 -- Compiling might fail if linking fails
285 -- Running might fail if it throws an exception
287 hval <- HscMain.compileExpr
289 rdr_env type_env expr
290 Meta.runQ (unsafeCoerce# hval) -- Coerce it to Q t, and run it
291 )) `thenM` \ either_tval ->
294 Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:",
295 nest 4 (vcat [text "Code:" <+> ppr expr,
296 text ("Exn: " ++ Panic.showException exn)])])
302 -----------------------------------
307 import Lib( g :: Int -> M Exp )
309 f x y = [| \z -> (x, $(g y), z, map, h) |]
311 h p = $( (\q r -> if q then [| \s -> (p,r,s) |]
316 f :: Liftable a => a -> Int -> M Exp
317 f = /\a -> \d::Liftable a ->
318 \ x y -> genSym "z" `bindM` \ z::String ->
319 g y `bindM` \ vv::Exp ->
320 Lam z (Tup [lift d x, v, Var z,
321 Glob "Prelude" "map",
325 h :: Tree Int -> M Exp
326 h = \p -> \s' -> (p,3,s')
331 map: C0 C1 (top-level/imp)
343 f x y = lam "z" (tup [lift x, g y, var "z",
344 [| map |], [| h |] ])
347 f = \x y -> lam "z" (tup [lift d x, g y, var "z",
348 return (Glob "Prelude" "map"),
349 return (Glob "Foo" "h")])
358 h v = [| \x -> map $v x |]
360 g :: Tree Int -> M Exp
363 g x = \x' -> map x x'
365 *** Simon claims x does not have to be liftable! **
369 Level 2 code returned by run time (generation time)
371 Non-top-level variables
374 bound at level 0 --> x
375 bound at level 1 --> var "x"
377 not inside brackets --> x
381 bound at level 0 --> x
382 bound at level 1 --> var "x"
386 Two successive brackets aren't allowed
389 %************************************************************************
391 \subsection{Errors and contexts}
393 %************************************************************************
396 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
397 showSplice what before after
398 = getSrcLocM `thenM` \ loc ->
399 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
400 nest 2 (sep [nest 2 (ppr before),
405 = ptext SLIT("Illegal bracket at level") <+> ppr level
408 = ptext SLIT("Illegal splice at level") <+> ppr level