1fa44ca308ec26c2aa184d8bebdad2486c5b3a3c
[ghc-hetmet.git] / compiler / typecheck / TcRnMonad.lhs
1 \begin{code}
2 module TcRnMonad(
3         module TcRnMonad,
4         module TcRnTypes,
5         module IOEnv
6   ) where
7
8 #include "HsVersions.h"
9
10 import TcRnTypes        -- Re-export all
11 import IOEnv            -- Re-export all
12
13 #if defined(GHCI) && defined(BREAKPOINT)
14 import TypeRep          ( Type(..), liftedTypeKind )
15 import Var              ( mkTyVar, mkGlobalId )
16 import IdInfo           ( GlobalIdDetails(..), vanillaIdInfo )
17 import OccName          ( mkOccName, tvName )
18 import SrcLoc           ( noSrcLoc  )
19 import TysWiredIn       ( intTy, stringTy, mkListTy, unitTy, boolTy )
20 import PrelNames        ( breakpointJumpName, breakpointCondJumpName )
21 import NameEnv          ( mkNameEnv )
22 #endif
23
24 import HsSyn            ( emptyLHsBinds )
25 import HscTypes         ( HscEnv(..), ModGuts(..), ModIface(..),
26                           TypeEnv, emptyTypeEnv, HscSource(..), isHsBoot,
27                           ExternalPackageState(..), HomePackageTable,
28                           Deprecs(..), FixityEnv, FixItem, 
29                           mkPrintUnqualified )
30 import Module           ( Module, moduleName )
31 import RdrName          ( GlobalRdrEnv, LocalRdrEnv, emptyLocalRdrEnv )
32 import Name             ( Name, mkInternalName, tidyNameOcc, nameOccName, getSrcLoc )
33 import Type             ( Type )
34 import TcType           ( tcIsTyVarTy, tcGetTyVar )
35 import NameEnv          ( extendNameEnvList, nameEnvElts )
36 import InstEnv          ( emptyInstEnv )
37
38 import Var              ( setTyVarName )
39 import VarSet           ( emptyVarSet )
40 import VarEnv           ( TidyEnv, emptyTidyEnv, extendVarEnv )
41 import ErrUtils         ( Message, Messages, emptyMessages, errorsFound, 
42                           mkWarnMsg, printErrorsAndWarnings,
43                           mkLocMessage, mkLongErrMsg )
44 import SrcLoc           ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
45 import NameEnv          ( emptyNameEnv )
46 import NameSet          ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
47 import OccName          ( emptyOccEnv, tidyOccName )
48 import Bag              ( emptyBag )
49 import Outputable
50 import UniqSupply       ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
51 import UniqFM           ( unitUFM )
52 import Unique           ( Unique )
53 import DynFlags         ( DynFlags(..), DynFlag(..), dopt, dopt_set, GhcMode )
54 import StaticFlags      ( opt_PprStyle_Debug )
55 import Bag              ( snocBag, unionBags )
56 import Panic            ( showException )
57  
58 import IO               ( stderr )
59 import DATA_IOREF       ( newIORef, readIORef )
60 import EXCEPTION        ( Exception )
61 \end{code}
62
63
64
65 %************************************************************************
66 %*                                                                      *
67                         initTc
68 %*                                                                      *
69 %************************************************************************
70
71 \begin{code}
72 ioToTcRn :: IO r -> TcRn r
73 ioToTcRn = ioToIOEnv
74 \end{code}
75
76 \begin{code}
77 initTc :: HscEnv
78        -> HscSource
79        -> Module 
80        -> TcM r
81        -> IO (Messages, Maybe r)
82                 -- Nothing => error thrown by the thing inside
83                 -- (error messages should have been printed already)
84
85 initTc hsc_env hsc_src mod do_this
86  = do { errs_var     <- newIORef (emptyBag, emptyBag) ;
87         tvs_var      <- newIORef emptyVarSet ;
88         type_env_var <- newIORef emptyNameEnv ;
89         dfuns_var    <- newIORef emptyNameSet ;
90         keep_var     <- newIORef emptyNameSet ;
91         th_var       <- newIORef False ;
92         dfun_n_var   <- newIORef 1 ;
93         let {
94              gbl_env = TcGblEnv {
95                 tcg_mod      = mod,
96                 tcg_src      = hsc_src,
97                 tcg_rdr_env  = hsc_global_rdr_env hsc_env,
98                 tcg_fix_env  = emptyNameEnv,
99                 tcg_default  = Nothing,
100                 tcg_type_env = hsc_global_type_env hsc_env,
101                 tcg_type_env_var = type_env_var,
102                 tcg_inst_env  = emptyInstEnv,
103                 tcg_inst_uses = dfuns_var,
104                 tcg_th_used   = th_var,
105                 tcg_exports  = emptyNameSet,
106                 tcg_imports  = init_imports,
107                 tcg_dus      = emptyDUs,
108                 tcg_rn_imports = Nothing,
109                 tcg_rn_exports = Nothing,
110                 tcg_rn_decls = Nothing,
111                 tcg_binds    = emptyLHsBinds,
112                 tcg_deprecs  = NoDeprecs,
113                 tcg_insts    = [],
114                 tcg_rules    = [],
115                 tcg_fords    = [],
116                 tcg_dfun_n   = dfun_n_var,
117                 tcg_keep     = keep_var
118              } ;
119              lcl_env = TcLclEnv {
120                 tcl_errs       = errs_var,
121                 tcl_loc        = mkGeneralSrcSpan FSLIT("Top level"),
122                 tcl_ctxt       = [],
123                 tcl_rdr        = emptyLocalRdrEnv,
124                 tcl_th_ctxt    = topStage,
125                 tcl_arrow_ctxt = NoArrowCtxt,
126                 tcl_env        = emptyNameEnv,
127                 tcl_tyvars     = tvs_var,
128                 tcl_lie        = panic "initTc:LIE"     -- LIE only valid inside a getLIE
129              } ;
130         } ;
131    
132         -- OK, here's the business end!
133         maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
134                      do {
135 #if defined(GHCI) && defined(BREAKPOINT)
136                           unique <- newUnique ;
137                           let { var = mkInternalName unique (mkOccName tvName "a") noSrcLoc;
138                                 tyvar = mkTyVar var liftedTypeKind;
139                                 basicType extra = (FunTy intTy
140                                                    (FunTy (mkListTy unitTy)
141                                                     (FunTy stringTy
142                                                      (ForAllTy tyvar
143                                                       (extra
144                                                        (FunTy (TyVarTy tyvar)
145                                                         (TyVarTy tyvar)))))));
146                                 breakpointJumpType
147                                     = mkGlobalId VanillaGlobal breakpointJumpName
148                                                  (basicType id) vanillaIdInfo;
149                                 breakpointCondJumpType
150                                     = mkGlobalId VanillaGlobal breakpointCondJumpName
151                                                  (basicType (FunTy boolTy)) vanillaIdInfo;
152                                 new_env = mkNameEnv [(breakpointJumpName
153                                                      , ATcId breakpointJumpType topLevel False)
154                                                      ,(breakpointCondJumpName
155                                                      , ATcId breakpointCondJumpType topLevel False)];
156                               };
157                           r <- tryM (updLclEnv (\gbl -> gbl{tcl_env=new_env}) do_this)
158 #else
159                           r <- tryM do_this
160 #endif
161                         ; case r of
162                           Right res -> return (Just res)
163                           Left _    -> return Nothing } ;
164
165         -- Collect any error messages
166         msgs <- readIORef errs_var ;
167
168         let { dflags = hsc_dflags hsc_env
169             ; final_res | errorsFound dflags msgs = Nothing
170                         | otherwise               = maybe_res } ;
171
172         return (msgs, final_res)
173     }
174   where
175     init_imports = emptyImportAvails {imp_env = 
176                                         unitUFM (moduleName mod) emptyNameSet}
177         -- Initialise tcg_imports with an empty set of bindings for
178         -- this module, so that if we see 'module M' in the export
179         -- list, and there are no bindings in M, we don't bleat 
180         -- "unknown module M".
181
182 initTcPrintErrors       -- Used from the interactive loop only
183        :: HscEnv
184        -> Module 
185        -> TcM r
186        -> IO (Maybe r)
187 initTcPrintErrors env mod todo = do
188   (msgs, res) <- initTc env HsSrcFile mod todo
189   printErrorsAndWarnings (hsc_dflags env) msgs
190   return res
191 \end{code}
192
193
194 %************************************************************************
195 %*                                                                      *
196                 Initialisation
197 %*                                                                      *
198 %************************************************************************
199
200
201 \begin{code}
202 initTcRnIf :: Char              -- Tag for unique supply
203            -> HscEnv
204            -> gbl -> lcl 
205            -> TcRnIf gbl lcl a 
206            -> IO a
207 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
208    = do { us     <- mkSplitUniqSupply uniq_tag ;
209         ; us_var <- newIORef us ;
210
211         ; let { env = Env { env_top = hsc_env,
212                             env_us  = us_var,
213                             env_gbl = gbl_env,
214                             env_lcl = lcl_env } }
215
216         ; runIOEnv env thing_inside
217         }
218 \end{code}
219
220 %************************************************************************
221 %*                                                                      *
222                 Simple accessors
223 %*                                                                      *
224 %************************************************************************
225
226 \begin{code}
227 getTopEnv :: TcRnIf gbl lcl HscEnv
228 getTopEnv = do { env <- getEnv; return (env_top env) }
229
230 getGblEnv :: TcRnIf gbl lcl gbl
231 getGblEnv = do { env <- getEnv; return (env_gbl env) }
232
233 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
234 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) -> 
235                           env { env_gbl = upd gbl })
236
237 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
238 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
239
240 getLclEnv :: TcRnIf gbl lcl lcl
241 getLclEnv = do { env <- getEnv; return (env_lcl env) }
242
243 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
244 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) -> 
245                           env { env_lcl = upd lcl })
246
247 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
248 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
249
250 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
251 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
252
253 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
254 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
255 \end{code}
256
257
258 Command-line flags
259
260 \begin{code}
261 getDOpts :: TcRnIf gbl lcl DynFlags
262 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
263
264 doptM :: DynFlag -> TcRnIf gbl lcl Bool
265 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
266
267 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
268 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
269                          env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
270
271 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()     -- Do it flag is true
272 ifOptM flag thing_inside = do { b <- doptM flag; 
273                                 if b then thing_inside else return () }
274
275 getGhcMode :: TcRnIf gbl lcl GhcMode
276 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
277 \end{code}
278
279 \begin{code}
280 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
281 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
282
283 getEps :: TcRnIf gbl lcl ExternalPackageState
284 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
285
286 -- Updating the EPS.  This should be an atomic operation.
287 -- Note the delicate 'seq' which forces the EPS before putting it in the
288 -- variable.  Otherwise what happens is that we get
289 --      write eps_var (....(unsafeRead eps_var)....)
290 -- and if the .... is strict, that's obviously bottom.  By forcing it beforehand
291 -- we make the unsafeRead happen before we update the variable.
292
293 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
294           -> TcRnIf gbl lcl a
295 updateEps upd_fn = do   { traceIf (text "updating EPS")
296                         ; eps_var <- getEpsVar
297                         ; eps <- readMutVar eps_var
298                         ; let { (eps', val) = upd_fn eps }
299                         ; seq eps' (writeMutVar eps_var eps')
300                         ; return val }
301
302 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
303            -> TcRnIf gbl lcl ()
304 updateEps_ upd_fn = do  { traceIf (text "updating EPS_")
305                         ; eps_var <- getEpsVar
306                         ; eps <- readMutVar eps_var
307                         ; let { eps' = upd_fn eps }
308                         ; seq eps' (writeMutVar eps_var eps') }
309
310 getHpt :: TcRnIf gbl lcl HomePackageTable
311 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
312
313 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
314 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
315                   ; return (eps, hsc_HPT env) }
316 \end{code}
317
318 %************************************************************************
319 %*                                                                      *
320                 Unique supply
321 %*                                                                      *
322 %************************************************************************
323
324 \begin{code}
325 newUnique :: TcRnIf gbl lcl Unique
326 newUnique
327  = do { env <- getEnv ;
328         let { u_var = env_us env } ;
329         us <- readMutVar u_var ;
330         case splitUniqSupply us of { (us1,_) -> do {
331         writeMutVar u_var us1 ;
332         return $! uniqFromSupply us }}}
333    -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
334    -- a chain of unevaluated supplies behind.
335    -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
336    -- throw away one half of the new split supply.  This is safe because this
337    -- is the only place we use that unique.  Using the other half of the split
338    -- supply is safer, but slower.
339
340 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
341 newUniqueSupply
342  = do { env <- getEnv ;
343         let { u_var = env_us env } ;
344         us <- readMutVar u_var ;
345         case splitUniqSupply us of { (us1,us2) -> do {
346         writeMutVar u_var us1 ;
347         return us2 }}}
348
349 newLocalName :: Name -> TcRnIf gbl lcl Name
350 newLocalName name       -- Make a clone
351   = newUnique           `thenM` \ uniq ->
352     returnM (mkInternalName uniq (nameOccName name) (getSrcLoc name))
353 \end{code}
354
355
356 %************************************************************************
357 %*                                                                      *
358                 Debugging
359 %*                                                                      *
360 %************************************************************************
361
362 \begin{code}
363 traceTc, traceRn :: SDoc -> TcRn ()
364 traceRn      = traceOptTcRn Opt_D_dump_rn_trace
365 traceTc      = traceOptTcRn Opt_D_dump_tc_trace
366 traceSplice  = traceOptTcRn Opt_D_dump_splices
367
368
369 traceIf :: SDoc -> TcRnIf m n ()        
370 traceIf      = traceOptIf Opt_D_dump_if_trace
371 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
372
373
374 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n ()  -- No RdrEnv available, so qualify everything
375 traceOptIf flag doc = ifOptM flag $
376                      ioToIOEnv (printForUser stderr alwaysQualify doc)
377
378 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
379 traceOptTcRn flag doc = ifOptM flag $ do
380                         { ctxt <- getErrCtxt
381                         ; loc  <- getSrcSpanM
382                         ; env0 <- tcInitTidyEnv
383                         ; ctxt_msgs <- do_ctxt env0 ctxt 
384                         ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
385                         ; dumpTcRn real_doc }
386
387 dumpTcRn :: SDoc -> TcRn ()
388 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
389                     ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
390
391 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
392 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
393 \end{code}
394
395
396 %************************************************************************
397 %*                                                                      *
398                 Typechecker global environment
399 %*                                                                      *
400 %************************************************************************
401
402 \begin{code}
403 getModule :: TcRn Module
404 getModule = do { env <- getGblEnv; return (tcg_mod env) }
405
406 setModule :: Module -> TcRn a -> TcRn a
407 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
408
409 tcIsHsBoot :: TcRn Bool
410 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
411
412 getGlobalRdrEnv :: TcRn GlobalRdrEnv
413 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
414
415 getImports :: TcRn ImportAvails
416 getImports = do { env <- getGblEnv; return (tcg_imports env) }
417
418 getFixityEnv :: TcRn FixityEnv
419 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
420
421 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
422 extendFixityEnv new_bit
423   = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) -> 
424                 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})           
425
426 getDefaultTys :: TcRn (Maybe [Type])
427 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
428 \end{code}
429
430 %************************************************************************
431 %*                                                                      *
432                 Error management
433 %*                                                                      *
434 %************************************************************************
435
436 \begin{code}
437 getSrcSpanM :: TcRn SrcSpan
438         -- Avoid clash with Name.getSrcLoc
439 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
440
441 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
442 setSrcSpan loc thing_inside
443   | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
444   | otherwise         = thing_inside    -- Don't overwrite useful info with useless
445
446 addLocM :: (a -> TcM b) -> Located a -> TcM b
447 addLocM fn (L loc a) = setSrcSpan loc $ fn a
448
449 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
450 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
451
452 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
453 wrapLocFstM fn (L loc a) =
454   setSrcSpan loc $ do
455     (b,c) <- fn a
456     return (L loc b, c)
457
458 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
459 wrapLocSndM fn (L loc a) =
460   setSrcSpan loc $ do
461     (b,c) <- fn a
462     return (b, L loc c)
463 \end{code}
464
465
466 \begin{code}
467 getErrsVar :: TcRn (TcRef Messages)
468 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
469
470 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
471 setErrsVar v = updLclEnv (\ env -> env { tcl_errs =  v })
472
473 addErr :: Message -> TcRn ()
474 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
475
476 addLocErr :: Located e -> (e -> Message) -> TcRn ()
477 addLocErr (L loc e) fn = addErrAt loc (fn e)
478
479 addErrAt :: SrcSpan -> Message -> TcRn ()
480 addErrAt loc msg = addLongErrAt loc msg empty
481
482 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
483 addLongErrAt loc msg extra
484   = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;  
485          errs_var <- getErrsVar ;
486          rdr_env <- getGlobalRdrEnv ;
487          let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
488          (warns, errs) <- readMutVar errs_var ;
489          writeMutVar errs_var (warns, errs `snocBag` err) }
490
491 addErrs :: [(SrcSpan,Message)] -> TcRn ()
492 addErrs msgs = mappM_ add msgs
493              where
494                add (loc,msg) = addErrAt loc msg
495
496 addReport :: Message -> TcRn ()
497 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
498
499 addReportAt :: SrcSpan -> Message -> TcRn ()
500 addReportAt loc msg
501   = do { errs_var <- getErrsVar ;
502          rdr_env <- getGlobalRdrEnv ;
503          let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
504          (warns, errs) <- readMutVar errs_var ;
505          writeMutVar errs_var (warns `snocBag` warn, errs) }
506
507 addWarn :: Message -> TcRn ()
508 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
509
510 addWarnAt :: SrcSpan -> Message -> TcRn ()
511 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
512
513 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
514 addLocWarn (L loc e) fn = addReportAt loc (fn e)
515
516 checkErr :: Bool -> Message -> TcRn ()
517 -- Add the error if the bool is False
518 checkErr ok msg = checkM ok (addErr msg)
519
520 warnIf :: Bool -> Message -> TcRn ()
521 warnIf True  msg = addWarn msg
522 warnIf False msg = return ()
523
524 addMessages :: Messages -> TcRn ()
525 addMessages (m_warns, m_errs)
526   = do { errs_var <- getErrsVar ;
527          (warns, errs) <- readMutVar errs_var ;
528          writeMutVar errs_var (warns `unionBags` m_warns,
529                                errs  `unionBags` m_errs) }
530
531 discardWarnings :: TcRn a -> TcRn a
532 -- Ignore warnings inside the thing inside;
533 -- used to ignore-unused-variable warnings inside derived code
534 -- With -dppr-debug, the effects is switched off, so you can still see
535 -- what warnings derived code would give
536 discardWarnings thing_inside
537   | opt_PprStyle_Debug = thing_inside
538   | otherwise
539   = do  { errs_var <- newMutVar emptyMessages
540         ; result <- setErrsVar errs_var thing_inside
541         ; (_warns, errs) <- readMutVar errs_var
542         ; addMessages (emptyBag, errs)
543         ; return result }
544 \end{code}
545
546
547 \begin{code}
548 try_m :: TcRn r -> TcRn (Either Exception r)
549 -- Does try_m, with a debug-trace on failure
550 try_m thing 
551   = do { mb_r <- tryM thing ;
552          case mb_r of 
553              Left exn -> do { traceTc (exn_msg exn); return mb_r }
554              Right r  -> return mb_r }
555   where
556     exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
557
558 -----------------------
559 recoverM :: TcRn r      -- Recovery action; do this if the main one fails
560          -> TcRn r      -- Main action: do this first
561          -> TcRn r
562 -- Errors in 'thing' are retained
563 recoverM recover thing 
564   = do { mb_res <- try_m thing ;
565          case mb_res of
566            Left exn  -> recover
567            Right res -> returnM res }
568
569 -----------------------
570 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
571 -- (tryTc m) executes m, and returns
572 --      Just r,  if m succeeds (returning r)
573 --      Nothing, if m fails
574 -- It also returns all the errors and warnings accumulated by m
575 -- It always succeeds (never raises an exception)
576 tryTc m 
577  = do { errs_var <- newMutVar emptyMessages ;
578         res  <- try_m (setErrsVar errs_var m) ; 
579         msgs <- readMutVar errs_var ;
580         return (msgs, case res of
581                             Left exn  -> Nothing
582                             Right val -> Just val)
583         -- The exception is always the IOEnv built-in
584         -- in exception; see IOEnv.failM
585    }
586
587 -----------------------
588 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
589 -- Run the thing, returning 
590 --      Just r,  if m succceeds with no error messages
591 --      Nothing, if m fails, or if it succeeds but has error messages
592 -- Either way, the messages are returned; even in the Just case
593 -- there might be warnings
594 tryTcErrs thing 
595   = do  { (msgs, res) <- tryTc thing
596         ; dflags <- getDOpts
597         ; let errs_found = errorsFound dflags msgs
598         ; return (msgs, case res of
599                           Nothing -> Nothing
600                           Just val | errs_found -> Nothing
601                                    | otherwise  -> Just val)
602         }
603
604 -----------------------
605 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
606 -- Just like tryTcErrs, except that it ensures that the LIE
607 -- for the thing is propagated only if there are no errors
608 -- Hence it's restricted to the type-check monad
609 tryTcLIE thing_inside
610   = do  { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
611         ; case mb_res of
612             Nothing  -> return (msgs, Nothing)
613             Just val -> do { extendLIEs lie; return (msgs, Just val) }
614         }
615
616 -----------------------
617 tryTcLIE_ :: TcM r -> TcM r -> TcM r
618 -- (tryTcLIE_ r m) tries m; 
619 --      if m succeeds with no error messages, it's the answer
620 --      otherwise tryTcLIE_ drops everything from m and tries r instead.
621 tryTcLIE_ recover main
622   = do  { (msgs, mb_res) <- tryTcLIE main
623         ; case mb_res of
624              Just val -> do { addMessages msgs  -- There might be warnings
625                              ; return val }
626              Nothing  -> recover                -- Discard all msgs
627         }
628
629 -----------------------
630 checkNoErrs :: TcM r -> TcM r
631 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
632 -- If m fails then (checkNoErrsTc m) fails.
633 -- If m succeeds, it checks whether m generated any errors messages
634 --      (it might have recovered internally)
635 --      If so, it fails too.
636 -- Regardless, any errors generated by m are propagated to the enclosing context.
637 checkNoErrs main
638   = do  { (msgs, mb_res) <- tryTcLIE main
639         ; addMessages msgs
640         ; case mb_res of
641             Nothing   -> failM
642             Just val -> return val
643         } 
644
645 ifErrsM :: TcRn r -> TcRn r -> TcRn r
646 --      ifErrsM bale_out main
647 -- does 'bale_out' if there are errors in errors collection
648 -- otherwise does 'main'
649 ifErrsM bale_out normal
650  = do { errs_var <- getErrsVar ;
651         msgs <- readMutVar errs_var ;
652         dflags <- getDOpts ;
653         if errorsFound dflags msgs then
654            bale_out
655         else    
656            normal }
657
658 failIfErrsM :: TcRn ()
659 -- Useful to avoid error cascades
660 failIfErrsM = ifErrsM failM (return ())
661 \end{code}
662
663
664 %************************************************************************
665 %*                                                                      *
666         Context management and error message generation
667                     for the type checker
668 %*                                                                      *
669 %************************************************************************
670
671 \begin{code}
672 getErrCtxt :: TcM ErrCtxt
673 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
674
675 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
676 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
677
678 addErrCtxt :: Message -> TcM a -> TcM a
679 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
680
681 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
682 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
683
684 -- Helper function for the above
685 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
686 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> 
687                            env { tcl_ctxt = upd ctxt })
688
689 -- Conditionally add an error context
690 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
691 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
692 maybeAddErrCtxt Nothing    thing_inside = thing_inside
693
694 popErrCtxt :: TcM a -> TcM a
695 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
696
697 getInstLoc :: InstOrigin -> TcM InstLoc
698 getInstLoc origin
699   = do { loc <- getSrcSpanM ; env <- getLclEnv ;
700          return (InstLoc origin loc (tcl_ctxt env)) }
701
702 addInstCtxt :: InstLoc -> TcM a -> TcM a
703 -- Add the SrcSpan and context from the first Inst in the list
704 --      (they all have similar locations)
705 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
706   = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
707 \end{code}
708
709     The addErrTc functions add an error message, but do not cause failure.
710     The 'M' variants pass a TidyEnv that has already been used to
711     tidy up the message; we then use it to tidy the context messages
712
713 \begin{code}
714 addErrTc :: Message -> TcM ()
715 addErrTc err_msg = do { env0 <- tcInitTidyEnv
716                       ; addErrTcM (env0, err_msg) }
717
718 addErrsTc :: [Message] -> TcM ()
719 addErrsTc err_msgs = mappM_ addErrTc err_msgs
720
721 addErrTcM :: (TidyEnv, Message) -> TcM ()
722 addErrTcM (tidy_env, err_msg)
723   = do { ctxt <- getErrCtxt ;
724          loc  <- getSrcSpanM ;
725          add_err_tcm tidy_env err_msg loc ctxt }
726 \end{code}
727
728 The failWith functions add an error message and cause failure
729
730 \begin{code}
731 failWithTc :: Message -> TcM a               -- Add an error message and fail
732 failWithTc err_msg 
733   = addErrTc err_msg >> failM
734
735 failWithTcM :: (TidyEnv, Message) -> TcM a   -- Add an error message and fail
736 failWithTcM local_and_msg
737   = addErrTcM local_and_msg >> failM
738
739 checkTc :: Bool -> Message -> TcM ()         -- Check that the boolean is true
740 checkTc True  err = returnM ()
741 checkTc False err = failWithTc err
742 \end{code}
743
744         Warnings have no 'M' variant, nor failure
745
746 \begin{code}
747 addWarnTc :: Message -> TcM ()
748 addWarnTc msg
749  = do { ctxt <- getErrCtxt ;
750         env0 <- tcInitTidyEnv ;
751         ctxt_msgs <- do_ctxt env0 ctxt ;
752         addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
753
754 warnTc :: Bool -> Message -> TcM ()
755 warnTc warn_if_true warn_msg
756   | warn_if_true = addWarnTc warn_msg
757   | otherwise    = return ()
758 \end{code}
759
760 -----------------------------------
761          Tidying
762
763 We initialise the "tidy-env", used for tidying types before printing,
764 by building a reverse map from the in-scope type variables to the
765 OccName that the programmer originally used for them
766
767 \begin{code}
768 tcInitTidyEnv :: TcM TidyEnv
769 tcInitTidyEnv
770   = do  { lcl_env <- getLclEnv
771         ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
772                           | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
773                           , tcIsTyVarTy ty ]
774         ; return (foldl add emptyTidyEnv nm_tv_prs) }
775   where
776     add (env,subst) (name, tyvar)
777         = case tidyOccName env (nameOccName name) of
778             (env', occ') ->  (env', extendVarEnv subst tyvar tyvar')
779                 where
780                   tyvar' = setTyVarName tyvar name'
781                   name'  = tidyNameOcc name occ'
782 \end{code}
783
784 -----------------------------------
785         Other helper functions
786
787 \begin{code}
788 add_err_tcm tidy_env err_msg loc ctxt
789  = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
790         addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
791
792 do_ctxt tidy_env []
793  = return []
794 do_ctxt tidy_env (c:cs)
795  = do { (tidy_env', m) <- c tidy_env  ;
796         ms             <- do_ctxt tidy_env' cs  ;
797         return (m:ms) }
798
799 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
800                  | otherwise          = take 3 ctxt
801 \end{code}
802
803 debugTc is useful for monadic debugging code
804
805 \begin{code}
806 debugTc :: TcM () -> TcM ()
807 #ifdef DEBUG
808 debugTc thing = thing
809 #else
810 debugTc thing = return ()
811 #endif
812 \end{code}
813
814  %************************************************************************
815 %*                                                                      *
816              Type constraints (the so-called LIE)
817 %*                                                                      *
818 %************************************************************************
819
820 \begin{code}
821 nextDFunIndex :: TcM Int        -- Get the next dfun index
822 nextDFunIndex = do { env <- getGblEnv
823                    ; let dfun_n_var = tcg_dfun_n env
824                    ; n <- readMutVar dfun_n_var
825                    ; writeMutVar dfun_n_var (n+1)
826                    ; return n }
827
828 getLIEVar :: TcM (TcRef LIE)
829 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
830
831 setLIEVar :: TcRef LIE -> TcM a -> TcM a
832 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
833
834 getLIE :: TcM a -> TcM (a, [Inst])
835 -- (getLIE m) runs m, and returns the type constraints it generates
836 getLIE thing_inside
837   = do { lie_var <- newMutVar emptyLIE ;
838          res <- updLclEnv (\ env -> env { tcl_lie = lie_var }) 
839                           thing_inside ;
840          lie <- readMutVar lie_var ;
841          return (res, lieToList lie) }
842
843 extendLIE :: Inst -> TcM ()
844 extendLIE inst
845   = do { lie_var <- getLIEVar ;
846          lie <- readMutVar lie_var ;
847          writeMutVar lie_var (inst `consLIE` lie) }
848
849 extendLIEs :: [Inst] -> TcM ()
850 extendLIEs [] 
851   = returnM ()
852 extendLIEs insts
853   = do { lie_var <- getLIEVar ;
854          lie <- readMutVar lie_var ;
855          writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
856 \end{code}
857
858 \begin{code}
859 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
860 -- Set the local type envt, but do *not* disturb other fields,
861 -- notably the lie_var
862 setLclTypeEnv lcl_env thing_inside
863   = updLclEnv upd thing_inside
864   where
865     upd env = env { tcl_env = tcl_env lcl_env,
866                     tcl_tyvars = tcl_tyvars lcl_env }
867 \end{code}
868
869
870 %************************************************************************
871 %*                                                                      *
872              Template Haskell context
873 %*                                                                      *
874 %************************************************************************
875
876 \begin{code}
877 recordThUse :: TcM ()
878 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
879
880 keepAliveTc :: Name -> TcM ()   -- Record the name in the keep-alive set
881 keepAliveTc n = do { env <- getGblEnv; 
882                    ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
883
884 keepAliveSetTc :: NameSet -> TcM ()     -- Record the name in the keep-alive set
885 keepAliveSetTc ns = do { env <- getGblEnv; 
886                        ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
887
888 getStage :: TcM ThStage
889 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
890
891 setStage :: ThStage -> TcM a -> TcM a 
892 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
893 \end{code}
894
895
896 %************************************************************************
897 %*                                                                      *
898              Stuff for the renamer's local env
899 %*                                                                      *
900 %************************************************************************
901
902 \begin{code}
903 getLocalRdrEnv :: RnM LocalRdrEnv
904 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
905
906 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
907 setLocalRdrEnv rdr_env thing_inside 
908   = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
909 \end{code}
910
911
912 %************************************************************************
913 %*                                                                      *
914              Stuff for interface decls
915 %*                                                                      *
916 %************************************************************************
917
918 \begin{code}
919 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
920 mkIfLclEnv mod loc = IfLclEnv { if_mod     = mod,
921                                 if_loc     = loc,
922                                 if_tv_env  = emptyOccEnv,
923                                 if_id_env  = emptyOccEnv }
924
925 initIfaceTcRn :: IfG a -> TcRn a
926 initIfaceTcRn thing_inside
927   = do  { tcg_env <- getGblEnv 
928         ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
929               ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
930         ; setEnvs (if_env, ()) thing_inside }
931
932 initIfaceExtCore :: IfL a -> TcRn a
933 initIfaceExtCore thing_inside
934   = do  { tcg_env <- getGblEnv 
935         ; let { mod = tcg_mod tcg_env
936               ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
937               ; if_env = IfGblEnv { 
938                         if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
939               ; if_lenv = mkIfLclEnv mod doc
940           }
941         ; setEnvs (if_env, if_lenv) thing_inside }
942
943 initIfaceCheck :: HscEnv -> IfG a -> IO a
944 -- Used when checking the up-to-date-ness of the old Iface
945 -- Initialise the environment with no useful info at all
946 initIfaceCheck hsc_env do_this
947  = do   { let gbl_env = IfGblEnv { if_rec_types = Nothing }
948         ; initTcRnIf 'i' hsc_env gbl_env () do_this
949     }
950
951 initIfaceTc :: ModIface 
952             -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
953 -- Used when type-checking checking an up-to-date interface file
954 -- No type envt from the current module, but we do know the module dependencies
955 initIfaceTc iface do_this
956  = do   { tc_env_var <- newMutVar emptyTypeEnv
957         ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
958               ; if_lenv = mkIfLclEnv mod doc
959            }
960         ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
961     }
962   where
963     mod = mi_module iface
964     doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
965
966 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
967 -- Used when sucking in new Rules in SimplCore
968 -- We have available the type envt of the module being compiled, and we must use it
969 initIfaceRules hsc_env guts do_this
970  = do   { let {
971              type_info = (mg_module guts, return (mg_types guts))
972            ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
973            }
974
975         -- Run the thing; any exceptions just bubble out from here
976         ; initTcRnIf 'i' hsc_env gbl_env () do_this
977     }
978
979 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
980 initIfaceLcl mod loc_doc thing_inside 
981   = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
982
983 getIfModule :: IfL Module
984 getIfModule = do { env <- getLclEnv; return (if_mod env) }
985
986 --------------------
987 failIfM :: Message -> IfL a
988 -- The Iface monad doesn't have a place to accumulate errors, so we
989 -- just fall over fast if one happens; it "shouldnt happen".
990 -- We use IfL here so that we can get context info out of the local env
991 failIfM msg
992   = do  { env <- getLclEnv
993         ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
994         ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
995         ; failM }
996
997 --------------------
998 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
999 -- Run thing_inside in an interleaved thread.  
1000 -- It shares everything with the parent thread, so this is DANGEROUS.  
1001 --
1002 -- It returns Nothing if the computation fails
1003 -- 
1004 -- It's used for lazily type-checking interface
1005 -- signatures, which is pretty benign
1006
1007 forkM_maybe doc thing_inside
1008  = do { unsafeInterleaveM $
1009         do { traceIf (text "Starting fork {" <+> doc)
1010            ; mb_res <- tryM $
1011                        updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $ 
1012                        thing_inside
1013            ; case mb_res of
1014                 Right r  -> do  { traceIf (text "} ending fork" <+> doc)
1015                                 ; return (Just r) }
1016                 Left exn -> do {
1017
1018                     -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1019                     -- Otherwise we silently discard errors. Errors can legitimately
1020                     -- happen when compiling interface signatures (see tcInterfaceSigs)
1021                       ifOptM Opt_D_dump_if_trace 
1022                              (print_errs (hang (text "forkM failed:" <+> doc)
1023                                              4 (text (show exn))))
1024
1025                     ; traceIf (text "} ending fork (badly)" <+> doc)
1026                     ; return Nothing }
1027         }}
1028   where
1029     print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1030
1031 forkM :: SDoc -> IfL a -> IfL a
1032 forkM doc thing_inside
1033  = do   { mb_res <- forkM_maybe doc thing_inside
1034         ; return (case mb_res of 
1035                         Nothing -> pgmError "Cannot continue after interface file error"
1036                                    -- pprPanic "forkM" doc
1037                         Just r  -> r) }
1038 \end{code}
1039
1040