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 GHC.Base ( unsafeCoerce# ) -- Should have a better home in the module hierarchy
43 %************************************************************************
45 \subsection{Main interface + stubs for the non-GHCI case
47 %************************************************************************
50 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
58 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
59 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
63 %************************************************************************
65 \subsection{Splicing an expression}
67 %************************************************************************
70 tcBracket :: HsBracket Name -> TcM TcType
71 tcBracket (ExpBr expr)
72 = newTyVarTy openTypeKind `thenM` \ any_ty ->
73 tcMonoExpr expr any_ty `thenM_`
74 tcMetaTy exprTyConName
75 -- Result type is Expr (= Q Exp)
77 tcBracket (DecBr decls)
78 = tcTopSrcDecls decls `thenM_`
79 tcMetaTy decTyConName `thenM` \ decl_ty ->
80 tcMetaTy qTyConName `thenM` \ q_ty ->
81 returnM (mkAppTy q_ty (mkListTy decl_ty))
82 -- Result type is Q [Dec]
86 %************************************************************************
88 \subsection{Splicing an expression}
90 %************************************************************************
93 tcSpliceExpr name expr res_ty
94 = getStage `thenM` \ level ->
95 case spliceOK level of {
96 Nothing -> failWithTc (illegalSplice level) ;
100 Comp -> tcTopSplice expr res_ty ;
101 Brack _ ps_var lie_var ->
103 -- A splice inside brackets
104 -- NB: ignore res_ty, apart from zapping it to a mono-type
105 -- e.g. [| reverse $(h 4) |]
106 -- Here (h 4) :: Q Exp
107 -- but $(h 4) :: forall a.a i.e. anything!
109 zapToType res_ty `thenM_`
110 tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
111 setStage (Splice next_level) (
113 tcMonoExpr expr meta_exp_ty
116 -- Write the pending splice into the bucket
117 readMutVar ps_var `thenM` \ ps ->
118 writeMutVar ps_var ((name,expr') : ps) `thenM_`
120 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
123 -- tcTopSplice used to have this:
124 -- Note that we do not decrement the level (to -1) before
125 -- typechecking the expression. For example:
126 -- f x = $( ...$(g 3) ... )
127 -- The recursive call to tcMonoExpr will simply expand the
128 -- inner escape before dealing with the outer one
130 tcTopSplice expr res_ty
131 = tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
132 setStage topSpliceStage (
133 getLIE (tcMonoExpr expr meta_exp_ty)
134 ) `thenM` \ (expr', lie) ->
136 -- Solve the constraints
137 tcSimplifyTop lie `thenM` \ const_binds ->
139 q_expr = mkHsLet const_binds expr'
141 zonkTopExpr q_expr `thenM` \ zonked_q_expr ->
143 -- Run the expression
144 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
145 runMetaE zonked_q_expr `thenM` \ simple_expr ->
148 -- simple_expr :: Meta.Exp
150 expr2 :: RdrNameHsExpr
151 expr2 = convertToHsExpr simple_expr
153 traceTc (text "Got result" <+> ppr expr2) `thenM_`
155 showSplice "expression"
156 zonked_q_expr (ppr expr2) `thenM_`
157 initRn SourceMode (rnExpr expr2) `thenM` \ (exp3, fvs) ->
158 importSupportingDecls fvs `thenM` \ env ->
160 setGblEnv env (tcMonoExpr exp3 res_ty)
164 %************************************************************************
166 \subsection{Splicing an expression}
168 %************************************************************************
171 -- Always at top level
173 = tcMetaTy decTyConName `thenM` \ meta_dec_ty ->
174 tcMetaTy qTyConName `thenM` \ meta_q_ty ->
175 setStage topSpliceStage (
176 getLIE (tcMonoExpr expr (mkAppTy meta_q_ty (mkListTy meta_dec_ty)))
177 ) `thenM` \ (expr', lie) ->
178 -- Solve the constraints
179 tcSimplifyTop lie `thenM` \ const_binds ->
181 q_expr = mkHsLet const_binds expr'
183 zonkTopExpr q_expr `thenM` \ zonked_q_expr ->
185 -- Run the expression
186 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
187 runMetaD zonked_q_expr `thenM` \ simple_expr ->
188 -- simple_expr :: [Meta.Dec]
189 -- decls :: [RdrNameHsDecl]
190 handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
191 traceTc (text "Got result" <+> vcat (map ppr decls)) `thenM_`
192 showSplice "declarations"
193 zonked_q_expr (vcat (map ppr decls)) `thenM_`
196 where handleErrors :: [Either a Message] -> TcM [a]
197 handleErrors [] = return []
198 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
199 handleErrors (Right m:xs) = do addErrTc m
204 %************************************************************************
206 \subsection{Running an expression}
208 %************************************************************************
211 runMetaE :: TypecheckedHsExpr -- Of type (Q Exp)
212 -> TcM Meta.Exp -- Of type Exp
213 runMetaE e = runMeta e
215 runMetaD :: TypecheckedHsExpr -- Of type Q [Dec]
216 -> TcM [Meta.Dec] -- Of type [Dec]
217 runMetaD e = runMeta e
219 tcRunQ :: Meta.Q a -> TcM a
220 tcRunQ thing = ioToTcRn (Meta.runQ thing)
222 runMeta :: TypecheckedHsExpr -- Of type X
223 -> TcM t -- Of type t
225 = getTopEnv `thenM` \ top_env ->
226 getGblEnv `thenM` \ tcg_env ->
227 getEps `thenM` \ eps ->
228 getNameCache `thenM` \ name_cache ->
229 getModule `thenM` \ this_mod ->
231 ghci_mode = top_mode top_env
233 hsc_env = HscEnv { hsc_mode = ghci_mode, hsc_HPT = top_hpt top_env,
234 hsc_dflags = top_dflags top_env }
236 pcs = PCS { pcs_nc = name_cache, pcs_EPS = eps }
238 type_env = tcg_type_env tcg_env
239 rdr_env = tcg_rdr_env tcg_env
241 ioToTcRn (HscMain.compileExpr
243 rdr_env type_env expr) `thenM` \ hval ->
245 tryM (tcRunQ (unsafeCoerce# hval)) `thenM` \ either_tval ->
248 Left exn -> failWithTc (vcat [text "Exception when running compile-time code:",
249 nest 4 (vcat [text "Code:" <+> ppr expr,
250 text ("Exn: " ++ show exn)])])
256 -----------------------------------
261 import Lib( g :: Int -> M Exp )
263 f x y = [| \z -> (x, $(g y), z, map, h) |]
265 h p = $( (\q r -> if q then [| \s -> (p,r,s) |]
270 f :: Liftable a => a -> Int -> M Exp
271 f = /\a -> \d::Liftable a ->
272 \ x y -> genSym "z" `bindM` \ z::String ->
273 g y `bindM` \ vv::Exp ->
274 Lam z (Tup [lift d x, v, Var z,
275 Glob "Prelude" "map",
279 h :: Tree Int -> M Exp
280 h = \p -> \s' -> (p,3,s')
285 map: C0 C1 (top-level/imp)
297 f x y = lam "z" (tup [lift x, g y, var "z",
298 [| map |], [| h |] ])
301 f = \x y -> lam "z" (tup [lift d x, g y, var "z",
302 return (Glob "Prelude" "map"),
303 return (Glob "Foo" "h")])
312 h v = [| \x -> map $v x |]
314 g :: Tree Int -> M Exp
317 g x = \x' -> map x x'
319 *** Simon claims x does not have to be liftable! **
323 Level 2 code returned by run time (generation time)
325 Non-top-level variables
328 bound at level 0 --> x
329 bound at level 1 --> var "x"
331 not inside brackets --> x
335 bound at level 0 --> x
336 bound at level 1 --> var "x"
340 Two successive brackets aren't allowed
343 %************************************************************************
345 \subsection{Errors and contexts}
347 %************************************************************************
350 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
351 showSplice what before after
352 = getSrcLocM `thenM` \ loc ->
353 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
354 nest 2 (sep [nest 2 (ppr before),
359 = ptext SLIT("Illegal splice at level") <+> ppr level