[project @ 2003-10-09 11:58:39 by simonpj]
[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       ( 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(..) )
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, tcMonoExpr )
25 import TcHsSyn          ( TcExpr, TypecheckedHsExpr, mkHsLet, zonkTopExpr )
26 import TcSimplify       ( tcSimplifyTop, tcSimplifyBracket )
27 import TcUnify          ( Expected, zapExpectedTo, zapExpectedType )
28 import TcType           ( TcType, openTypeKind, mkAppTy )
29 import TcEnv            ( spliceOK, tcMetaTy, bracketOK )
30 import TcMType          ( newTyVarTy, UserTypeCtxt(ExprSigCtxt) )
31 import TcHsType         ( tcHsSigType )
32 import Name             ( Name )
33 import TcRnMonad
34
35 import TysWiredIn       ( mkListTy )
36 import DsMeta           ( expQTyConName, typeQTyConName, 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              -> Expected 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 -> Expected 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         -- Make the expected type have the right shape
91     zapExpectedTo 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 expQTyConName
103         -- Result type is Expr (= Q Exp)
104
105 tc_bracket (TypBr typ) 
106   = tcHsSigType ExprSigCtxt typ         `thenM_`
107     tcMetaTy typeQTyConName
108         -- Result type is Type (= Q Typ)
109
110 tc_bracket (DecBr decls)
111   = tcTopSrcDecls decls         `thenM_`
112         -- Typecheck the declarations, dicarding the result
113         -- We'll get all that stuff later, when we splice it in
114
115     tcMetaTy decTyConName       `thenM` \ decl_ty ->
116     tcMetaTy qTyConName         `thenM` \ q_ty ->
117     returnM (mkAppTy q_ty (mkListTy decl_ty))
118         -- Result type is Q [Dec]
119 \end{code}
120
121
122 %************************************************************************
123 %*                                                                      *
124 \subsection{Splicing an expression}
125 %*                                                                      *
126 %************************************************************************
127
128 \begin{code}
129 tcSpliceExpr name expr res_ty
130   = getStage            `thenM` \ level ->
131     case spliceOK level of {
132         Nothing         -> failWithTc (illegalSplice level) ;
133         Just next_level -> 
134
135     case level of {
136         Comp                   -> tcTopSplice expr res_ty ;
137         Brack _ ps_var lie_var ->  
138
139         -- A splice inside brackets
140         -- NB: ignore res_ty, apart from zapping it to a mono-type
141         -- e.g.   [| reverse $(h 4) |]
142         -- Here (h 4) :: Q Exp
143         -- but $(h 4) :: forall a.a     i.e. anything!
144
145     zapExpectedType res_ty                      `thenM_`
146     tcMetaTy expQTyConName                      `thenM` \ meta_exp_ty ->
147     setStage (Splice next_level) (
148         setLIEVar lie_var          $
149         tcCheckRho expr meta_exp_ty
150     )                                           `thenM` \ expr' ->
151
152         -- Write the pending splice into the bucket
153     readMutVar ps_var                           `thenM` \ ps ->
154     writeMutVar ps_var ((name,expr') : ps)      `thenM_`
155
156     returnM (panic "tcSpliceExpr")      -- The returned expression is ignored
157     }} 
158
159 -- tcTopSplice used to have this:
160 -- Note that we do not decrement the level (to -1) before 
161 -- typechecking the expression.  For example:
162 --      f x = $( ...$(g 3) ... )
163 -- The recursive call to tcMonoExpr will simply expand the 
164 -- inner escape before dealing with the outer one
165
166 tcTopSplice expr res_ty
167   = tcMetaTy expQTyConName              `thenM` \ meta_exp_ty ->
168
169         -- Typecheck the expression
170     tcTopSpliceExpr expr meta_exp_ty    `thenM` \ zonked_q_expr ->
171
172         -- Run the expression
173     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
174     runMetaE zonked_q_expr              `thenM` \ simple_expr ->
175   
176     let 
177         -- simple_expr :: Meta.Exp
178
179         expr2 :: RdrNameHsExpr
180         expr2 = convertToHsExpr simple_expr 
181     in
182     traceTc (text "Got result" <+> ppr expr2)   `thenM_`
183
184     showSplice "expression" 
185                zonked_q_expr (ppr expr2)        `thenM_`
186     rnExpr expr2                                `thenM` \ (exp3, fvs) ->
187
188     tcMonoExpr exp3 res_ty
189
190
191 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
192 -- Type check an expression that is the body of a top-level splice
193 --   (the caller will compile and run it)
194 tcTopSpliceExpr expr meta_ty
195   = checkNoErrs $       -- checkNoErrs: must not try to run the thing
196                         --              if the type checker fails!
197
198     setStage topSpliceStage $
199
200         -- Typecheck the expression
201     getLIE (tcCheckRho expr meta_ty)    `thenM` \ (expr', lie) ->
202
203         -- Solve the constraints
204     tcSimplifyTop lie                   `thenM` \ const_binds ->
205         
206         -- And zonk it
207     zonkTopExpr (mkHsLet const_binds expr')
208 \end{code}
209
210
211 %************************************************************************
212 %*                                                                      *
213 \subsection{Splicing an expression}
214 %*                                                                      *
215 %************************************************************************
216
217 \begin{code}
218 -- Always at top level
219 tcSpliceDecls expr
220   = tcMetaTy decTyConName               `thenM` \ meta_dec_ty ->
221     tcMetaTy qTyConName                 `thenM` \ meta_q_ty ->
222     let
223         list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
224     in
225     tcTopSpliceExpr expr list_q         `thenM` \ zonked_q_expr ->
226
227         -- Run the expression
228     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
229     runMetaD zonked_q_expr              `thenM` \ simple_expr ->
230     -- simple_expr :: [Meta.Dec]
231     -- decls :: [RdrNameHsDecl]
232     handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
233     traceTc (text "Got result" <+> vcat (map ppr decls))        `thenM_`
234     showSplice "declarations"
235                zonked_q_expr (vcat (map ppr decls))             `thenM_`
236     returnM decls
237
238   where handleErrors :: [Either a Message] -> TcM [a]
239         handleErrors [] = return []
240         handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
241         handleErrors (Right m:xs) = do addErrTc m
242                                        handleErrors xs
243 \end{code}
244
245
246 %************************************************************************
247 %*                                                                      *
248 \subsection{Running an expression}
249 %*                                                                      *
250 %************************************************************************
251
252 \begin{code}
253 runMetaE :: TypecheckedHsExpr   -- Of type (Q Exp)
254          -> TcM Meta.Exp        -- Of type Exp
255 runMetaE e = runMeta e
256
257 runMetaD :: TypecheckedHsExpr   -- Of type Q [Dec]
258          -> TcM [Meta.Dec]      -- Of type [Dec]
259 runMetaD e = runMeta e
260
261 runMeta :: TypecheckedHsExpr    -- Of type X
262         -> TcM t                -- Of type t
263 runMeta expr
264   = getTopEnv           `thenM` \ hsc_env ->
265     getGblEnv           `thenM` \ tcg_env ->
266     getModule           `thenM` \ this_mod ->
267     let
268         type_env = tcg_type_env tcg_env
269         rdr_env  = tcg_rdr_env tcg_env
270     in
271         -- Wrap the compile-and-run in an exception-catcher
272         -- Compiling might fail if linking fails
273         -- Running might fail if it throws an exception
274     tryM (ioToTcRn (do
275         hval <- HscMain.compileExpr 
276                       hsc_env this_mod 
277                       rdr_env type_env expr
278         Meta.runQ (unsafeCoerce# hval)          -- Coerce it to Q t, and run it
279     ))                                  `thenM` \ either_tval ->
280
281     case either_tval of
282           Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:", 
283                                         nest 4 (vcat [text "Code:" <+> ppr expr,
284                                                       text ("Exn: " ++ Panic.showException exn)])])
285           Right v  -> returnM v
286 \end{code}
287
288
289
290 -----------------------------------
291         Random comments
292
293
294       module Foo where
295         import Lib( g :: Int -> M Exp )
296         h x = not x     
297         f x y = [| \z -> (x, $(g y), z, map, h) |]
298
299         h p = $( (\q r -> if q then [| \s -> (p,r,s) |] 
300                                else ... ) True 3)   )
301
302 ==> core
303
304         f :: Liftable a => a -> Int -> M Exp
305         f = /\a -> \d::Liftable a ->
306             \ x y -> genSym "z"         `bindM` \ z::String ->
307                      g y                `bindM` \ vv::Exp ->
308                      Lam z (Tup [lift d x, v, Var z, 
309                                  Glob "Prelude" "map",
310                                  Glob "Foo" "h"])
311
312
313         h :: Tree Int -> M Exp
314         h = \p -> \s' -> (p,3,s')
315
316
317                 Bound   Used
318
319         map:    C0      C1      (top-level/imp)
320         x:      C0      C1      (lam/case)
321         y:      C0      C0
322         z:      C1      C1
323
324         p:      C0      S1
325         r:      S0      S1
326         q:      S0      S0
327         s:      S1      S1
328
329 -------
330
331         f x y = lam "z" (tup [lift x, g y, var "z", 
332                               [| map |], [| h |] ])
333 ==> core
334         
335         f = \x y -> lam "z" (tup [lift d x, g y, var "z",
336                                   return (Glob "Prelude" "map"),
337                                   return (Glob "Foo" "h")])
338
339
340
341
342
343
344
345         h :: M Exp -> M Exp
346         h v = [| \x -> map $v x |]
347
348         g :: Tree Int -> M Exp
349         g x = $(h [| x |])
350 ==>
351         g x = \x' -> map x x'
352
353 *** Simon claims x does not have to be liftable! **
354         
355 Level 0 compile time
356 Level 1 run time
357 Level 2 code returned by run time (generation time)
358
359 Non-top-level variables
360         x occurs at level 1
361           inside brackets
362             bound at level 0    --> x
363             bound at level 1    --> var "x"
364
365           not inside brackets   --> x
366
367         x at level 2
368           inside brackets
369             bound at level 0    --> x
370             bound at level 1    --> var "x"
371
372         f x = x
373
374 Two successive brackets aren't allowed
375
376
377 %************************************************************************
378 %*                                                                      *
379 \subsection{Errors and contexts}
380 %*                                                                      *
381 %************************************************************************
382
383 \begin{code}
384 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
385 showSplice what before after
386   = getSrcLocM          `thenM` \ loc ->
387     traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what, 
388                        nest 2 (sep [nest 2 (ppr before),
389                                     text "======>",
390                                     nest 2 after])])
391
392 illegalBracket level
393   = ptext SLIT("Illegal bracket at level") <+> ppr level
394
395 illegalSplice level
396   = ptext SLIT("Illegal splice at level") <+> ppr level
397
398 #endif  /* GHCI */
399 \end{code}