d191fcdc607792b93dea31e6f387515bf148d3af
[ghc-hetmet.git] / ghc / compiler / typecheck / TcSplice.lhs
1 2%
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcSplice]{Template Haskell splices}
5
6 \begin{code}
7 module TcSplice( tcSpliceExpr, tcSpliceDecls, tcBracket ) where
8
9 #include "HsVersions.h"
10
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
15
16 import qualified Language.Haskell.THSyntax as Meta
17
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 )
31 import Name             ( Name )
32 import TcRnMonad
33
34 import TysWiredIn       ( mkListTy )
35 import DsMeta           ( exprTyConName, declTyConName, decTyConName, qTyConName )
36 import ErrUtils (Message)
37 import Outputable
38 import Panic            ( showException )
39 import GHC.Base         ( unsafeCoerce# )       -- Should have a better home in the module hierarchy
40 import Monad (liftM)
41 \end{code}
42
43
44 %************************************************************************
45 %*                                                                      *
46 \subsection{Main interface + stubs for the non-GHCI case
47 %*                                                                      *
48 %************************************************************************
49
50 \begin{code}
51 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
52
53 tcSpliceExpr :: Name 
54              -> RenamedHsExpr
55              -> TcType
56              -> TcM TcExpr
57
58 #ifndef GHCI
59 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
60 tcSpliceDecls e     = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
61 #else
62 \end{code}
63
64 %************************************************************************
65 %*                                                                      *
66 \subsection{Quoting an expression}
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 tcBracket :: HsBracket Name -> TcM TcType
72 tcBracket brack
73   = getStage                            `thenM` \ level ->
74     case bracketOK level of {
75         Nothing         -> failWithTc (illegalBracket level) ;
76         Just next_level ->
77
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 ->
83
84     setStage (Brack next_level pending_splices lie_var) (
85         getLIE (tc_bracket brack)
86     )                                   `thenM` \ (meta_ty, lie) ->
87     tcSimplifyBracket lie               `thenM_`  
88
89     unifyTauTy res_ty meta_ty           `thenM_`
90
91         -- Return the original expression, not the type-decorated one
92     readMutVar pending_splices          `thenM` \ pendings ->
93     returnM (HsBracketOut brack pendings)
94     }
95
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)
101
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
108
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]
113 \end{code}
114
115
116 %************************************************************************
117 %*                                                                      *
118 \subsection{Splicing an expression}
119 %*                                                                      *
120 %************************************************************************
121
122 \begin{code}
123 tcSpliceExpr name expr res_ty
124   = getStage            `thenM` \ level ->
125     case spliceOK level of {
126         Nothing         -> failWithTc (illegalSplice level) ;
127         Just next_level -> 
128
129     case level of {
130         Comp                   -> tcTopSplice expr res_ty ;
131         Brack _ ps_var lie_var ->  
132
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!
138
139     zapToType res_ty                            `thenM_`
140     tcMetaTy exprTyConName                      `thenM` \ meta_exp_ty ->
141     setStage (Splice next_level) (
142         setLIEVar lie_var          $
143         tcMonoExpr expr meta_exp_ty
144     )                                           `thenM` \ expr' ->
145
146         -- Write the pending splice into the bucket
147     readMutVar ps_var                           `thenM` \ ps ->
148     writeMutVar ps_var ((name,expr') : ps)      `thenM_`
149
150     returnM (panic "tcSpliceExpr")      -- The returned expression is ignored
151     }} 
152
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
159
160 tcTopSplice expr res_ty
161   = tcMetaTy exprTyConName              `thenM` \ meta_exp_ty ->
162
163         -- Typecheck the expression
164     tcTopSpliceExpr expr meta_exp_ty    `thenM` \ zonked_q_expr ->
165
166         -- Run the expression
167     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
168     runMetaE zonked_q_expr              `thenM` \ simple_expr ->
169   
170     let 
171         -- simple_expr :: Meta.Exp
172
173         expr2 :: RdrNameHsExpr
174         expr2 = convertToHsExpr simple_expr 
175     in
176     traceTc (text "Got result" <+> ppr expr2)   `thenM_`
177
178     showSplice "expression" 
179                zonked_q_expr (ppr expr2)        `thenM_`
180     initRn SourceMode (rnExpr expr2)            `thenM` \ (exp3, fvs) ->
181     importSupportingDecls fvs                   `thenM` \ env ->
182
183     setGblEnv env (tcMonoExpr exp3 res_ty)
184
185
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!
192
193     setStage topSpliceStage $
194
195         -- Typecheck the expression
196     getLIE (tcMonoExpr expr meta_ty)    `thenM` \ (expr', lie) ->
197
198         -- Solve the constraints
199     tcSimplifyTop lie                   `thenM` \ const_binds ->
200         
201         -- And zonk it
202     zonkTopExpr (mkHsLet const_binds expr')
203 \end{code}
204
205
206 %************************************************************************
207 %*                                                                      *
208 \subsection{Splicing an expression}
209 %*                                                                      *
210 %************************************************************************
211
212 \begin{code}
213 -- Always at top level
214 tcSpliceDecls expr
215   = tcMetaTy decTyConName               `thenM` \ meta_dec_ty ->
216     tcMetaTy qTyConName                 `thenM` \ meta_q_ty ->
217     let
218         list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
219     in
220     tcTopSpliceExpr expr list_q         `thenM` \ zonked_q_expr ->
221
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_`
231     returnM decls
232
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
237                                        handleErrors xs
238 \end{code}
239
240
241 %************************************************************************
242 %*                                                                      *
243 \subsection{Running an expression}
244 %*                                                                      *
245 %************************************************************************
246
247 \begin{code}
248 runMetaE :: TypecheckedHsExpr   -- Of type (Q Exp)
249          -> TcM Meta.Exp        -- Of type Exp
250 runMetaE e = runMeta e
251
252 runMetaD :: TypecheckedHsExpr   -- Of type Q [Dec]
253          -> TcM [Meta.Dec]      -- Of type [Dec]
254 runMetaD e = runMeta e
255
256 runMeta :: TypecheckedHsExpr    -- Of type X
257         -> TcM t                -- Of type t
258 runMeta expr
259   = getTopEnv           `thenM` \ top_env ->
260     getGblEnv           `thenM` \ tcg_env ->
261     getEps              `thenM` \ eps ->
262     getNameCache        `thenM` \ name_cache -> 
263     getModule           `thenM` \ this_mod ->
264     let
265         ghci_mode = top_mode top_env
266
267         hsc_env = HscEnv { hsc_mode = ghci_mode, hsc_HPT = top_hpt top_env,
268                            hsc_dflags = top_dflags top_env }
269
270         pcs = PCS { pcs_nc = name_cache, pcs_EPS = eps }
271
272         type_env = tcg_type_env tcg_env
273         rdr_env  = tcg_rdr_env tcg_env
274     in
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
278     tryM (ioToTcRn (do
279         hval <- HscMain.compileExpr 
280                       hsc_env pcs this_mod 
281                       rdr_env type_env expr
282         Meta.runQ (unsafeCoerce# hval)          -- Coerce it to Q t, and run it
283     ))                                  `thenM` \ either_tval ->
284
285     case either_tval of
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)])])
289           Right v  -> returnM v
290 \end{code}
291
292
293
294 -----------------------------------
295         Random comments
296
297
298       module Foo where
299         import Lib( g :: Int -> M Exp )
300         h x = not x     
301         f x y = [| \z -> (x, $(g y), z, map, h) |]
302
303         h p = $( (\q r -> if q then [| \s -> (p,r,s) |] 
304                                else ... ) True 3)   )
305
306 ==> core
307
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",
314                                  Glob "Foo" "h"])
315
316
317         h :: Tree Int -> M Exp
318         h = \p -> \s' -> (p,3,s')
319
320
321                 Bound   Used
322
323         map:    C0      C1      (top-level/imp)
324         x:      C0      C1      (lam/case)
325         y:      C0      C0
326         z:      C1      C1
327
328         p:      C0      S1
329         r:      S0      S1
330         q:      S0      S0
331         s:      S1      S1
332
333 -------
334
335         f x y = lam "z" (tup [lift x, g y, var "z", 
336                               [| map |], [| h |] ])
337 ==> core
338         
339         f = \x y -> lam "z" (tup [lift d x, g y, var "z",
340                                   return (Glob "Prelude" "map"),
341                                   return (Glob "Foo" "h")])
342
343
344
345
346
347
348
349         h :: M Exp -> M Exp
350         h v = [| \x -> map $v x |]
351
352         g :: Tree Int -> M Exp
353         g x = $(h [| x |])
354 ==>
355         g x = \x' -> map x x'
356
357 *** Simon claims x does not have to be liftable! **
358         
359 Level 0 compile time
360 Level 1 run time
361 Level 2 code returned by run time (generation time)
362
363 Non-top-level variables
364         x occurs at level 1
365           inside brackets
366             bound at level 0    --> x
367             bound at level 1    --> var "x"
368
369           not inside brackets   --> x
370
371         x at level 2
372           inside brackets
373             bound at level 0    --> x
374             bound at level 1    --> var "x"
375
376         f x = x
377
378 Two successive brackets aren't allowed
379
380
381 %************************************************************************
382 %*                                                                      *
383 \subsection{Errors and contexts}
384 %*                                                                      *
385 %************************************************************************
386
387 \begin{code}
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),
393                                     text "======>",
394                                     nest 2 after])])
395
396 illegalBracket level
397   = ptext SLIT("Illegal bracket at level") <+> ppr level
398
399 illegalSplice level
400   = ptext SLIT("Illegal splice at level") <+> ppr level
401
402 #endif  /* GHCI */
403 \end{code}