31205e708d63a0be0a51757467eea03af4a795eb
[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 )
29 import TcRnTypes        ( TopEnv(..) )
30 import TcMType          ( newTyVarTy )
31 import Name             ( Name )
32 import TcRnMonad
33
34 import TysWiredIn       ( mkListTy )
35 import DsMeta           ( exprTyConName, declTyConName, decTyConName, qTyConName )
36 import Outputable
37 import GHC.Base         ( unsafeCoerce# )       -- Should have a better home in the module hierarchy
38 \end{code}
39
40
41 %************************************************************************
42 %*                                                                      *
43 \subsection{Main interface + stubs for the non-GHCI case
44 %*                                                                      *
45 %************************************************************************
46
47 \begin{code}
48 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
49
50 tcSpliceExpr :: Name 
51              -> RenamedHsExpr
52              -> TcType
53              -> TcM TcExpr
54
55 #ifndef GHCI
56 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
57 tcSpliceDecls e     = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
58 #else
59 \end{code}
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection{Splicing an expression}
64 %*                                                                      *
65 %************************************************************************
66
67 \begin{code}
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)
74
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]
81 \end{code}
82
83
84 %************************************************************************
85 %*                                                                      *
86 \subsection{Splicing an expression}
87 %*                                                                      *
88 %************************************************************************
89
90 \begin{code}
91 tcSpliceExpr name expr res_ty
92   = getStage            `thenM` \ level ->
93     case spliceOK level of {
94         Nothing         -> failWithTc (illegalSplice level) ;
95         Just next_level -> 
96
97     case level of {
98         Comp                   -> tcTopSplice expr res_ty ;
99         Brack _ ps_var lie_var ->  
100
101         -- A splice inside brackets
102         -- NB: ignore res_ty
103         -- e.g.   [| reverse $(h 4) |]
104         -- Here (h 4) :: Q Exp
105         -- but $(h 4) :: forall a.a     i.e. anything!
106
107     tcMetaTy exprTyConName                      `thenM` \ meta_exp_ty ->
108     setStage (Splice next_level) (
109         setLIEVar lie_var          $
110         tcMonoExpr expr meta_exp_ty
111     )                                           `thenM` \ expr' ->
112
113         -- Write the pending splice into the bucket
114     readMutVar ps_var                           `thenM` \ ps ->
115     writeMutVar ps_var ((name,expr') : ps)      `thenM_`
116
117     returnM (panic "tcSpliceExpr")      -- The returned expression is ignored
118     }} 
119
120 -- tcTopSplice used to have this:
121 -- Note that we do not decrement the level (to -1) before 
122 -- typechecking the expression.  For example:
123 --      f x = $( ...$(g 3) ... )
124 -- The recursive call to tcMonoExpr will simply expand the 
125 -- inner escape before dealing with the outer one
126
127 tcTopSplice expr res_ty
128   = tcMetaTy exprTyConName              `thenM` \ meta_exp_ty ->
129     setStage topSpliceStage (
130         getLIE (tcMonoExpr expr meta_exp_ty)
131     )                                   `thenM` \ (expr', lie) ->
132
133         -- Solve the constraints
134     tcSimplifyTop lie                   `thenM` \ const_binds ->
135     let 
136         q_expr = mkHsLet const_binds expr'
137     in
138     zonkTopExpr q_expr                  `thenM` \ zonked_q_expr ->
139
140         -- Run the expression
141     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
142     runMetaE zonked_q_expr              `thenM` \ simple_expr ->
143   
144     let 
145         -- simple_expr :: Meta.Exp
146
147         expr2 :: RdrNameHsExpr
148         expr2 = convertToHsExpr simple_expr 
149     in
150     traceTc (text "Got result" <+> ppr expr2)   `thenM_`
151
152     showSplice "expression" 
153                zonked_q_expr (ppr expr2)        `thenM_`
154     initRn SourceMode (rnExpr expr2)            `thenM` \ (exp3, fvs) ->
155     importSupportingDecls fvs                   `thenM` \ env ->
156
157     setGblEnv env (tcMonoExpr exp3 res_ty)
158 \end{code}
159
160
161 %************************************************************************
162 %*                                                                      *
163 \subsection{Splicing an expression}
164 %*                                                                      *
165 %************************************************************************
166
167 \begin{code}
168 -- Always at top level
169 tcSpliceDecls expr
170   = tcMetaTy decTyConName               `thenM` \ meta_dec_ty ->
171     tcMetaTy qTyConName                 `thenM` \ meta_q_ty ->
172     setStage topSpliceStage (
173         getLIE (tcMonoExpr expr (mkAppTy meta_q_ty (mkListTy meta_dec_ty)))
174     )                                   `thenM` \ (expr', lie) ->
175         -- Solve the constraints
176     tcSimplifyTop lie                   `thenM` \ const_binds ->
177     let 
178         q_expr = mkHsLet const_binds expr'
179     in
180     zonkTopExpr q_expr                  `thenM` \ zonked_q_expr ->
181
182         -- Run the expression
183     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
184     runMetaD zonked_q_expr              `thenM` \ simple_expr ->
185     let 
186         -- simple_expr :: [Meta.Dec]
187         decls :: [RdrNameHsDecl]
188         decls = convertToHsDecls simple_expr 
189     in
190     traceTc (text "Got result" <+> vcat (map ppr decls))        `thenM_`
191     showSplice "declarations"
192                zonked_q_expr (vcat (map ppr decls))             `thenM_`
193     returnM decls
194 \end{code}
195
196
197 %************************************************************************
198 %*                                                                      *
199 \subsection{Running an expression}
200 %*                                                                      *
201 %************************************************************************
202
203 \begin{code}
204 runMetaE :: TypecheckedHsExpr   -- Of type (Q Exp)
205          -> TcM Meta.Exp        -- Of type Exp
206 runMetaE e = runMeta e
207
208 runMetaD :: TypecheckedHsExpr   -- Of type Q [Dec]
209          -> TcM [Meta.Dec]      -- Of type [Dec]
210 runMetaD e = runMeta e
211
212 -- Warning: if Q is anything other than IO, we need to change this
213 tcRunQ :: Meta.Q a -> TcM a
214 tcRunQ thing = ioToTcRn thing
215
216
217 runMeta :: TypecheckedHsExpr    -- Of type X
218         -> TcM t                -- Of type t
219 runMeta expr
220   = getTopEnv           `thenM` \ top_env ->
221     getEps              `thenM` \ eps ->
222     getNameCache        `thenM` \ name_cache -> 
223     getModule           `thenM` \ this_mod ->
224     getGlobalRdrEnv     `thenM` \ rdr_env -> 
225     let
226         ghci_mode = top_mode top_env
227
228         hsc_env = HscEnv { hsc_mode = ghci_mode, hsc_HPT = top_hpt top_env,
229                            hsc_dflags = top_dflags top_env }
230
231         pcs = PCS { pcs_nc = name_cache, pcs_EPS = eps }
232
233         print_unqual = unQualInScope rdr_env
234     in
235     ioToTcRn (HscMain.compileExpr hsc_env pcs this_mod 
236                                   print_unqual expr) `thenM` \ hval ->
237
238     tryM (tcRunQ (unsafeCoerce# hval))  `thenM` \ either_tval ->
239
240     case either_tval of
241           Left exn -> failWithTc (vcat [text "Exception when running compile-time code:", 
242                                         nest 4 (vcat [text "Code:" <+> ppr expr,
243                                                       text ("Exn: " ++ show exn)])])
244           Right v  -> returnM v
245 \end{code}
246
247
248
249 -----------------------------------
250         Random comments
251
252
253       module Foo where
254         import Lib( g :: Int -> M Exp )
255         h x = not x     
256         f x y = [| \z -> (x, $(g y), z, map, h) |]
257
258         h p = $( (\q r -> if q then [| \s -> (p,r,s) |] 
259                                else ... ) True 3)   )
260
261 ==> core
262
263         f :: Liftable a => a -> Int -> M Exp
264         f = /\a -> \d::Liftable a ->
265             \ x y -> genSym "z"         `bindM` \ z::String ->
266                      g y                `bindM` \ vv::Exp ->
267                      Lam z (Tup [lift d x, v, Var z, 
268                                  Glob "Prelude" "map",
269                                  Glob "Foo" "h"])
270
271
272         h :: Tree Int -> M Exp
273         h = \p -> \s' -> (p,3,s')
274
275
276                 Bound   Used
277
278         map:    C0      C1      (top-level/imp)
279         x:      C0      C1      (lam/case)
280         y:      C0      C0
281         z:      C1      C1
282
283         p:      C0      S1
284         r:      S0      S1
285         q:      S0      S0
286         s:      S1      S1
287
288 -------
289
290         f x y = lam "z" (tup [lift x, g y, var "z", 
291                               [| map |], [| h |] ])
292 ==> core
293         
294         f = \x y -> lam "z" (tup [lift d x, g y, var "z",
295                                   return (Glob "Prelude" "map"),
296                                   return (Glob "Foo" "h")])
297
298
299
300
301
302
303
304         h :: M Exp -> M Exp
305         h v = [| \x -> map $v x |]
306
307         g :: Tree Int -> M Exp
308         g x = $(h [| x |])
309 ==>
310         g x = \x' -> map x x'
311
312 *** Simon claims x does not have to be liftable! **
313         
314 Level 0 compile time
315 Level 1 run time
316 Level 2 code returned by run time (generation time)
317
318 Non-top-level variables
319         x occurs at level 1
320           inside brackets
321             bound at level 0    --> x
322             bound at level 1    --> var "x"
323
324           not inside brackets   --> x
325
326         x at level 2
327           inside brackets
328             bound at level 0    --> x
329             bound at level 1    --> var "x"
330
331         f x = x
332
333 Two successive brackets aren't allowed
334
335
336 %************************************************************************
337 %*                                                                      *
338 \subsection{Errors and contexts}
339 %*                                                                      *
340 %************************************************************************
341
342 \begin{code}
343 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
344 showSplice what before after
345   = getSrcLocM          `thenM` \ loc ->
346     traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what, 
347                        nest 2 (sep [nest 2 (ppr before),
348                                     text "======>",
349                                     nest 2 after])])
350
351 illegalSplice level
352   = ptext SLIT("Illegal splice at level") <+> ppr level
353
354 #endif  /* GHCI */
355 \end{code}