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