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 ( 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(..) )
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, tcMonoExpr )
25 import TcHsSyn ( TcExpr, TypecheckedHsExpr, mkHsLet, zonkTopExpr )
26 import TcSimplify ( tcSimplifyTop, tcSimplifyBracket )
27 import TcUnify ( Expected, zapExpectedTo, zapExpectedType )
28 import TcType ( TcType, openTypeKind, mkAppTy )
29 import TcEnv ( spliceOK, tcMetaTy, bracketOK )
30 import TcMType ( newTyVarTy, UserTypeCtxt(ExprSigCtxt) )
31 import TcHsType ( tcHsSigType )
35 import TysWiredIn ( mkListTy )
36 import DsMeta ( expQTyConName, typeQTyConName, decTyConName, qTyConName )
37 import ErrUtils (Message)
39 import Panic ( showException )
40 import GHC.Base ( unsafeCoerce# ) -- Should have a better home in the module hierarchy
45 %************************************************************************
47 \subsection{Main interface + stubs for the non-GHCI case
49 %************************************************************************
52 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
60 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
61 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
65 %************************************************************************
67 \subsection{Quoting an expression}
69 %************************************************************************
72 tcBracket :: HsBracket Name -> Expected TcType -> TcM TcExpr
73 tcBracket brack res_ty
74 = getStage `thenM` \ level ->
75 case bracketOK level of {
76 Nothing -> failWithTc (illegalBracket level) ;
79 -- Typecheck expr to make sure it is valid,
80 -- but throw away the results. We'll type check
81 -- it again when we actually use it.
82 newMutVar [] `thenM` \ pending_splices ->
83 getLIEVar `thenM` \ lie_var ->
85 setStage (Brack next_level pending_splices lie_var) (
86 getLIE (tc_bracket brack)
87 ) `thenM` \ (meta_ty, lie) ->
88 tcSimplifyBracket lie `thenM_`
90 -- Make the expected type have the right shape
91 zapExpectedTo 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
101 -- tcMetaTy varTyConName
102 -- Result type is Var (not Q-monadic)
104 tc_bracket (ExpBr expr)
105 = newTyVarTy openTypeKind `thenM` \ any_ty ->
106 tcCheckRho expr any_ty `thenM_`
107 tcMetaTy expQTyConName
108 -- Result type is Expr (= Q Exp)
110 tc_bracket (TypBr typ)
111 = tcHsSigType ExprSigCtxt typ `thenM_`
112 tcMetaTy typeQTyConName
113 -- Result type is Type (= Q Typ)
115 tc_bracket (DecBr decls)
116 = tcTopSrcDecls decls `thenM_`
117 -- Typecheck the declarations, dicarding the result
118 -- We'll get all that stuff later, when we splice it in
120 tcMetaTy decTyConName `thenM` \ decl_ty ->
121 tcMetaTy qTyConName `thenM` \ q_ty ->
122 returnM (mkAppTy q_ty (mkListTy decl_ty))
123 -- Result type is Q [Dec]
127 %************************************************************************
129 \subsection{Splicing an expression}
131 %************************************************************************
134 tcSpliceExpr name expr res_ty
135 = getStage `thenM` \ level ->
136 case spliceOK level of {
137 Nothing -> failWithTc (illegalSplice level) ;
141 Comp -> tcTopSplice expr res_ty ;
142 Brack _ ps_var lie_var ->
144 -- A splice inside brackets
145 -- NB: ignore res_ty, apart from zapping it to a mono-type
146 -- e.g. [| reverse $(h 4) |]
147 -- Here (h 4) :: Q Exp
148 -- but $(h 4) :: forall a.a i.e. anything!
150 zapExpectedType res_ty `thenM_`
151 tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
152 setStage (Splice next_level) (
154 tcCheckRho expr meta_exp_ty
157 -- Write the pending splice into the bucket
158 readMutVar ps_var `thenM` \ ps ->
159 writeMutVar ps_var ((name,expr') : ps) `thenM_`
161 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
164 -- tcTopSplice used to have this:
165 -- Note that we do not decrement the level (to -1) before
166 -- typechecking the expression. For example:
167 -- f x = $( ...$(g 3) ... )
168 -- The recursive call to tcMonoExpr will simply expand the
169 -- inner escape before dealing with the outer one
171 tcTopSplice expr res_ty
172 = tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
174 -- Typecheck the expression
175 tcTopSpliceExpr expr meta_exp_ty `thenM` \ zonked_q_expr ->
177 -- Run the expression
178 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
179 runMetaE zonked_q_expr `thenM` \ simple_expr ->
182 -- simple_expr :: Meta.Exp
184 expr2 :: RdrNameHsExpr
185 expr2 = convertToHsExpr simple_expr
187 traceTc (text "Got result" <+> ppr expr2) `thenM_`
189 showSplice "expression"
190 zonked_q_expr (ppr expr2) `thenM_`
191 rnExpr expr2 `thenM` \ (exp3, fvs) ->
193 tcMonoExpr exp3 res_ty
196 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
197 -- Type check an expression that is the body of a top-level splice
198 -- (the caller will compile and run it)
199 tcTopSpliceExpr expr meta_ty
200 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
201 -- if the type checker fails!
203 setStage topSpliceStage $
205 -- Typecheck the expression
206 getLIE (tcCheckRho expr meta_ty) `thenM` \ (expr', lie) ->
208 -- Solve the constraints
209 tcSimplifyTop lie `thenM` \ const_binds ->
212 zonkTopExpr (mkHsLet const_binds expr')
216 %************************************************************************
218 \subsection{Splicing an expression}
220 %************************************************************************
223 -- Always at top level
225 = tcMetaTy decTyConName `thenM` \ meta_dec_ty ->
226 tcMetaTy qTyConName `thenM` \ meta_q_ty ->
228 list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
230 tcTopSpliceExpr expr list_q `thenM` \ zonked_q_expr ->
232 -- Run the expression
233 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
234 runMetaD zonked_q_expr `thenM` \ simple_expr ->
235 -- simple_expr :: [Meta.Dec]
236 -- decls :: [RdrNameHsDecl]
237 handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
238 traceTc (text "Got result" <+> vcat (map ppr decls)) `thenM_`
239 showSplice "declarations"
240 zonked_q_expr (vcat (map ppr decls)) `thenM_`
243 where handleErrors :: [Either a Message] -> TcM [a]
244 handleErrors [] = return []
245 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
246 handleErrors (Right m:xs) = do addErrTc m
251 %************************************************************************
253 \subsection{Running an expression}
255 %************************************************************************
258 runMetaE :: TypecheckedHsExpr -- Of type (Q Exp)
259 -> TcM Meta.Exp -- Of type Exp
260 runMetaE e = runMeta e
262 runMetaD :: TypecheckedHsExpr -- Of type Q [Dec]
263 -> TcM [Meta.Dec] -- Of type [Dec]
264 runMetaD e = runMeta e
266 runMeta :: TypecheckedHsExpr -- Of type X
267 -> TcM t -- Of type t
269 = getTopEnv `thenM` \ hsc_env ->
270 getGblEnv `thenM` \ tcg_env ->
271 getModule `thenM` \ this_mod ->
273 type_env = tcg_type_env tcg_env
274 rdr_env = tcg_rdr_env tcg_env
276 -- Wrap the compile-and-run in an exception-catcher
277 -- Compiling might fail if linking fails
278 -- Running might fail if it throws an exception
280 hval <- HscMain.compileExpr
282 rdr_env type_env expr
283 Meta.runQ (unsafeCoerce# hval) -- Coerce it to Q t, and run it
284 )) `thenM` \ either_tval ->
287 Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:",
288 nest 4 (vcat [text "Code:" <+> ppr expr,
289 text ("Exn: " ++ Panic.showException exn)])])
295 -----------------------------------
300 import Lib( g :: Int -> M Exp )
302 f x y = [| \z -> (x, $(g y), z, map, h) |]
304 h p = $( (\q r -> if q then [| \s -> (p,r,s) |]
309 f :: Liftable a => a -> Int -> M Exp
310 f = /\a -> \d::Liftable a ->
311 \ x y -> genSym "z" `bindM` \ z::String ->
312 g y `bindM` \ vv::Exp ->
313 Lam z (Tup [lift d x, v, Var z,
314 Glob "Prelude" "map",
318 h :: Tree Int -> M Exp
319 h = \p -> \s' -> (p,3,s')
324 map: C0 C1 (top-level/imp)
336 f x y = lam "z" (tup [lift x, g y, var "z",
337 [| map |], [| h |] ])
340 f = \x y -> lam "z" (tup [lift d x, g y, var "z",
341 return (Glob "Prelude" "map"),
342 return (Glob "Foo" "h")])
351 h v = [| \x -> map $v x |]
353 g :: Tree Int -> M Exp
356 g x = \x' -> map x x'
358 *** Simon claims x does not have to be liftable! **
362 Level 2 code returned by run time (generation time)
364 Non-top-level variables
367 bound at level 0 --> x
368 bound at level 1 --> var "x"
370 not inside brackets --> x
374 bound at level 0 --> x
375 bound at level 1 --> var "x"
379 Two successive brackets aren't allowed
382 %************************************************************************
384 \subsection{Errors and contexts}
386 %************************************************************************
389 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
390 showSplice what before after
391 = getSrcLocM `thenM` \ loc ->
392 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
393 nest 2 (sep [nest 2 (ppr before),
398 = ptext SLIT("Illegal bracket at level") <+> ppr level
401 = ptext SLIT("Illegal splice at level") <+> ppr level