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