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