fix haddock submodule pointer
[ghc-hetmet.git] / compiler / typecheck / TcRnMonad.lhs
1 %
2 % (c) The University of Glasgow 2006
3 %
4
5 \begin{code}
6 module TcRnMonad(
7         module TcRnMonad,
8         module TcRnTypes,
9         module IOEnv
10   ) where
11
12 #include "HsVersions.h"
13
14 import TcRnTypes        -- Re-export all
15 import IOEnv            -- Re-export all
16
17 import HsSyn hiding (LIE)
18 import HscTypes
19 import Module
20 import RdrName
21 import Name
22 import TcType
23 import InstEnv
24 import FamInstEnv
25 import PrelNames        ( iNTERACTIVE )
26
27 import Var
28 import Id
29 import VarSet
30 import VarEnv
31 import ErrUtils
32 import SrcLoc
33 import NameEnv
34 import NameSet
35 import Bag
36 import Outputable
37 import UniqSupply
38 import Unique
39 import UniqFM
40 import DynFlags
41 import StaticFlags
42 import FastString
43 import Panic
44 import Util
45
46 import System.IO
47 import Data.IORef
48 import qualified Data.Set as Set
49 import Control.Monad
50 \end{code}
51
52
53
54 %************************************************************************
55 %*                                                                      *
56                         initTc
57 %*                                                                      *
58 %************************************************************************
59
60 \begin{code}
61
62 initTc :: HscEnv
63        -> HscSource
64        -> Bool          -- True <=> retain renamed syntax trees
65        -> Module 
66        -> TcM r
67        -> IO (Messages, Maybe r)
68                 -- Nothing => error thrown by the thing inside
69                 -- (error messages should have been printed already)
70
71 initTc hsc_env hsc_src keep_rn_syntax mod do_this
72  = do { errs_var     <- newIORef (emptyBag, emptyBag) ;
73         meta_var     <- newIORef initTyVarUnique ;
74         tvs_var      <- newIORef emptyVarSet ;
75         keep_var     <- newIORef emptyNameSet ;
76         used_rdr_var <- newIORef Set.empty ;
77         th_var       <- newIORef False ;
78         lie_var      <- newIORef emptyWC ;
79         dfun_n_var   <- newIORef emptyOccSet ;
80         type_env_var <- case hsc_type_env_var hsc_env of {
81                            Just (_mod, te_var) -> return te_var ;
82                            Nothing             -> newIORef emptyNameEnv } ;
83         let {
84              maybe_rn_syntax :: forall a. a -> Maybe a ;
85              maybe_rn_syntax empty_val
86                 | keep_rn_syntax = Just empty_val
87                 | otherwise      = Nothing ;
88                         
89              gbl_env = TcGblEnv {
90                 tcg_mod       = mod,
91                 tcg_src       = hsc_src,
92                 tcg_rdr_env   = emptyGlobalRdrEnv,
93                 tcg_fix_env   = emptyNameEnv,
94                 tcg_field_env = RecFields emptyNameEnv emptyNameSet,
95                 tcg_default   = Nothing,
96                 tcg_type_env  = emptyNameEnv,
97                 tcg_type_env_var = type_env_var,
98                 tcg_inst_env  = emptyInstEnv,
99                 tcg_fam_inst_env  = emptyFamInstEnv,
100                 tcg_th_used   = th_var,
101                 tcg_exports  = [],
102                 tcg_imports  = emptyImportAvails,
103                 tcg_used_rdrnames = used_rdr_var,
104                 tcg_dus      = emptyDUs,
105
106                 tcg_rn_imports = [],
107                 tcg_rn_exports = maybe_rn_syntax [],
108                 tcg_rn_decls   = maybe_rn_syntax emptyRnGroup,
109
110                 tcg_binds     = emptyLHsBinds,
111                 tcg_imp_specs = [],
112                 tcg_sigs      = emptyNameSet,
113                 tcg_ev_binds  = emptyBag,
114                 tcg_warns     = NoWarnings,
115                 tcg_anns      = [],
116                 tcg_insts     = [],
117                 tcg_fam_insts = [],
118                 tcg_rules     = [],
119                 tcg_fords     = [],
120                 tcg_vects     = [],
121                 tcg_dfun_n    = dfun_n_var,
122                 tcg_keep      = keep_var,
123                 tcg_doc_hdr   = Nothing,
124                 tcg_hpc       = False,
125                 tcg_main      = Nothing
126              } ;
127              lcl_env = TcLclEnv {
128                 tcl_errs       = errs_var,
129                 tcl_loc        = mkGeneralSrcSpan (fsLit "Top level"),
130                 tcl_ctxt       = [],
131                 tcl_rdr        = emptyLocalRdrEnv,
132                 tcl_th_ctxt    = topStage,
133                 tcl_arrow_ctxt = NoArrowCtxt,
134                 tcl_env        = emptyNameEnv,
135                 tcl_tyvars     = tvs_var,
136                 tcl_lie        = lie_var,
137                 tcl_meta       = meta_var,
138                 tcl_untch      = initTyVarUnique,
139                 tcl_hetMetLevel    = []
140              } ;
141         } ;
142    
143         -- OK, here's the business end!
144         maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
145                      do { r <- tryM do_this
146                         ; case r of
147                           Right res -> return (Just res)
148                           Left _    -> return Nothing } ;
149
150         -- Check for unsolved constraints
151         lie <- readIORef lie_var ;
152         if isEmptyWC lie
153            then return ()
154            else pprPanic "initTc: unsolved constraints" 
155                          (pprWantedsWithLocs lie) ;
156
157         -- Collect any error messages
158         msgs <- readIORef errs_var ;
159
160         let { dflags = hsc_dflags hsc_env
161             ; final_res | errorsFound dflags msgs = Nothing
162                         | otherwise               = maybe_res } ;
163
164         return (msgs, final_res)
165     }
166
167 initTcPrintErrors       -- Used from the interactive loop only
168        :: HscEnv
169        -> Module 
170        -> TcM r
171        -> IO (Messages, Maybe r)
172
173 initTcPrintErrors env mod todo = initTc env HsSrcFile False mod todo
174 \end{code}
175
176 %************************************************************************
177 %*                                                                      *
178                 Initialisation
179 %*                                                                      *
180 %************************************************************************
181
182
183 \begin{code}
184 initTcRnIf :: Char              -- Tag for unique supply
185            -> HscEnv
186            -> gbl -> lcl 
187            -> TcRnIf gbl lcl a 
188            -> IO a
189 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
190    = do { us     <- mkSplitUniqSupply uniq_tag ;
191         ; us_var <- newIORef us ;
192
193         ; let { env = Env { env_top = hsc_env,
194                             env_us  = us_var,
195                             env_gbl = gbl_env,
196                             env_lcl = lcl_env} }
197
198         ; runIOEnv env thing_inside
199         }
200 \end{code}
201
202 %************************************************************************
203 %*                                                                      *
204                 Simple accessors
205 %*                                                                      *
206 %************************************************************************
207
208 \begin{code}
209 getTopEnv :: TcRnIf gbl lcl HscEnv
210 getTopEnv = do { env <- getEnv; return (env_top env) }
211
212 getGblEnv :: TcRnIf gbl lcl gbl
213 getGblEnv = do { env <- getEnv; return (env_gbl env) }
214
215 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
216 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) -> 
217                           env { env_gbl = upd gbl })
218
219 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
220 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
221
222 getLclEnv :: TcRnIf gbl lcl lcl
223 getLclEnv = do { env <- getEnv; return (env_lcl env) }
224
225 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
226 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) -> 
227                           env { env_lcl = upd lcl })
228
229 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
230 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
231
232 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
233 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
234
235 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
236 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
237 \end{code}
238
239
240 Command-line flags
241
242 \begin{code}
243 getDOpts :: TcRnIf gbl lcl DynFlags
244 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
245
246 xoptM :: ExtensionFlag -> TcRnIf gbl lcl Bool
247 xoptM flag = do { dflags <- getDOpts; return (xopt flag dflags) }
248
249 doptM :: DynFlag -> TcRnIf gbl lcl Bool
250 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
251
252 -- XXX setOptM and unsetOptM operate on different types. One should be renamed.
253
254 setOptM :: ExtensionFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
255 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
256                          env { env_top = top { hsc_dflags = xopt_set (hsc_dflags top) flag}} )
257
258 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
259 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
260                          env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
261
262 -- | Do it flag is true
263 ifDOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
264 ifDOptM flag thing_inside = do { b <- doptM flag; 
265                                 if b then thing_inside else return () }
266
267 ifXOptM :: ExtensionFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
268 ifXOptM flag thing_inside = do { b <- xoptM flag; 
269                                 if b then thing_inside else return () }
270
271 getGhcMode :: TcRnIf gbl lcl GhcMode
272 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
273 \end{code}
274
275 \begin{code}
276 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
277 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
278
279 getEps :: TcRnIf gbl lcl ExternalPackageState
280 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
281
282 -- | Update the external package state.  Returns the second result of the
283 -- modifier function.
284 --
285 -- This is an atomic operation and forces evaluation of the modified EPS in
286 -- order to avoid space leaks.
287 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
288           -> TcRnIf gbl lcl a
289 updateEps upd_fn = do
290   traceIf (text "updating EPS")
291   eps_var <- getEpsVar
292   atomicUpdMutVar' eps_var upd_fn
293
294 -- | Update the external package state.
295 --
296 -- This is an atomic operation and forces evaluation of the modified EPS in
297 -- order to avoid space leaks.
298 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
299            -> TcRnIf gbl lcl ()
300 updateEps_ upd_fn = do
301   traceIf (text "updating EPS_")
302   eps_var <- getEpsVar
303   atomicUpdMutVar' eps_var (\eps -> (upd_fn eps, ()))
304
305 getHpt :: TcRnIf gbl lcl HomePackageTable
306 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
307
308 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
309 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
310                   ; return (eps, hsc_HPT env) }
311 \end{code}
312
313 %************************************************************************
314 %*                                                                      *
315                 Unique supply
316 %*                                                                      *
317 %************************************************************************
318
319 \begin{code}
320 newMetaUnique :: TcM Unique
321 -- The uniques for TcMetaTyVars are allocated specially
322 -- in guaranteed linear order, starting at zero for each module
323 newMetaUnique 
324  = do { env <- getLclEnv
325       ; let meta_var = tcl_meta env
326       ; uniq <- readMutVar meta_var
327       ; writeMutVar meta_var (incrUnique uniq)
328       ; return uniq }
329
330 newUnique :: TcRnIf gbl lcl Unique
331 newUnique
332  = do { env <- getEnv ;
333         let { u_var = env_us env } ;
334         us <- readMutVar u_var ;
335         case takeUniqFromSupply us of { (uniq, us') -> do {
336         writeMutVar u_var us' ;
337         return $! uniq }}}
338    -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
339    -- a chain of unevaluated supplies behind.
340    -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
341    -- throw away one half of the new split supply.  This is safe because this
342    -- is the only place we use that unique.  Using the other half of the split
343    -- supply is safer, but slower.
344
345 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
346 newUniqueSupply
347  = do { env <- getEnv ;
348         let { u_var = env_us env } ;
349         us <- readMutVar u_var ;
350         case splitUniqSupply us of { (us1,us2) -> do {
351         writeMutVar u_var us1 ;
352         return us2 }}}
353
354 newLocalName :: Name -> TcRnIf gbl lcl Name
355 newLocalName name       -- Make a clone
356   = do  { uniq <- newUnique
357         ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
358
359 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
360 newSysLocalIds fs tys
361   = do  { us <- newUniqueSupply
362         ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
363
364 instance MonadUnique (IOEnv (Env gbl lcl)) where
365         getUniqueM = newUnique
366         getUniqueSupplyM = newUniqueSupply
367 \end{code}
368
369
370 %************************************************************************
371 %*                                                                      *
372                 Debugging
373 %*                                                                      *
374 %************************************************************************
375
376 \begin{code}
377 newTcRef :: a -> TcRnIf gbl lcl (TcRef a)
378 newTcRef = newMutVar 
379
380 readTcRef :: TcRef a -> TcRnIf gbl lcl a
381 readTcRef = readMutVar
382
383 writeTcRef :: TcRef a -> a -> TcRnIf gbl lcl ()
384 writeTcRef = writeMutVar
385
386 updTcRef :: TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
387 updTcRef = updMutVar
388 \end{code}
389
390 %************************************************************************
391 %*                                                                      *
392                 Debugging
393 %*                                                                      *
394 %************************************************************************
395
396 \begin{code}
397 traceTc :: String -> SDoc -> TcRn () 
398 traceTc = traceTcN 1
399
400 traceTcN :: Int -> String -> SDoc -> TcRn () 
401 traceTcN level herald doc
402   | level <= opt_TraceLevel = traceOptTcRn Opt_D_dump_tc_trace $
403                               hang (text herald) 2 doc
404   | otherwise               = return ()
405
406 traceRn, traceSplice :: SDoc -> TcRn ()
407 traceRn      = traceOptTcRn Opt_D_dump_rn_trace
408 traceSplice  = traceOptTcRn Opt_D_dump_splices
409
410 traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()
411 traceIf      = traceOptIf Opt_D_dump_if_trace
412 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
413
414
415 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n ()  -- No RdrEnv available, so qualify everything
416 traceOptIf flag doc = ifDOptM flag $
417                       liftIO (printForUser stderr alwaysQualify doc)
418
419 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
420 -- Output the message, with current location if opt_PprStyle_Debug
421 traceOptTcRn flag doc = ifDOptM flag $ do
422                         { loc  <- getSrcSpanM
423                         ; let real_doc 
424                                 | opt_PprStyle_Debug = mkLocMessage loc doc
425                                 | otherwise = doc   -- The full location is 
426                                                     -- usually way too much
427                         ; dumpTcRn real_doc }
428
429 dumpTcRn :: SDoc -> TcRn ()
430 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv 
431                   ; dflags <- getDOpts 
432                   ; liftIO (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
433
434 debugDumpTcRn :: SDoc -> TcRn ()
435 debugDumpTcRn doc | opt_NoDebugOutput = return ()
436                   | otherwise         = dumpTcRn doc
437
438 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
439 dumpOptTcRn flag doc = ifDOptM flag (dumpTcRn doc)
440 \end{code}
441
442
443 %************************************************************************
444 %*                                                                      *
445                 Typechecker global environment
446 %*                                                                      *
447 %************************************************************************
448
449 \begin{code}
450 getModule :: TcRn Module
451 getModule = do { env <- getGblEnv; return (tcg_mod env) }
452
453 setModule :: Module -> TcRn a -> TcRn a
454 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
455
456 getIsGHCi :: TcRn Bool
457 getIsGHCi = do { mod <- getModule; return (mod == iNTERACTIVE) }
458
459 tcIsHsBoot :: TcRn Bool
460 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
461
462 getGlobalRdrEnv :: TcRn GlobalRdrEnv
463 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
464
465 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
466 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
467
468 getImports :: TcRn ImportAvails
469 getImports = do { env <- getGblEnv; return (tcg_imports env) }
470
471 getFixityEnv :: TcRn FixityEnv
472 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
473
474 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
475 extendFixityEnv new_bit
476   = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) -> 
477                 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})           
478
479 getRecFieldEnv :: TcRn RecFieldEnv
480 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
481
482 getDeclaredDefaultTys :: TcRn (Maybe [Type])
483 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
484 \end{code}
485
486 %************************************************************************
487 %*                                                                      *
488                 Error management
489 %*                                                                      *
490 %************************************************************************
491
492 \begin{code}
493 getSrcSpanM :: TcRn SrcSpan
494         -- Avoid clash with Name.getSrcLoc
495 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
496
497 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
498 setSrcSpan loc@(RealSrcSpan _) thing_inside
499     = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
500 -- Don't overwrite useful info with useless:
501 setSrcSpan (UnhelpfulSpan _) thing_inside = thing_inside
502
503 addLocM :: (a -> TcM b) -> Located a -> TcM b
504 addLocM fn (L loc a) = setSrcSpan loc $ fn a
505
506 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
507 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
508
509 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
510 wrapLocFstM fn (L loc a) =
511   setSrcSpan loc $ do
512     (b,c) <- fn a
513     return (L loc b, c)
514
515 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
516 wrapLocSndM fn (L loc a) =
517   setSrcSpan loc $ do
518     (b,c) <- fn a
519     return (b, L loc c)
520 \end{code}
521
522 Reporting errors
523
524 \begin{code}
525 getErrsVar :: TcRn (TcRef Messages)
526 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
527
528 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
529 setErrsVar v = updLclEnv (\ env -> env { tcl_errs =  v })
530
531 addErr :: Message -> TcRn ()    -- Ignores the context stack
532 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
533
534 failWith :: Message -> TcRn a
535 failWith msg = addErr msg >> failM
536
537 addErrAt :: SrcSpan -> Message -> TcRn ()
538 -- addErrAt is mainly (exclusively?) used by the renamer, where
539 -- tidying is not an issue, but it's all lazy so the extra
540 -- work doesn't matter
541 addErrAt loc msg = do { ctxt <- getErrCtxt 
542                       ; tidy_env <- tcInitTidyEnv
543                       ; err_info <- mkErrInfo tidy_env ctxt
544                       ; addLongErrAt loc msg err_info }
545
546 addErrs :: [(SrcSpan,Message)] -> TcRn ()
547 addErrs msgs = mapM_ add msgs
548              where
549                add (loc,msg) = addErrAt loc msg
550
551 addWarn :: Message -> TcRn ()
552 addWarn msg = addReport (ptext (sLit "Warning:") <+> msg) empty
553
554 addWarnAt :: SrcSpan -> Message -> TcRn ()
555 addWarnAt loc msg = addReportAt loc (ptext (sLit "Warning:") <+> msg) empty
556
557 checkErr :: Bool -> Message -> TcRn ()
558 -- Add the error if the bool is False
559 checkErr ok msg = unless ok (addErr msg)
560
561 warnIf :: Bool -> Message -> TcRn ()
562 warnIf True  msg = addWarn msg
563 warnIf False _   = return ()
564
565 addMessages :: Messages -> TcRn ()
566 addMessages (m_warns, m_errs)
567   = do { errs_var <- getErrsVar ;
568          (warns, errs) <- readTcRef errs_var ;
569          writeTcRef errs_var (warns `unionBags` m_warns,
570                                errs  `unionBags` m_errs) }
571
572 discardWarnings :: TcRn a -> TcRn a
573 -- Ignore warnings inside the thing inside;
574 -- used to ignore-unused-variable warnings inside derived code
575 -- With -dppr-debug, the effects is switched off, so you can still see
576 -- what warnings derived code would give
577 discardWarnings thing_inside
578   | opt_PprStyle_Debug = thing_inside
579   | otherwise
580   = do  { errs_var <- newTcRef emptyMessages
581         ; result <- setErrsVar errs_var thing_inside
582         ; (_warns, errs) <- readTcRef errs_var
583         ; addMessages (emptyBag, errs)
584         ; return result }
585 \end{code}
586
587
588 %************************************************************************
589 %*                                                                      *
590         Shared error message stuff: renamer and typechecker
591 %*                                                                      *
592 %************************************************************************
593
594 \begin{code}
595 addReport :: Message -> Message -> TcRn ()
596 addReport msg extra_info = do loc <- getSrcSpanM; addReportAt loc msg extra_info
597
598 addReportAt :: SrcSpan -> Message -> Message -> TcRn ()
599 addReportAt loc msg extra_info
600   = do { errs_var <- getErrsVar ;
601          rdr_env <- getGlobalRdrEnv ;
602          dflags <- getDOpts ;
603          let { warn = mkLongWarnMsg loc (mkPrintUnqualified dflags rdr_env)
604                                     msg extra_info } ;
605          (warns, errs) <- readTcRef errs_var ;
606          writeTcRef errs_var (warns `snocBag` warn, errs) }
607
608 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
609 addLongErrAt loc msg extra
610   = do { traceTc "Adding error:" (mkLocMessage loc (msg $$ extra)) ;    
611          errs_var <- getErrsVar ;
612          rdr_env <- getGlobalRdrEnv ;
613          dflags <- getDOpts ;
614          let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
615          (warns, errs) <- readTcRef errs_var ;
616          writeTcRef errs_var (warns, errs `snocBag` err) }
617
618 dumpDerivingInfo :: SDoc -> TcM ()
619 dumpDerivingInfo doc
620   = do { dflags <- getDOpts
621        ; when (dopt Opt_D_dump_deriv dflags) $ do
622        { rdr_env <- getGlobalRdrEnv
623        ; let unqual = mkPrintUnqualified dflags rdr_env
624        ; liftIO (putMsgWith dflags unqual doc) } }
625 \end{code}
626
627
628 \begin{code}
629 try_m :: TcRn r -> TcRn (Either IOEnvFailure r)
630 -- Does try_m, with a debug-trace on failure
631 try_m thing 
632   = do { mb_r <- tryM thing ;
633          case mb_r of 
634              Left exn -> do { traceTc "tryTc/recoverM recovering from" $
635                                       text (showException exn)
636                             ; return mb_r }
637              Right _  -> return mb_r }
638
639 -----------------------
640 recoverM :: TcRn r      -- Recovery action; do this if the main one fails
641          -> TcRn r      -- Main action: do this first
642          -> TcRn r
643 -- Errors in 'thing' are retained
644 recoverM recover thing 
645   = do { mb_res <- try_m thing ;
646          case mb_res of
647            Left _    -> recover
648            Right res -> return res }
649
650
651 -----------------------
652 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
653 -- Drop elements of the input that fail, so the result
654 -- list can be shorter than the argument list
655 mapAndRecoverM _ []     = return []
656 mapAndRecoverM f (x:xs) = do { mb_r <- try_m (f x)
657                              ; rs <- mapAndRecoverM f xs
658                              ; return (case mb_r of
659                                           Left _  -> rs
660                                           Right r -> r:rs) }
661                         
662
663 -----------------------
664 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
665 -- (tryTc m) executes m, and returns
666 --      Just r,  if m succeeds (returning r)
667 --      Nothing, if m fails
668 -- It also returns all the errors and warnings accumulated by m
669 -- It always succeeds (never raises an exception)
670 tryTc m 
671  = do { errs_var <- newTcRef emptyMessages ;
672         res  <- try_m (setErrsVar errs_var m) ; 
673         msgs <- readTcRef errs_var ;
674         return (msgs, case res of
675                             Left _  -> Nothing
676                             Right val -> Just val)
677         -- The exception is always the IOEnv built-in
678         -- in exception; see IOEnv.failM
679    }
680
681 -----------------------
682 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
683 -- Run the thing, returning 
684 --      Just r,  if m succceeds with no error messages
685 --      Nothing, if m fails, or if it succeeds but has error messages
686 -- Either way, the messages are returned; even in the Just case
687 -- there might be warnings
688 tryTcErrs thing 
689   = do  { (msgs, res) <- tryTc thing
690         ; dflags <- getDOpts
691         ; let errs_found = errorsFound dflags msgs
692         ; return (msgs, case res of
693                           Nothing -> Nothing
694                           Just val | errs_found -> Nothing
695                                    | otherwise  -> Just val)
696         }
697
698 -----------------------
699 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
700 -- Just like tryTcErrs, except that it ensures that the LIE
701 -- for the thing is propagated only if there are no errors
702 -- Hence it's restricted to the type-check monad
703 tryTcLIE thing_inside
704   = do  { ((msgs, mb_res), lie) <- captureConstraints (tryTcErrs thing_inside) ;
705         ; case mb_res of
706             Nothing  -> return (msgs, Nothing)
707             Just val -> do { emitConstraints lie; return (msgs, Just val) }
708         }
709
710 -----------------------
711 tryTcLIE_ :: TcM r -> TcM r -> TcM r
712 -- (tryTcLIE_ r m) tries m; 
713 --      if m succeeds with no error messages, it's the answer
714 --      otherwise tryTcLIE_ drops everything from m and tries r instead.
715 tryTcLIE_ recover main
716   = do  { (msgs, mb_res) <- tryTcLIE main
717         ; case mb_res of
718              Just val -> do { addMessages msgs  -- There might be warnings
719                              ; return val }
720              Nothing  -> recover                -- Discard all msgs
721         }
722
723 -----------------------
724 checkNoErrs :: TcM r -> TcM r
725 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
726 -- If m fails then (checkNoErrsTc m) fails.
727 -- If m succeeds, it checks whether m generated any errors messages
728 --      (it might have recovered internally)
729 --      If so, it fails too.
730 -- Regardless, any errors generated by m are propagated to the enclosing context.
731 checkNoErrs main
732   = do  { (msgs, mb_res) <- tryTcLIE main
733         ; addMessages msgs
734         ; case mb_res of
735             Nothing  -> failM
736             Just val -> return val
737         } 
738
739 ifErrsM :: TcRn r -> TcRn r -> TcRn r
740 --      ifErrsM bale_out main
741 -- does 'bale_out' if there are errors in errors collection
742 -- otherwise does 'main'
743 ifErrsM bale_out normal
744  = do { errs_var <- getErrsVar ;
745         msgs <- readTcRef errs_var ;
746         dflags <- getDOpts ;
747         if errorsFound dflags msgs then
748            bale_out
749         else    
750            normal }
751
752 failIfErrsM :: TcRn ()
753 -- Useful to avoid error cascades
754 failIfErrsM = ifErrsM failM (return ())
755 \end{code}
756
757
758 %************************************************************************
759 %*                                                                      *
760         Context management for the type checker
761 %*                                                                      *
762 %************************************************************************
763
764 \begin{code}
765 getErrCtxt :: TcM [ErrCtxt]
766 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
767
768 setErrCtxt :: [ErrCtxt] -> TcM a -> TcM a
769 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
770
771 addErrCtxt :: Message -> TcM a -> TcM a
772 addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
773
774 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
775 addErrCtxtM ctxt = updCtxt (\ ctxts -> (False, ctxt) : ctxts)
776
777 addLandmarkErrCtxt :: Message -> TcM a -> TcM a
778 addLandmarkErrCtxt msg = updCtxt (\ctxts -> (True, \env -> return (env,msg)) : ctxts)
779
780 -- Helper function for the above
781 updCtxt :: ([ErrCtxt] -> [ErrCtxt]) -> TcM a -> TcM a
782 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> 
783                            env { tcl_ctxt = upd ctxt })
784
785 popErrCtxt :: TcM a -> TcM a
786 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
787
788 getCtLoc :: orig -> TcM (CtLoc orig)
789 getCtLoc origin
790   = do { loc <- getSrcSpanM ; env <- getLclEnv ;
791          return (CtLoc origin loc (tcl_ctxt env)) }
792
793 setCtLoc :: CtLoc orig -> TcM a -> TcM a
794 setCtLoc (CtLoc _ src_loc ctxt) thing_inside
795   = setSrcSpan src_loc (setErrCtxt ctxt thing_inside)
796 \end{code}
797
798 %************************************************************************
799 %*                                                                      *
800              Error message generation (type checker)
801 %*                                                                      *
802 %************************************************************************
803
804     The addErrTc functions add an error message, but do not cause failure.
805     The 'M' variants pass a TidyEnv that has already been used to
806     tidy up the message; we then use it to tidy the context messages
807
808 \begin{code}
809 addErrTc :: Message -> TcM ()
810 addErrTc err_msg = do { env0 <- tcInitTidyEnv
811                       ; addErrTcM (env0, err_msg) }
812
813 addErrsTc :: [Message] -> TcM ()
814 addErrsTc err_msgs = mapM_ addErrTc err_msgs
815
816 addErrTcM :: (TidyEnv, Message) -> TcM ()
817 addErrTcM (tidy_env, err_msg)
818   = do { ctxt <- getErrCtxt ;
819          loc  <- getSrcSpanM ;
820          add_err_tcm tidy_env err_msg loc ctxt }
821 \end{code}
822
823 The failWith functions add an error message and cause failure
824
825 \begin{code}
826 failWithTc :: Message -> TcM a               -- Add an error message and fail
827 failWithTc err_msg 
828   = addErrTc err_msg >> failM
829
830 failWithTcM :: (TidyEnv, Message) -> TcM a   -- Add an error message and fail
831 failWithTcM local_and_msg
832   = addErrTcM local_and_msg >> failM
833
834 checkTc :: Bool -> Message -> TcM ()         -- Check that the boolean is true
835 checkTc True  _   = return ()
836 checkTc False err = failWithTc err
837 \end{code}
838
839         Warnings have no 'M' variant, nor failure
840
841 \begin{code}
842 addWarnTc :: Message -> TcM ()
843 addWarnTc msg = do { env0 <- tcInitTidyEnv 
844                    ; addWarnTcM (env0, msg) }
845
846 addWarnTcM :: (TidyEnv, Message) -> TcM ()
847 addWarnTcM (env0, msg)
848  = do { ctxt <- getErrCtxt ;
849         err_info <- mkErrInfo env0 ctxt ;
850         addReport (ptext (sLit "Warning:") <+> msg) err_info }
851
852 warnTc :: Bool -> Message -> TcM ()
853 warnTc warn_if_true warn_msg
854   | warn_if_true = addWarnTc warn_msg
855   | otherwise    = return ()
856 \end{code}
857
858 -----------------------------------
859          Tidying
860
861 We initialise the "tidy-env", used for tidying types before printing,
862 by building a reverse map from the in-scope type variables to the
863 OccName that the programmer originally used for them
864
865 \begin{code}
866 tcInitTidyEnv :: TcM TidyEnv
867 tcInitTidyEnv
868   = do  { lcl_env <- getLclEnv
869         ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
870                           | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
871                           , tcIsTyVarTy ty ]
872         ; return (foldl add emptyTidyEnv nm_tv_prs) }
873   where
874     add (env,subst) (name, tyvar)
875         = case tidyOccName env (nameOccName name) of
876             (env', occ') ->  (env', extendVarEnv subst tyvar tyvar')
877                 where
878                   tyvar' = setTyVarName tyvar name'
879                   name'  = tidyNameOcc name occ'
880 \end{code}
881
882 -----------------------------------
883         Other helper functions
884
885 \begin{code}
886 add_err_tcm :: TidyEnv -> Message -> SrcSpan
887             -> [ErrCtxt]
888             -> TcM ()
889 add_err_tcm tidy_env err_msg loc ctxt
890  = do { err_info <- mkErrInfo tidy_env ctxt ;
891         addLongErrAt loc err_msg err_info }
892
893 mkErrInfo :: TidyEnv -> [ErrCtxt] -> TcM SDoc
894 -- Tidy the error info, trimming excessive contexts
895 mkErrInfo env ctxts
896  | opt_PprStyle_Debug     -- In -dppr-debug style the output 
897  = return empty           -- just becomes too voluminous
898  | otherwise
899  = go 0 env ctxts
900  where
901    go :: Int -> TidyEnv -> [ErrCtxt] -> TcM SDoc
902    go _ _   [] = return empty
903    go n env ((is_landmark, ctxt) : ctxts)
904      | is_landmark || n < mAX_CONTEXTS -- Too verbose || opt_PprStyle_Debug 
905      = do { (env', msg) <- ctxt env
906           ; let n' = if is_landmark then n else n+1
907           ; rest <- go n' env' ctxts
908           ; return (msg $$ rest) }
909      | otherwise
910      = go n env ctxts
911
912 mAX_CONTEXTS :: Int     -- No more than this number of non-landmark contexts
913 mAX_CONTEXTS = 3
914 \end{code}
915
916 debugTc is useful for monadic debugging code
917
918 \begin{code}
919 debugTc :: TcM () -> TcM ()
920 debugTc thing
921  | debugIsOn = thing
922  | otherwise = return ()
923 \end{code}
924
925 %************************************************************************
926 %*                                                                      *
927              Type constraints
928 %*                                                                      *
929 %************************************************************************
930
931 \begin{code}
932 newTcEvBinds :: TcM EvBindsVar
933 newTcEvBinds = do { ref <- newTcRef emptyEvBindMap
934                   ; uniq <- newUnique
935                   ; return (EvBindsVar ref uniq) }
936
937 extendTcEvBinds :: TcEvBinds -> EvVar -> EvTerm -> TcM TcEvBinds
938 extendTcEvBinds binds@(TcEvBinds binds_var) var rhs 
939   = do { addTcEvBind binds_var var rhs
940        ; return binds }
941 extendTcEvBinds (EvBinds bnds) var rhs
942   = return (EvBinds (bnds `snocBag` EvBind var rhs))
943
944 addTcEvBind :: EvBindsVar -> EvVar -> EvTerm -> TcM ()
945 -- Add a binding to the TcEvBinds by side effect
946 addTcEvBind (EvBindsVar ev_ref _) var rhs
947   = do { bnds <- readTcRef ev_ref
948        ; writeTcRef ev_ref (extendEvBinds bnds var rhs) }
949
950 chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
951 chooseUniqueOccTc fn =
952   do { env <- getGblEnv
953      ; let dfun_n_var = tcg_dfun_n env
954      ; set <- readTcRef dfun_n_var
955      ; let occ = fn set
956      ; writeTcRef dfun_n_var (extendOccSet set occ)
957      ; return occ }
958
959 getConstraintVar :: TcM (TcRef WantedConstraints)
960 getConstraintVar = do { env <- getLclEnv; return (tcl_lie env) }
961
962 setConstraintVar :: TcRef WantedConstraints -> TcM a -> TcM a
963 setConstraintVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
964
965 emitConstraints :: WantedConstraints -> TcM ()
966 emitConstraints ct
967   = do { lie_var <- getConstraintVar ;
968          updTcRef lie_var (`andWC` ct) }
969
970 emitFlat :: WantedEvVar -> TcM ()
971 emitFlat ct
972   = do { lie_var <- getConstraintVar ;
973          updTcRef lie_var (`addFlats` unitBag ct) }
974
975 emitFlats :: Bag WantedEvVar -> TcM ()
976 emitFlats ct
977   = do { lie_var <- getConstraintVar ;
978          updTcRef lie_var (`addFlats` ct) }
979
980 emitImplication :: Implication -> TcM ()
981 emitImplication ct
982   = do { lie_var <- getConstraintVar ;
983          updTcRef lie_var (`addImplics` unitBag ct) }
984
985 emitImplications :: Bag Implication -> TcM ()
986 emitImplications ct
987   = do { lie_var <- getConstraintVar ;
988          updTcRef lie_var (`addImplics` ct) }
989
990 captureConstraints :: TcM a -> TcM (a, WantedConstraints)
991 -- (captureConstraints m) runs m, and returns the type constraints it generates
992 captureConstraints thing_inside
993   = do { lie_var <- newTcRef emptyWC ;
994          res <- updLclEnv (\ env -> env { tcl_lie = lie_var }) 
995                           thing_inside ;
996          lie <- readTcRef lie_var ;
997          return (res, lie) }
998
999 captureUntouchables :: TcM a -> TcM (a, Untouchables)
1000 captureUntouchables thing_inside
1001   = do { env <- getLclEnv
1002        ; low_meta <- readTcRef (tcl_meta env)
1003        ; res <- setLclEnv (env { tcl_untch = low_meta }) 
1004                 thing_inside 
1005        ; high_meta <- readTcRef (tcl_meta env)
1006        ; return (res, TouchableRange low_meta high_meta) }
1007
1008 isUntouchable :: TcTyVar -> TcM Bool
1009 isUntouchable tv = do { env <- getLclEnv
1010                       ; return (varUnique tv < tcl_untch env) }
1011
1012 getLclTypeEnv :: TcM (NameEnv TcTyThing)
1013 getLclTypeEnv = do { env <- getLclEnv; return (tcl_env env) }
1014
1015 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
1016 -- Set the local type envt, but do *not* disturb other fields,
1017 -- notably the lie_var
1018 setLclTypeEnv lcl_env thing_inside
1019   = updLclEnv upd thing_inside
1020   where
1021     upd env = env { tcl_env = tcl_env lcl_env,
1022                     tcl_tyvars = tcl_tyvars lcl_env }
1023
1024 traceTcConstraints :: String -> TcM ()
1025 traceTcConstraints msg
1026   = do { lie_var <- getConstraintVar
1027        ; lie     <- readTcRef lie_var
1028        ; traceTc (msg ++ "LIE:") (ppr lie)
1029        }
1030 \end{code}
1031
1032
1033 %************************************************************************
1034 %*                                                                      *
1035              Template Haskell context
1036 %*                                                                      *
1037 %************************************************************************
1038
1039 \begin{code}
1040 recordThUse :: TcM ()
1041 recordThUse = do { env <- getGblEnv; writeTcRef (tcg_th_used env) True }
1042
1043 keepAliveTc :: Id -> TcM ()     -- Record the name in the keep-alive set
1044 keepAliveTc id 
1045   | isLocalId id = do { env <- getGblEnv; 
1046                       ; updTcRef (tcg_keep env) (`addOneToNameSet` idName id) }
1047   | otherwise = return ()
1048
1049 keepAliveSetTc :: NameSet -> TcM ()     -- Record the name in the keep-alive set
1050 keepAliveSetTc ns = do { env <- getGblEnv; 
1051                        ; updTcRef (tcg_keep env) (`unionNameSets` ns) }
1052
1053 getStage :: TcM ThStage
1054 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
1055
1056 setStage :: ThStage -> TcM a -> TcM a 
1057 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
1058 \end{code}
1059
1060
1061 %************************************************************************
1062 %*                                                                      *
1063              Stuff for the renamer's local env
1064 %*                                                                      *
1065 %************************************************************************
1066
1067 \begin{code}
1068 getLocalRdrEnv :: RnM LocalRdrEnv
1069 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
1070
1071 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
1072 setLocalRdrEnv rdr_env thing_inside 
1073   = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
1074 \end{code}
1075
1076
1077 %************************************************************************
1078 %*                                                                      *
1079              Stuff for interface decls
1080 %*                                                                      *
1081 %************************************************************************
1082
1083 \begin{code}
1084 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
1085 mkIfLclEnv mod loc = IfLclEnv { if_mod     = mod,
1086                                 if_loc     = loc,
1087                                 if_tv_env  = emptyUFM,
1088                                 if_id_env  = emptyUFM }
1089
1090 initIfaceTcRn :: IfG a -> TcRn a
1091 initIfaceTcRn thing_inside
1092   = do  { tcg_env <- getGblEnv 
1093         ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
1094               ; get_type_env = readTcRef (tcg_type_env_var tcg_env) }
1095         ; setEnvs (if_env, ()) thing_inside }
1096
1097 initIfaceExtCore :: IfL a -> TcRn a
1098 initIfaceExtCore thing_inside
1099   = do  { tcg_env <- getGblEnv 
1100         ; let { mod = tcg_mod tcg_env
1101               ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
1102               ; if_env = IfGblEnv { 
1103                         if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
1104               ; if_lenv = mkIfLclEnv mod doc
1105           }
1106         ; setEnvs (if_env, if_lenv) thing_inside }
1107
1108 initIfaceCheck :: HscEnv -> IfG a -> IO a
1109 -- Used when checking the up-to-date-ness of the old Iface
1110 -- Initialise the environment with no useful info at all
1111 initIfaceCheck hsc_env do_this
1112  = do let rec_types = case hsc_type_env_var hsc_env of
1113                          Just (mod,var) -> Just (mod, readTcRef var)
1114                          Nothing        -> Nothing
1115           gbl_env = IfGblEnv { if_rec_types = rec_types }
1116       initTcRnIf 'i' hsc_env gbl_env () do_this
1117
1118 initIfaceTc :: ModIface 
1119             -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
1120 -- Used when type-checking checking an up-to-date interface file
1121 -- No type envt from the current module, but we do know the module dependencies
1122 initIfaceTc iface do_this
1123  = do   { tc_env_var <- newTcRef emptyTypeEnv
1124         ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readTcRef tc_env_var) } ;
1125               ; if_lenv = mkIfLclEnv mod doc
1126            }
1127         ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
1128     }
1129   where
1130     mod = mi_module iface
1131     doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
1132
1133 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
1134 -- Used when sucking in new Rules in SimplCore
1135 -- We have available the type envt of the module being compiled, and we must use it
1136 initIfaceRules hsc_env guts do_this
1137  = do   { let {
1138              type_info = (mg_module guts, return (mg_types guts))
1139            ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
1140            }
1141
1142         -- Run the thing; any exceptions just bubble out from here
1143         ; initTcRnIf 'i' hsc_env gbl_env () do_this
1144     }
1145
1146 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
1147 initIfaceLcl mod loc_doc thing_inside 
1148   = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1149
1150 getIfModule :: IfL Module
1151 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1152
1153 --------------------
1154 failIfM :: Message -> IfL a
1155 -- The Iface monad doesn't have a place to accumulate errors, so we
1156 -- just fall over fast if one happens; it "shouldnt happen".
1157 -- We use IfL here so that we can get context info out of the local env
1158 failIfM msg
1159   = do  { env <- getLclEnv
1160         ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1161         ; liftIO (printErrs full_msg defaultErrStyle)
1162         ; failM }
1163
1164 --------------------
1165 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1166 -- Run thing_inside in an interleaved thread.  
1167 -- It shares everything with the parent thread, so this is DANGEROUS.  
1168 --
1169 -- It returns Nothing if the computation fails
1170 -- 
1171 -- It's used for lazily type-checking interface
1172 -- signatures, which is pretty benign
1173
1174 forkM_maybe doc thing_inside
1175  = do { unsafeInterleaveM $
1176         do { traceIf (text "Starting fork {" <+> doc)
1177            ; mb_res <- tryM $
1178                        updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $ 
1179                        thing_inside
1180            ; case mb_res of
1181                 Right r  -> do  { traceIf (text "} ending fork" <+> doc)
1182                                 ; return (Just r) }
1183                 Left exn -> do {
1184
1185                     -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1186                     -- Otherwise we silently discard errors. Errors can legitimately
1187                     -- happen when compiling interface signatures (see tcInterfaceSigs)
1188                       ifDOptM Opt_D_dump_if_trace 
1189                              (print_errs (hang (text "forkM failed:" <+> doc)
1190                                              2 (text (show exn))))
1191
1192                     ; traceIf (text "} ending fork (badly)" <+> doc)
1193                     ; return Nothing }
1194         }}
1195   where
1196     print_errs sdoc = liftIO (printErrs sdoc defaultErrStyle)
1197
1198 forkM :: SDoc -> IfL a -> IfL a
1199 forkM doc thing_inside
1200  = do   { mb_res <- forkM_maybe doc thing_inside
1201         ; return (case mb_res of 
1202                         Nothing -> pgmError "Cannot continue after interface file error"
1203                                    -- pprPanic "forkM" doc
1204                         Just r  -> r) }
1205 \end{code}