[project @ 2003-11-13 15:02:53 by simonpj]
[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
210         -- Rename it, but bale out if there are errors
211         -- otherwise the type checker just gives more spurious errors
212     checkNoErrs (rnExpr expr2)                  `thenM` \ (exp3, fvs) ->
213
214     tcMonoExpr exp3 res_ty
215
216
217 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
218 -- Type check an expression that is the body of a top-level splice
219 --   (the caller will compile and run it)
220 tcTopSpliceExpr expr meta_ty
221   = checkNoErrs $       -- checkNoErrs: must not try to run the thing
222                         --              if the type checker fails!
223
224     setStage topSpliceStage $
225
226         -- Typecheck the expression
227     getLIE (tcCheckRho expr meta_ty)    `thenM` \ (expr', lie) ->
228
229         -- Solve the constraints
230     tcSimplifyTop lie                   `thenM` \ const_binds ->
231         
232         -- And zonk it
233     zonkTopExpr (mkHsLet const_binds expr')
234 \end{code}
235
236
237 %************************************************************************
238 %*                                                                      *
239 \subsection{Splicing an expression}
240 %*                                                                      *
241 %************************************************************************
242
243 \begin{code}
244 -- Always at top level
245 tcSpliceDecls expr
246   = tcMetaTy decTyConName               `thenM` \ meta_dec_ty ->
247     tcMetaTy qTyConName                 `thenM` \ meta_q_ty ->
248     let
249         list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
250     in
251     tcTopSpliceExpr expr list_q         `thenM` \ zonked_q_expr ->
252
253         -- Run the expression
254     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
255     runMetaD zonked_q_expr              `thenM` \ simple_expr ->
256     -- simple_expr :: [TH.Dec]
257     -- decls :: [RdrNameHsDecl]
258     handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
259     traceTc (text "Got result" <+> vcat (map ppr decls))        `thenM_`
260     showSplice "declarations"
261                zonked_q_expr (vcat (map ppr decls))             `thenM_`
262     returnM decls
263
264   where handleErrors :: [Either a Message] -> TcM [a]
265         handleErrors [] = return []
266         handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
267         handleErrors (Right m:xs) = do addErrTc m
268                                        handleErrors xs
269 \end{code}
270
271
272 %************************************************************************
273 %*                                                                      *
274 \subsection{Running an expression}
275 %*                                                                      *
276 %************************************************************************
277
278 \begin{code}
279 runMetaE :: TypecheckedHsExpr   -- Of type (Q Exp)
280          -> TcM TH.Exp  -- Of type Exp
281 runMetaE e = runMeta e
282
283 runMetaD :: TypecheckedHsExpr   -- Of type Q [Dec]
284          -> TcM [TH.Dec]        -- Of type [Dec]
285 runMetaD e = runMeta e
286
287 runMeta :: TypecheckedHsExpr    -- Of type X
288         -> TcM t                -- Of type t
289 runMeta expr
290   = do  { hsc_env <- getTopEnv
291         ; tcg_env <- getGblEnv
292         ; this_mod <- getModule
293         ; let type_env = tcg_type_env tcg_env
294               rdr_env  = tcg_rdr_env tcg_env
295         -- Wrap the compile-and-run in an exception-catcher
296         -- Compiling might fail if linking fails
297         -- Running might fail if it throws an exception
298         ; either_tval <- tryM $ do
299                 {       -- Compile it
300                   hval <- ioToTcRn (HscMain.compileExpr 
301                                       hsc_env this_mod 
302                                       rdr_env type_env expr)
303                         -- Coerce it to Q t, and run it
304                 ; TH.runQ (unsafeCoerce# hval) }
305
306         ; case either_tval of
307               Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:", 
308                                             nest 4 (vcat [text "Code:" <+> ppr expr,
309                                                       text ("Exn: " ++ Panic.showException exn)])])
310               Right v  -> returnM v }
311 \end{code}
312
313 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
314
315 \begin{code}
316 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
317   qNewName s = do  { u <- newUnique 
318                   ; let i = getKey u
319                   ; return (TH.mkNameU s i) }
320
321   qReport True msg  = addErr (text msg)
322   qReport False msg = addReport (text msg)
323
324   qCurrentModule = do { m <- getModule; return (moduleUserString m) }
325   qReify v = reify v
326   qRecover = recoverM
327
328   qRunIO io = ioToTcRn io
329 \end{code}
330
331
332 %************************************************************************
333 %*                                                                      *
334 \subsection{Errors and contexts}
335 %*                                                                      *
336 %************************************************************************
337
338 \begin{code}
339 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
340 showSplice what before after
341   = getSrcLocM          `thenM` \ loc ->
342     traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what, 
343                        nest 2 (sep [nest 2 (ppr before),
344                                     text "======>",
345                                     nest 2 after])])
346
347 illegalBracket level
348   = ptext SLIT("Illegal bracket at level") <+> ppr level
349
350 illegalSplice level
351   = ptext SLIT("Illegal splice at level") <+> ppr level
352
353 #endif  /* GHCI */
354 \end{code}
355
356
357 %************************************************************************
358 %*                                                                      *
359                         Reification
360 %*                                                                      *
361 %************************************************************************
362
363
364 \begin{code}
365 reify :: TH.Name -> TcM TH.Info
366 reify (TH.Name occ (TH.NameG th_ns mod))
367   = do  { name <- lookupOrig (mkModuleName (TH.modString mod))
368                              (OccName.mkOccName ghc_ns (TH.occString occ))
369         ; thing <- tcLookup name
370         ; reifyThing thing
371     }
372   where
373     ghc_ns = case th_ns of
374                 TH.DataName  -> dataName
375                 TH.TcClsName -> tcClsName
376                 TH.VarName   -> varName
377
378 ------------------------------
379 reifyThing :: TcTyThing -> TcM TH.Info
380 -- The only reason this is monadic is for error reporting,
381 -- which in turn is mainly for the case when TH can't express
382 -- some random GHC extension
383
384 reifyThing (AGlobal (AnId id))
385   = do  { ty <- reifyType (idType id)
386         ; fix <- reifyFixity (idName id)
387         ; let v = reifyName id
388         ; case globalIdDetails id of
389             ClassOpId cls    -> return (TH.ClassOpI v ty (reifyName cls) fix)
390             other            -> return (TH.VarI     v ty Nothing fix)
391     }
392
393 reifyThing (AGlobal (ATyCon tc))   = do { dec <- reifyTyCon tc;  return (TH.TyConI dec) }
394 reifyThing (AGlobal (AClass cls))  = do { dec <- reifyClass cls; return (TH.ClassI dec) }
395 reifyThing (AGlobal (ADataCon dc))
396   = do  { let name = dataConName dc
397         ; ty <- reifyType (idType (dataConWrapId dc))
398         ; fix <- reifyFixity name
399         ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
400
401 reifyThing (ATcId id _ _) 
402   = do  { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
403                                         -- though it may be incomplete
404         ; ty2 <- reifyType ty1
405         ; fix <- reifyFixity (idName id)
406         ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
407
408 reifyThing (ATyVar tv) 
409   = do  { ty1 <- zonkTcTyVar tv
410         ; ty2 <- reifyType ty1
411         ; return (TH.TyVarI (reifyName tv) ty2) }
412
413 ------------------------------
414 reifyTyCon :: TyCon -> TcM TH.Dec
415 reifyTyCon tc
416   | isSynTyCon tc
417   = do  { let (tvs, rhs) = getSynTyConDefn tc
418         ; rhs' <- reifyType rhs
419         ; return (TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
420
421   | isNewTyCon tc
422   = do  { cxt <- reifyCxt (tyConTheta tc)
423         ; con <- reifyDataCon (head (tyConDataCons tc))
424         ; return (TH.NewtypeD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
425                               con [{- Don't know about deriving -}]) }
426
427   | otherwise   -- Algebraic
428   = do  { cxt <- reifyCxt (tyConTheta tc)
429         ; cons <- mapM reifyDataCon (tyConDataCons tc)
430         ; return (TH.DataD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
431                               cons [{- Don't know about deriving -}]) }
432
433 reifyDataCon :: DataCon -> TcM TH.Con
434 reifyDataCon dc
435   = do  { arg_tys <- reifyTypes (dataConOrigArgTys dc)
436         ; let stricts = map reifyStrict (dataConStrictMarks dc)
437               fields  = dataConFieldLabels dc
438         ; if null fields then
439              return (TH.NormalC (reifyName dc) (stricts `zip` arg_tys))
440           else
441              return (TH.RecC (reifyName dc) (zip3 (map reifyName fields) stricts arg_tys)) }
442         -- NB: we don't remember whether the constructor was declared in an infix way
443
444 ------------------------------
445 reifyClass :: Class -> TcM TH.Dec
446 reifyClass cls 
447   = do  { cxt <- reifyCxt theta
448         ; ops <- mapM reify_op op_stuff
449         ; return (TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) ops) }
450   where
451     (tvs, theta, _, op_stuff) = classBigSig cls
452     reify_op (op, _) = do { ty <- reifyType (idType op)
453                           ; return (TH.SigD (reifyName op) ty) }
454
455 ------------------------------
456 reifyType :: TypeRep.Type -> TcM TH.Type
457 reifyType (TyVarTy tv)      = return (TH.VarT (reifyName tv))
458 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
459 reifyType (NewTcApp tc tys) = reify_tc_app (reifyName tc) tys
460 reifyType (NoteTy _ ty)     = reifyType ty
461 reifyType (AppTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
462 reifyType (FunTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
463 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt; 
464                                  ; tau' <- reifyType tau 
465                                  ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
466                             where
467                                 (tvs, cxt, tau) = tcSplitSigmaTy ty
468 reifyTypes = mapM reifyType
469 reifyCxt   = mapM reifyPred
470
471 reifyTyVars :: [TyVar] -> [TH.Name]
472 reifyTyVars = map reifyName
473
474 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
475 reify_tc_app tc tys = do { tys' <- reifyTypes tys 
476                          ; return (foldl TH.AppT (TH.ConT tc) tys') }
477
478 reifyPred :: TypeRep.PredType -> TcM TH.Type
479 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
480 reifyPred p@(IParam _ _)   = noTH SLIT("implicit parameters") (ppr p)
481
482
483 ------------------------------
484 reifyName :: NamedThing n => n -> TH.Name
485 reifyName thing
486   | isExternalName name = mk_varg mod occ_str
487   | otherwise           = TH.mkNameU occ_str (getKey (getUnique name))
488   where
489     name    = getName thing
490     mod     = moduleUserString (nameModule name)
491     occ_str = occNameUserString occ
492     occ     = nameOccName name
493     mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
494             | OccName.isVarOcc  occ = TH.mkNameG_v
495             | OccName.isTcOcc   occ = TH.mkNameG_tc
496             | otherwise             = pprPanic "reifyName" (ppr name)
497
498 ------------------------------
499 reifyFixity :: Name -> TcM TH.Fixity
500 reifyFixity name
501   = do  { fix <- lookupFixityRn name
502         ; return (conv_fix fix) }
503     where
504       conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
505       conv_dir BasicTypes.InfixR = TH.InfixR
506       conv_dir BasicTypes.InfixL = TH.InfixL
507       conv_dir BasicTypes.InfixN = TH.InfixN
508
509 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
510 reifyStrict MarkedStrict    = TH.IsStrict
511 reifyStrict MarkedUnboxed   = TH.IsStrict
512 reifyStrict NotMarkedStrict = TH.NotStrict
513
514 ------------------------------
515 noTH :: LitString -> SDoc -> TcM a
516 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+> 
517                                 ptext SLIT("in Template Haskell:"),
518                              nest 2 d])
519 \end{code}