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