b7b3c298b4147408cfc06afecd5f3ed9569b7ac2
[ghc-hetmet.git] / ghc / compiler / typecheck / TcSplice.lhs
1 %
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.TH.THSyntax as TH
17 -- THSyntax gives access to internal functions and data types
18
19 import HscTypes         ( HscEnv(..) )
20 import HsSyn            ( HsBracket(..), HsExpr(..) )
21 import Convert          ( convertToHsExpr, convertToHsDecls )
22 import RnExpr           ( rnExpr )
23 import RnEnv            ( lookupFixityRn )
24 import RdrHsSyn         ( RdrNameHsExpr, RdrNameHsDecl )
25 import RnHsSyn          ( RenamedHsExpr )
26 import TcExpr           ( tcCheckRho, tcMonoExpr )
27 import TcHsSyn          ( TcExpr, TypecheckedHsExpr, mkHsLet, zonkTopExpr )
28 import TcSimplify       ( tcSimplifyTop, tcSimplifyBracket )
29 import TcUnify          ( Expected, zapExpectedTo, zapExpectedType )
30 import TcType           ( TcType, openTypeKind, mkAppTy, tcSplitSigmaTy )
31 import TcEnv            ( spliceOK, tcMetaTy, bracketOK, tcLookup )
32 import TcMType          ( newTyVarTy, UserTypeCtxt(ExprSigCtxt), zonkTcType, zonkTcTyVar )
33 import TcHsType         ( tcHsSigType )
34 import TypeRep          ( Type(..), PredType(..), TyThing(..) ) -- For reification
35 import Name             ( Name, NamedThing(..), nameOccName, nameModule, isExternalName )
36 import OccName
37 import Var              ( TyVar, idType )
38 import Module           ( moduleUserString, mkModuleName )
39 import TcRnMonad
40 import IfaceEnv         ( lookupOrig )
41
42 import Class            ( Class, classBigSig )
43 import TyCon            ( TyCon, tyConTheta, tyConTyVars, getSynTyConDefn, isSynTyCon, isNewTyCon, tyConDataCons )
44 import DataCon          ( DataCon, dataConTyCon, dataConOrigArgTys, dataConStrictMarks, 
45                           dataConName, dataConFieldLabels, dataConWrapId )
46 import Id               ( idName, globalIdDetails )
47 import IdInfo           ( GlobalIdDetails(..) )
48 import TysWiredIn       ( mkListTy )
49 import DsMeta           ( expQTyConName, typeQTyConName, decTyConName, qTyConName, nameTyConName )
50 import ErrUtils         ( Message )
51 import Outputable
52 import Unique           ( Unique, Uniquable(..), getKey )
53 import IOEnv            ( IOEnv )
54 import BasicTypes       ( StrictnessMark(..), Fixity(..), FixityDirection(..) )
55 import Module           ( moduleUserString )
56 import Panic            ( showException )
57 import GHC.Base         ( unsafeCoerce#, Int(..) )      -- Should have a better home in the module hierarchy
58 import Monad            ( liftM )
59 import FastString       ( LitString )
60 import FastTypes        ( iBox )
61 \end{code}
62
63
64 %************************************************************************
65 %*                                                                      *
66 \subsection{Main interface + stubs for the non-GHCI case
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
72
73 tcSpliceExpr :: Name 
74              -> RenamedHsExpr
75              -> Expected TcType
76              -> TcM TcExpr
77
78 #ifndef GHCI
79 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
80 tcSpliceDecls e     = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
81 #else
82 \end{code}
83
84 %************************************************************************
85 %*                                                                      *
86 \subsection{Quoting an expression}
87 %*                                                                      *
88 %************************************************************************
89
90 \begin{code}
91 tcBracket :: HsBracket Name -> Expected TcType -> TcM TcExpr
92 tcBracket brack res_ty
93   = getStage                            `thenM` \ level ->
94     case bracketOK level of {
95         Nothing         -> failWithTc (illegalBracket level) ;
96         Just next_level ->
97
98         -- Typecheck expr to make sure it is valid,
99         -- but throw away the results.  We'll type check
100         -- it again when we actually use it.
101     newMutVar []                        `thenM` \ pending_splices ->
102     getLIEVar                           `thenM` \ lie_var ->
103
104     setStage (Brack next_level pending_splices lie_var) (
105         getLIE (tc_bracket brack)
106     )                                   `thenM` \ (meta_ty, lie) ->
107     tcSimplifyBracket lie               `thenM_`  
108
109         -- Make the expected type have the right shape
110     zapExpectedTo res_ty meta_ty        `thenM_`
111
112         -- Return the original expression, not the type-decorated one
113     readMutVar pending_splices          `thenM` \ pendings ->
114     returnM (HsBracketOut brack pendings)
115     }
116
117 tc_bracket :: HsBracket Name -> TcM TcType
118 tc_bracket (VarBr v) 
119   = tcMetaTy nameTyConName
120         -- Result type is Var (not Q-monadic)
121
122 tc_bracket (ExpBr expr) 
123   = newTyVarTy openTypeKind     `thenM` \ any_ty ->
124     tcCheckRho expr any_ty      `thenM_`
125     tcMetaTy expQTyConName
126         -- Result type is Expr (= Q Exp)
127
128 tc_bracket (TypBr typ) 
129   = tcHsSigType ExprSigCtxt typ         `thenM_`
130     tcMetaTy typeQTyConName
131         -- Result type is Type (= Q Typ)
132
133 tc_bracket (DecBr decls)
134   = tcTopSrcDecls decls         `thenM_`
135         -- Typecheck the declarations, dicarding the result
136         -- We'll get all that stuff later, when we splice it in
137
138     tcMetaTy decTyConName       `thenM` \ decl_ty ->
139     tcMetaTy qTyConName         `thenM` \ q_ty ->
140     returnM (mkAppTy q_ty (mkListTy decl_ty))
141         -- Result type is Q [Dec]
142 \end{code}
143
144
145 %************************************************************************
146 %*                                                                      *
147 \subsection{Splicing an expression}
148 %*                                                                      *
149 %************************************************************************
150
151 \begin{code}
152 tcSpliceExpr name expr res_ty
153   = getStage            `thenM` \ level ->
154     case spliceOK level of {
155         Nothing         -> failWithTc (illegalSplice level) ;
156         Just next_level -> 
157
158     case level of {
159         Comp                   -> tcTopSplice expr res_ty ;
160         Brack _ ps_var lie_var ->  
161
162         -- A splice inside brackets
163         -- NB: ignore res_ty, apart from zapping it to a mono-type
164         -- e.g.   [| reverse $(h 4) |]
165         -- Here (h 4) :: Q Exp
166         -- but $(h 4) :: forall a.a     i.e. anything!
167
168     zapExpectedType res_ty                      `thenM_`
169     tcMetaTy expQTyConName                      `thenM` \ meta_exp_ty ->
170     setStage (Splice next_level) (
171         setLIEVar lie_var          $
172         tcCheckRho expr meta_exp_ty
173     )                                           `thenM` \ expr' ->
174
175         -- Write the pending splice into the bucket
176     readMutVar ps_var                           `thenM` \ ps ->
177     writeMutVar ps_var ((name,expr') : ps)      `thenM_`
178
179     returnM (panic "tcSpliceExpr")      -- The returned expression is ignored
180     }} 
181
182 -- tcTopSplice used to have this:
183 -- Note that we do not decrement the level (to -1) before 
184 -- typechecking the expression.  For example:
185 --      f x = $( ...$(g 3) ... )
186 -- The recursive call to tcMonoExpr will simply expand the 
187 -- inner escape before dealing with the outer one
188
189 tcTopSplice expr res_ty
190   = tcMetaTy expQTyConName              `thenM` \ meta_exp_ty ->
191
192         -- Typecheck the expression
193     tcTopSpliceExpr expr meta_exp_ty    `thenM` \ zonked_q_expr ->
194
195         -- Run the expression
196     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
197     runMetaE zonked_q_expr              `thenM` \ simple_expr ->
198   
199     let 
200         -- simple_expr :: TH.Exp
201
202         expr2 :: RdrNameHsExpr
203         expr2 = convertToHsExpr simple_expr 
204     in
205     traceTc (text "Got result" <+> ppr expr2)   `thenM_`
206
207     showSplice "expression" 
208                zonked_q_expr (ppr expr2)        `thenM_`
209     rnExpr expr2                                `thenM` \ (exp3, fvs) ->
210
211     tcMonoExpr exp3 res_ty
212
213
214 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
215 -- Type check an expression that is the body of a top-level splice
216 --   (the caller will compile and run it)
217 tcTopSpliceExpr expr meta_ty
218   = checkNoErrs $       -- checkNoErrs: must not try to run the thing
219                         --              if the type checker fails!
220
221     setStage topSpliceStage $
222
223         -- Typecheck the expression
224     getLIE (tcCheckRho expr meta_ty)    `thenM` \ (expr', lie) ->
225
226         -- Solve the constraints
227     tcSimplifyTop lie                   `thenM` \ const_binds ->
228         
229         -- And zonk it
230     zonkTopExpr (mkHsLet const_binds expr')
231 \end{code}
232
233
234 %************************************************************************
235 %*                                                                      *
236 \subsection{Splicing an expression}
237 %*                                                                      *
238 %************************************************************************
239
240 \begin{code}
241 -- Always at top level
242 tcSpliceDecls expr
243   = tcMetaTy decTyConName               `thenM` \ meta_dec_ty ->
244     tcMetaTy qTyConName                 `thenM` \ meta_q_ty ->
245     let
246         list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
247     in
248     tcTopSpliceExpr expr list_q         `thenM` \ zonked_q_expr ->
249
250         -- Run the expression
251     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
252     runMetaD zonked_q_expr              `thenM` \ simple_expr ->
253     -- simple_expr :: [TH.Dec]
254     -- decls :: [RdrNameHsDecl]
255     handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
256     traceTc (text "Got result" <+> vcat (map ppr decls))        `thenM_`
257     showSplice "declarations"
258                zonked_q_expr (vcat (map ppr decls))             `thenM_`
259     returnM decls
260
261   where handleErrors :: [Either a Message] -> TcM [a]
262         handleErrors [] = return []
263         handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
264         handleErrors (Right m:xs) = do addErrTc m
265                                        handleErrors xs
266 \end{code}
267
268
269 %************************************************************************
270 %*                                                                      *
271 \subsection{Running an expression}
272 %*                                                                      *
273 %************************************************************************
274
275 \begin{code}
276 runMetaE :: TypecheckedHsExpr   -- Of type (Q Exp)
277          -> TcM TH.Exp  -- Of type Exp
278 runMetaE e = runMeta e
279
280 runMetaD :: TypecheckedHsExpr   -- Of type Q [Dec]
281          -> TcM [TH.Dec]        -- Of type [Dec]
282 runMetaD e = runMeta e
283
284 runMeta :: TypecheckedHsExpr    -- Of type X
285         -> TcM t                -- Of type t
286 runMeta expr
287   = do  { hsc_env <- getTopEnv
288         ; tcg_env <- getGblEnv
289         ; this_mod <- getModule
290         ; let type_env = tcg_type_env tcg_env
291               rdr_env  = tcg_rdr_env tcg_env
292         -- Wrap the compile-and-run in an exception-catcher
293         -- Compiling might fail if linking fails
294         -- Running might fail if it throws an exception
295         ; either_tval <- tryM $ do
296                 {       -- Compile it
297                   hval <- ioToTcRn (HscMain.compileExpr 
298                                       hsc_env this_mod 
299                                       rdr_env type_env expr)
300                         -- Coerce it to Q t, and run it
301                 ; TH.runQ (unsafeCoerce# hval) }
302
303         ; case either_tval of
304               Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:", 
305                                             nest 4 (vcat [text "Code:" <+> ppr expr,
306                                                       text ("Exn: " ++ Panic.showException exn)])])
307               Right v  -> returnM v }
308 \end{code}
309
310 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
311
312 \begin{code}
313 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
314   qNewName s = do  { u <- newUnique 
315                   ; let i = getKey u
316                   ; return (TH.mkNameU s i) }
317
318   qReport True msg  = addErr (text msg)
319   qReport False msg = addReport (text msg)
320
321   qCurrentModule = do { m <- getModule; return (moduleUserString m) }
322   qReify v = reify v
323   qRecover = recoverM
324
325   qRunIO io = ioToTcRn io
326 \end{code}
327
328
329 %************************************************************************
330 %*                                                                      *
331 \subsection{Errors and contexts}
332 %*                                                                      *
333 %************************************************************************
334
335 \begin{code}
336 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
337 showSplice what before after
338   = getSrcLocM          `thenM` \ loc ->
339     traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what, 
340                        nest 2 (sep [nest 2 (ppr before),
341                                     text "======>",
342                                     nest 2 after])])
343
344 illegalBracket level
345   = ptext SLIT("Illegal bracket at level") <+> ppr level
346
347 illegalSplice level
348   = ptext SLIT("Illegal splice at level") <+> ppr level
349
350 #endif  /* GHCI */
351 \end{code}
352
353
354 %************************************************************************
355 %*                                                                      *
356                         Reification
357 %*                                                                      *
358 %************************************************************************
359
360
361 \begin{code}
362 reify :: TH.Name -> TcM TH.Info
363 reify (TH.Name occ (TH.NameG th_ns mod))
364   = do  { name <- lookupOrig (mkModuleName (TH.modString mod))
365                              (OccName.mkOccName ghc_ns (TH.occString occ))
366         ; thing <- tcLookup name
367         ; reifyThing thing
368     }
369   where
370     ghc_ns = case th_ns of
371                 TH.DataName  -> dataName
372                 TH.TcClsName -> tcClsName
373                 TH.VarName   -> varName
374
375 ------------------------------
376 reifyThing :: TcTyThing -> TcM TH.Info
377 -- The only reason this is monadic is for error reporting,
378 -- which in turn is mainly for the case when TH can't express
379 -- some random GHC extension
380
381 reifyThing (AGlobal (AnId id))
382   = do  { ty <- reifyType (idType id)
383         ; fix <- reifyFixity (idName id)
384         ; let v = reifyName id
385         ; case globalIdDetails id of
386             ClassOpId cls    -> return (TH.ClassOpI v ty (reifyName cls) fix)
387             other            -> return (TH.VarI     v ty Nothing fix)
388     }
389
390 reifyThing (AGlobal (ATyCon tc))   = do { dec <- reifyTyCon tc;  return (TH.TyConI dec) }
391 reifyThing (AGlobal (AClass cls))  = do { dec <- reifyClass cls; return (TH.ClassI dec) }
392 reifyThing (AGlobal (ADataCon dc))
393   = do  { let name = dataConName dc
394         ; ty <- reifyType (idType (dataConWrapId dc))
395         ; fix <- reifyFixity name
396         ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
397
398 reifyThing (ATcId id _ _) 
399   = do  { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
400                                         -- though it may be incomplete
401         ; ty2 <- reifyType ty1
402         ; fix <- reifyFixity (idName id)
403         ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
404
405 reifyThing (ATyVar tv) 
406   = do  { ty1 <- zonkTcTyVar tv
407         ; ty2 <- reifyType ty1
408         ; return (TH.TyVarI (reifyName tv) ty2) }
409
410 ------------------------------
411 reifyTyCon :: TyCon -> TcM TH.Dec
412 reifyTyCon tc
413   | isSynTyCon tc
414   = do  { let (tvs, rhs) = getSynTyConDefn tc
415         ; rhs' <- reifyType rhs
416         ; return (TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
417
418   | isNewTyCon tc
419   = do  { cxt <- reifyCxt (tyConTheta tc)
420         ; con <- reifyDataCon (head (tyConDataCons tc))
421         ; return (TH.NewtypeD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
422                               con [{- Don't know about deriving -}]) }
423
424   | otherwise   -- Algebraic
425   = do  { cxt <- reifyCxt (tyConTheta tc)
426         ; cons <- mapM reifyDataCon (tyConDataCons tc)
427         ; return (TH.DataD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
428                               cons [{- Don't know about deriving -}]) }
429
430 reifyDataCon :: DataCon -> TcM TH.Con
431 reifyDataCon dc
432   = do  { arg_tys <- reifyTypes (dataConOrigArgTys dc)
433         ; let stricts = map reifyStrict (dataConStrictMarks dc)
434               fields  = dataConFieldLabels dc
435         ; if null fields then
436              return (TH.NormalC (reifyName dc) (stricts `zip` arg_tys))
437           else
438              return (TH.RecC (reifyName dc) (zip3 (map reifyName fields) stricts arg_tys)) }
439         -- NB: we don't remember whether the constructor was declared in an infix way
440
441 ------------------------------
442 reifyClass :: Class -> TcM TH.Dec
443 reifyClass cls 
444   = do  { cxt <- reifyCxt theta
445         ; ops <- mapM reify_op op_stuff
446         ; return (TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) ops) }
447   where
448     (tvs, theta, _, op_stuff) = classBigSig cls
449     reify_op (op, _) = do { ty <- reifyType (idType op)
450                           ; return (TH.SigD (reifyName op) ty) }
451
452 ------------------------------
453 reifyType :: TypeRep.Type -> TcM TH.Type
454 reifyType (TyVarTy tv)      = return (TH.VarT (reifyName tv))
455 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
456 reifyType (NewTcApp tc tys) = reify_tc_app (reifyName tc) tys
457 reifyType (NoteTy _ ty)     = reifyType ty
458 reifyType (AppTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
459 reifyType (FunTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
460 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt; 
461                                  ; tau' <- reifyType tau 
462                                  ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
463                             where
464                                 (tvs, cxt, tau) = tcSplitSigmaTy ty
465 reifyTypes = mapM reifyType
466 reifyCxt   = mapM reifyPred
467
468 reifyTyVars :: [TyVar] -> [TH.Name]
469 reifyTyVars = map reifyName
470
471 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
472 reify_tc_app tc tys = do { tys' <- reifyTypes tys 
473                          ; return (foldl TH.AppT (TH.ConT tc) tys') }
474
475 reifyPred :: TypeRep.PredType -> TcM TH.Type
476 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
477 reifyPred p@(IParam _ _)   = noTH SLIT("implicit parameters") (ppr p)
478
479
480 ------------------------------
481 reifyName :: NamedThing n => n -> TH.Name
482 reifyName thing
483   | isExternalName name = mk_varg mod occ_str
484   | otherwise           = TH.mkNameU occ_str (getKey (getUnique name))
485   where
486     name    = getName thing
487     mod     = moduleUserString (nameModule name)
488     occ_str = occNameUserString occ
489     occ     = nameOccName name
490     mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
491             | OccName.isVarOcc  occ = TH.mkNameG_v
492             | OccName.isTcOcc   occ = TH.mkNameG_tc
493             | otherwise             = pprPanic "reifyName" (ppr name)
494
495 ------------------------------
496 reifyFixity :: Name -> TcM TH.Fixity
497 reifyFixity name
498   = do  { fix <- lookupFixityRn name
499         ; return (conv_fix fix) }
500     where
501       conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
502       conv_dir BasicTypes.InfixR = TH.InfixR
503       conv_dir BasicTypes.InfixL = TH.InfixL
504       conv_dir BasicTypes.InfixN = TH.InfixN
505
506 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
507 reifyStrict MarkedStrict    = TH.IsStrict
508 reifyStrict MarkedUnboxed   = TH.IsStrict
509 reifyStrict NotMarkedStrict = TH.NotStrict
510
511 ------------------------------
512 noTH :: LitString -> SDoc -> TcM a
513 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+> 
514                                 ptext SLIT("in Template Haskell:"),
515                              nest 2 d])
516 \end{code}