3278fd9453456dcc3209f27b5606c06fb2802ec1
[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(..), HsExpr(..) )
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, 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 )
32 import Name             ( Name )
33 import TcRnMonad
34
35 import TysWiredIn       ( mkListTy )
36 import DsMeta           ( exprTyConName, declTyConName, decTyConName, qTyConName )
37 import ErrUtils (Message)
38 import Outputable
39 import Panic            ( showException )
40 import GHC.Base         ( unsafeCoerce# )       -- Should have a better home in the module hierarchy
41 import Monad (liftM)
42 \end{code}
43
44
45 %************************************************************************
46 %*                                                                      *
47 \subsection{Main interface + stubs for the non-GHCI case
48 %*                                                                      *
49 %************************************************************************
50
51 \begin{code}
52 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
53
54 tcSpliceExpr :: Name 
55              -> RenamedHsExpr
56              -> TcType
57              -> TcM TcExpr
58
59 #ifndef GHCI
60 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
61 tcSpliceDecls e     = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
62 #else
63 \end{code}
64
65 %************************************************************************
66 %*                                                                      *
67 \subsection{Quoting an expression}
68 %*                                                                      *
69 %************************************************************************
70
71 \begin{code}
72 tcBracket :: HsBracket Name -> TcType -> TcM TcExpr
73 tcBracket brack res_ty
74   = getStage                            `thenM` \ level ->
75     case bracketOK level of {
76         Nothing         -> failWithTc (illegalBracket level) ;
77         Just next_level ->
78
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 ->
84
85     setStage (Brack next_level pending_splices lie_var) (
86         getLIE (tc_bracket brack)
87     )                                   `thenM` \ (meta_ty, lie) ->
88     tcSimplifyBracket lie               `thenM_`  
89
90     unifyTauTy res_ty meta_ty           `thenM_`
91
92         -- Return the original expression, not the type-decorated one
93     readMutVar pending_splices          `thenM` \ pendings ->
94     returnM (HsBracketOut brack pendings)
95     }
96
97 tc_bracket (ExpBr expr) 
98   = newTyVarTy openTypeKind             `thenM` \ any_ty ->
99     tcMonoExpr expr any_ty              `thenM_`
100     tcMetaTy exprTyConName
101         -- Result type is Expr (= Q Exp)
102
103 tc_bracket (DecBr decls)
104   = tcWithTempInstEnv (tcTopSrcDecls decls)     `thenM_`
105         -- Typecheck the declarations, dicarding any side effects
106         -- on the instance environment (which is in a mutable variable)
107         -- and the extended environment.  We'll get all that stuff
108         -- later, when we splice it in
109
110     tcMetaTy decTyConName               `thenM` \ decl_ty ->
111     tcMetaTy qTyConName                 `thenM` \ q_ty ->
112     returnM (mkAppTy q_ty (mkListTy decl_ty))
113         -- Result type is Q [Dec]
114 \end{code}
115
116
117 %************************************************************************
118 %*                                                                      *
119 \subsection{Splicing an expression}
120 %*                                                                      *
121 %************************************************************************
122
123 \begin{code}
124 tcSpliceExpr name expr res_ty
125   = getStage            `thenM` \ level ->
126     case spliceOK level of {
127         Nothing         -> failWithTc (illegalSplice level) ;
128         Just next_level -> 
129
130     case level of {
131         Comp                   -> tcTopSplice expr res_ty ;
132         Brack _ ps_var lie_var ->  
133
134         -- A splice inside brackets
135         -- NB: ignore res_ty, apart from zapping it to a mono-type
136         -- e.g.   [| reverse $(h 4) |]
137         -- Here (h 4) :: Q Exp
138         -- but $(h 4) :: forall a.a     i.e. anything!
139
140     zapToType res_ty                            `thenM_`
141     tcMetaTy exprTyConName                      `thenM` \ meta_exp_ty ->
142     setStage (Splice next_level) (
143         setLIEVar lie_var          $
144         tcMonoExpr expr meta_exp_ty
145     )                                           `thenM` \ expr' ->
146
147         -- Write the pending splice into the bucket
148     readMutVar ps_var                           `thenM` \ ps ->
149     writeMutVar ps_var ((name,expr') : ps)      `thenM_`
150
151     returnM (panic "tcSpliceExpr")      -- The returned expression is ignored
152     }} 
153
154 -- tcTopSplice used to have this:
155 -- Note that we do not decrement the level (to -1) before 
156 -- typechecking the expression.  For example:
157 --      f x = $( ...$(g 3) ... )
158 -- The recursive call to tcMonoExpr will simply expand the 
159 -- inner escape before dealing with the outer one
160
161 tcTopSplice expr res_ty
162   = tcMetaTy exprTyConName              `thenM` \ meta_exp_ty ->
163
164         -- Typecheck the expression
165     tcTopSpliceExpr expr meta_exp_ty    `thenM` \ zonked_q_expr ->
166
167         -- Run the expression
168     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
169     runMetaE zonked_q_expr              `thenM` \ simple_expr ->
170   
171     let 
172         -- simple_expr :: Meta.Exp
173
174         expr2 :: RdrNameHsExpr
175         expr2 = convertToHsExpr simple_expr 
176     in
177     traceTc (text "Got result" <+> ppr expr2)   `thenM_`
178
179     showSplice "expression" 
180                zonked_q_expr (ppr expr2)        `thenM_`
181     initRn SourceMode (rnExpr expr2)            `thenM` \ (exp3, fvs) ->
182     importSupportingDecls fvs                   `thenM` \ env ->
183
184     setGblEnv env (tcMonoExpr exp3 res_ty)
185
186
187 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
188 -- Type check an expression that is the body of a top-level splice
189 --   (the caller will compile and run it)
190 tcTopSpliceExpr expr meta_ty
191   = checkNoErrs $       -- checkNoErrs: must not try to run the thing
192                         --              if the type checker fails!
193
194     setStage topSpliceStage $
195
196         -- Typecheck the expression
197     getLIE (tcMonoExpr expr meta_ty)    `thenM` \ (expr', lie) ->
198
199         -- Solve the constraints
200     tcSimplifyTop lie                   `thenM` \ const_binds ->
201         
202         -- And zonk it
203     zonkTopExpr (mkHsLet const_binds expr')
204 \end{code}
205
206
207 %************************************************************************
208 %*                                                                      *
209 \subsection{Splicing an expression}
210 %*                                                                      *
211 %************************************************************************
212
213 \begin{code}
214 -- Always at top level
215 tcSpliceDecls expr
216   = tcMetaTy decTyConName               `thenM` \ meta_dec_ty ->
217     tcMetaTy qTyConName                 `thenM` \ meta_q_ty ->
218     let
219         list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
220     in
221     tcTopSpliceExpr expr list_q         `thenM` \ zonked_q_expr ->
222
223         -- Run the expression
224     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
225     runMetaD zonked_q_expr              `thenM` \ simple_expr ->
226     -- simple_expr :: [Meta.Dec]
227     -- decls :: [RdrNameHsDecl]
228     handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
229     traceTc (text "Got result" <+> vcat (map ppr decls))        `thenM_`
230     showSplice "declarations"
231                zonked_q_expr (vcat (map ppr decls))             `thenM_`
232     returnM decls
233
234   where handleErrors :: [Either a Message] -> TcM [a]
235         handleErrors [] = return []
236         handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
237         handleErrors (Right m:xs) = do addErrTc m
238                                        handleErrors xs
239 \end{code}
240
241
242 %************************************************************************
243 %*                                                                      *
244 \subsection{Running an expression}
245 %*                                                                      *
246 %************************************************************************
247
248 \begin{code}
249 runMetaE :: TypecheckedHsExpr   -- Of type (Q Exp)
250          -> TcM Meta.Exp        -- Of type Exp
251 runMetaE e = runMeta e
252
253 runMetaD :: TypecheckedHsExpr   -- Of type Q [Dec]
254          -> TcM [Meta.Dec]      -- Of type [Dec]
255 runMetaD e = runMeta e
256
257 runMeta :: TypecheckedHsExpr    -- Of type X
258         -> TcM t                -- Of type t
259 runMeta expr
260   = getTopEnv           `thenM` \ top_env ->
261     getGblEnv           `thenM` \ tcg_env ->
262     getEps              `thenM` \ eps ->
263     getNameCache        `thenM` \ name_cache -> 
264     getModule           `thenM` \ this_mod ->
265     let
266         ghci_mode = top_mode top_env
267
268         hsc_env = HscEnv { hsc_mode = ghci_mode, hsc_HPT = top_hpt top_env,
269                            hsc_dflags = top_dflags top_env }
270
271         pcs = PCS { pcs_nc = name_cache, pcs_EPS = eps }
272
273         type_env = tcg_type_env tcg_env
274         rdr_env  = tcg_rdr_env tcg_env
275     in
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
279     tryM (ioToTcRn (do
280         hval <- HscMain.compileExpr 
281                       hsc_env pcs this_mod 
282                       rdr_env type_env expr
283         Meta.runQ (unsafeCoerce# hval)          -- Coerce it to Q t, and run it
284     ))                                  `thenM` \ either_tval ->
285
286     case either_tval of
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)])])
290           Right v  -> returnM v
291 \end{code}
292
293
294
295 -----------------------------------
296         Random comments
297
298
299       module Foo where
300         import Lib( g :: Int -> M Exp )
301         h x = not x     
302         f x y = [| \z -> (x, $(g y), z, map, h) |]
303
304         h p = $( (\q r -> if q then [| \s -> (p,r,s) |] 
305                                else ... ) True 3)   )
306
307 ==> core
308
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",
315                                  Glob "Foo" "h"])
316
317
318         h :: Tree Int -> M Exp
319         h = \p -> \s' -> (p,3,s')
320
321
322                 Bound   Used
323
324         map:    C0      C1      (top-level/imp)
325         x:      C0      C1      (lam/case)
326         y:      C0      C0
327         z:      C1      C1
328
329         p:      C0      S1
330         r:      S0      S1
331         q:      S0      S0
332         s:      S1      S1
333
334 -------
335
336         f x y = lam "z" (tup [lift x, g y, var "z", 
337                               [| map |], [| h |] ])
338 ==> core
339         
340         f = \x y -> lam "z" (tup [lift d x, g y, var "z",
341                                   return (Glob "Prelude" "map"),
342                                   return (Glob "Foo" "h")])
343
344
345
346
347
348
349
350         h :: M Exp -> M Exp
351         h v = [| \x -> map $v x |]
352
353         g :: Tree Int -> M Exp
354         g x = $(h [| x |])
355 ==>
356         g x = \x' -> map x x'
357
358 *** Simon claims x does not have to be liftable! **
359         
360 Level 0 compile time
361 Level 1 run time
362 Level 2 code returned by run time (generation time)
363
364 Non-top-level variables
365         x occurs at level 1
366           inside brackets
367             bound at level 0    --> x
368             bound at level 1    --> var "x"
369
370           not inside brackets   --> x
371
372         x at level 2
373           inside brackets
374             bound at level 0    --> x
375             bound at level 1    --> var "x"
376
377         f x = x
378
379 Two successive brackets aren't allowed
380
381
382 %************************************************************************
383 %*                                                                      *
384 \subsection{Errors and contexts}
385 %*                                                                      *
386 %************************************************************************
387
388 \begin{code}
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),
394                                     text "======>",
395                                     nest 2 after])])
396
397 illegalBracket level
398   = ptext SLIT("Illegal bracket at level") <+> ppr level
399
400 illegalSplice level
401   = ptext SLIT("Illegal splice at level") <+> ppr level
402
403 #endif  /* GHCI */
404 \end{code}