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 )
37 import GHC.Base ( unsafeCoerce# ) -- Should have a better home in the module hierarchy
41 %************************************************************************
43 \subsection{Main interface + stubs for the non-GHCI case
45 %************************************************************************
48 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
56 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
57 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
61 %************************************************************************
63 \subsection{Splicing an expression}
65 %************************************************************************
68 tcBracket :: HsBracket Name -> TcM TcType
69 tcBracket (ExpBr expr)
70 = newTyVarTy openTypeKind `thenM` \ any_ty ->
71 tcMonoExpr expr any_ty `thenM_`
72 tcMetaTy exprTyConName
73 -- Result type is Expr (= Q Exp)
75 tcBracket (DecBr decls)
76 = tcTopSrcDecls decls `thenM_`
77 tcMetaTy decTyConName `thenM` \ decl_ty ->
78 tcMetaTy qTyConName `thenM` \ q_ty ->
79 returnM (mkAppTy q_ty (mkListTy decl_ty))
80 -- Result type is Q [Dec]
84 %************************************************************************
86 \subsection{Splicing an expression}
88 %************************************************************************
91 tcSpliceExpr name expr res_ty
92 = getStage `thenM` \ level ->
93 case spliceOK level of {
94 Nothing -> failWithTc (illegalSplice level) ;
98 Comp -> tcTopSplice expr res_ty ;
99 Brack _ ps_var lie_var ->
101 -- A splice inside brackets
102 -- NB: ignore res_ty, apart from zapping it to a mono-type
103 -- e.g. [| reverse $(h 4) |]
104 -- Here (h 4) :: Q Exp
105 -- but $(h 4) :: forall a.a i.e. anything!
107 zapToType res_ty `thenM_`
108 tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
109 setStage (Splice next_level) (
111 tcMonoExpr expr meta_exp_ty
114 -- Write the pending splice into the bucket
115 readMutVar ps_var `thenM` \ ps ->
116 writeMutVar ps_var ((name,expr') : ps) `thenM_`
118 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
121 -- tcTopSplice used to have this:
122 -- Note that we do not decrement the level (to -1) before
123 -- typechecking the expression. For example:
124 -- f x = $( ...$(g 3) ... )
125 -- The recursive call to tcMonoExpr will simply expand the
126 -- inner escape before dealing with the outer one
128 tcTopSplice expr res_ty
129 = tcMetaTy exprTyConName `thenM` \ meta_exp_ty ->
130 setStage topSpliceStage (
131 getLIE (tcMonoExpr expr meta_exp_ty)
132 ) `thenM` \ (expr', lie) ->
134 -- Solve the constraints
135 tcSimplifyTop lie `thenM` \ const_binds ->
137 q_expr = mkHsLet const_binds expr'
139 zonkTopExpr q_expr `thenM` \ zonked_q_expr ->
141 -- Run the expression
142 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
143 runMetaE zonked_q_expr `thenM` \ simple_expr ->
146 -- simple_expr :: Meta.Exp
148 expr2 :: RdrNameHsExpr
149 expr2 = convertToHsExpr simple_expr
151 traceTc (text "Got result" <+> ppr expr2) `thenM_`
153 showSplice "expression"
154 zonked_q_expr (ppr expr2) `thenM_`
155 initRn SourceMode (rnExpr expr2) `thenM` \ (exp3, fvs) ->
156 importSupportingDecls fvs `thenM` \ env ->
158 setGblEnv env (tcMonoExpr exp3 res_ty)
162 %************************************************************************
164 \subsection{Splicing an expression}
166 %************************************************************************
169 -- Always at top level
171 = tcMetaTy decTyConName `thenM` \ meta_dec_ty ->
172 tcMetaTy qTyConName `thenM` \ meta_q_ty ->
173 setStage topSpliceStage (
174 getLIE (tcMonoExpr expr (mkAppTy meta_q_ty (mkListTy meta_dec_ty)))
175 ) `thenM` \ (expr', lie) ->
176 -- Solve the constraints
177 tcSimplifyTop lie `thenM` \ const_binds ->
179 q_expr = mkHsLet const_binds expr'
181 zonkTopExpr q_expr `thenM` \ zonked_q_expr ->
183 -- Run the expression
184 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
185 runMetaD zonked_q_expr `thenM` \ simple_expr ->
187 -- simple_expr :: [Meta.Dec]
188 decls :: [RdrNameHsDecl]
189 decls = convertToHsDecls simple_expr
191 traceTc (text "Got result" <+> vcat (map ppr decls)) `thenM_`
192 showSplice "declarations"
193 zonked_q_expr (vcat (map ppr decls)) `thenM_`
198 %************************************************************************
200 \subsection{Running an expression}
202 %************************************************************************
205 runMetaE :: TypecheckedHsExpr -- Of type (Q Exp)
206 -> TcM Meta.Exp -- Of type Exp
207 runMetaE e = runMeta e
209 runMetaD :: TypecheckedHsExpr -- Of type Q [Dec]
210 -> TcM [Meta.Dec] -- Of type [Dec]
211 runMetaD e = runMeta e
213 tcRunQ :: Meta.Q a -> TcM a
214 tcRunQ thing = ioToTcRn (Meta.runQ thing)
216 runMeta :: TypecheckedHsExpr -- Of type X
217 -> TcM t -- Of type t
219 = getTopEnv `thenM` \ top_env ->
220 getGblEnv `thenM` \ tcg_env ->
221 getEps `thenM` \ eps ->
222 getNameCache `thenM` \ name_cache ->
223 getModule `thenM` \ this_mod ->
225 ghci_mode = top_mode top_env
227 hsc_env = HscEnv { hsc_mode = ghci_mode, hsc_HPT = top_hpt top_env,
228 hsc_dflags = top_dflags top_env }
230 pcs = PCS { pcs_nc = name_cache, pcs_EPS = eps }
232 type_env = tcg_type_env tcg_env
233 rdr_env = tcg_rdr_env tcg_env
235 ioToTcRn (HscMain.compileExpr
237 rdr_env type_env expr) `thenM` \ hval ->
239 tryM (tcRunQ (unsafeCoerce# hval)) `thenM` \ either_tval ->
242 Left exn -> failWithTc (vcat [text "Exception when running compile-time code:",
243 nest 4 (vcat [text "Code:" <+> ppr expr,
244 text ("Exn: " ++ show exn)])])
250 -----------------------------------
255 import Lib( g :: Int -> M Exp )
257 f x y = [| \z -> (x, $(g y), z, map, h) |]
259 h p = $( (\q r -> if q then [| \s -> (p,r,s) |]
264 f :: Liftable a => a -> Int -> M Exp
265 f = /\a -> \d::Liftable a ->
266 \ x y -> genSym "z" `bindM` \ z::String ->
267 g y `bindM` \ vv::Exp ->
268 Lam z (Tup [lift d x, v, Var z,
269 Glob "Prelude" "map",
273 h :: Tree Int -> M Exp
274 h = \p -> \s' -> (p,3,s')
279 map: C0 C1 (top-level/imp)
291 f x y = lam "z" (tup [lift x, g y, var "z",
292 [| map |], [| h |] ])
295 f = \x y -> lam "z" (tup [lift d x, g y, var "z",
296 return (Glob "Prelude" "map"),
297 return (Glob "Foo" "h")])
306 h v = [| \x -> map $v x |]
308 g :: Tree Int -> M Exp
311 g x = \x' -> map x x'
313 *** Simon claims x does not have to be liftable! **
317 Level 2 code returned by run time (generation time)
319 Non-top-level variables
322 bound at level 0 --> x
323 bound at level 1 --> var "x"
325 not inside brackets --> x
329 bound at level 0 --> x
330 bound at level 1 --> var "x"
334 Two successive brackets aren't allowed
337 %************************************************************************
339 \subsection{Errors and contexts}
341 %************************************************************************
344 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
345 showSplice what before after
346 = getSrcLocM `thenM` \ loc ->
347 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
348 nest 2 (sep [nest 2 (ppr before),
353 = ptext SLIT("Illegal splice at level") <+> ppr level