[project @ 2002-10-24 14:17:46 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcRnMonad.lhs
1 \begin{code}
2 module TcRnMonad(
3         module TcRnMonad,
4         module TcRnTypes
5   ) where
6
7 #include "HsVersions.h"
8
9 import HsSyn            ( MonoBinds(..) )
10 import HscTypes         ( HscEnv(..), PersistentCompilerState(..),
11                           emptyFixityEnv, emptyGlobalRdrEnv, TyThing,
12                           ExternalPackageState(..), HomePackageTable,
13                           ModDetails(..), HomeModInfo(..), Deprecations(..),
14                           GlobalRdrEnv, LocalRdrEnv, NameCache, FixityEnv,
15                           GhciMode, lookupType, unQualInScope )
16 import TcRnTypes
17 import Module           ( Module, moduleName, unitModuleEnv, foldModuleEnv )
18 import Name             ( Name, isInternalName )
19 import Type             ( Type )
20 import NameEnv          ( extendNameEnvList )
21 import InstEnv          ( InstEnv, extendInstEnv )
22 import TysWiredIn       ( integerTy, doubleTy )
23
24 import VarSet           ( emptyVarSet )
25 import VarEnv           ( TidyEnv, emptyTidyEnv )
26 import RdrName          ( emptyRdrEnv )
27 import ErrUtils         ( Message, Messages, emptyMessages, errorsFound, 
28                           addShortErrLocLine, addShortWarnLocLine, printErrorsAndWarnings )
29 import SrcLoc           ( SrcLoc, noSrcLoc )
30 import NameEnv          ( emptyNameEnv )
31 import Bag              ( emptyBag )
32 import Outputable
33 import UniqSupply       ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
34 import Unique           ( Unique )
35 import CmdLineOpts      ( DynFlags, DynFlag(..), dopt, opt_PprStyle_Debug )
36 import BasicTypes       ( FixitySig )
37 import Bag              ( snocBag, unionBags )
38
39 import Maybe            ( isJust )
40 import IO               ( stderr )
41 import DATA_IOREF       ( newIORef, readIORef )
42 \end{code}
43
44 %************************************************************************
45 %*                                                                      *
46         Standard combinators, but specialised for this monad
47                         (for efficiency)
48 %*                                                                      *
49 6%************************************************************************
50
51 \begin{code}
52 mappM         :: (a -> TcRn m b) -> [a] -> TcRn m [b]
53 mappM_        :: (a -> TcRn m b) -> [a] -> TcRn m ()
54         -- Funny names to avoid clash with Prelude
55 sequenceM     :: [TcRn m a] -> TcRn m [a]
56 foldlM        :: (a -> b -> TcRn m a)  -> a -> [b] -> TcRn m a
57 mapAndUnzipM  :: (a -> TcRn m (b,c))   -> [a] -> TcRn m ([b],[c])
58 mapAndUnzip3M :: (a -> TcRn m (b,c,d)) -> [a] -> TcRn m ([b],[c],[d])
59 checkM        :: Bool -> TcRn m () -> TcRn m () -- Perform arg if bool is False
60 ifM           :: Bool -> TcRn m () -> TcRn m () -- Perform arg if bool is True
61
62 mappM f []     = return []
63 mappM f (x:xs) = do { r <- f x; rs <- mappM f xs; return (r:rs) }
64
65 mappM_ f []     = return ()
66 mappM_ f (x:xs) = f x >> mappM_ f xs
67
68 sequenceM [] = return []
69 sequenceM (x:xs) = do { r <- x; rs <- sequenceM xs; return (r:rs) }
70
71 foldlM k z [] = return z
72 foldlM k z (x:xs) = do { r <- k z x; foldlM k r xs }
73
74 mapAndUnzipM f []     = return ([],[])
75 mapAndUnzipM f (x:xs) = do { (r,s) <- f x; 
76                              (rs,ss) <- mapAndUnzipM f xs; 
77                              return (r:rs, s:ss) }
78
79 mapAndUnzip3M f []     = return ([],[], [])
80 mapAndUnzip3M f (x:xs) = do { (r,s,t) <- f x; 
81                               (rs,ss,ts) <- mapAndUnzip3M f xs; 
82                               return (r:rs, s:ss, t:ts) }
83
84 checkM True  err = return ()
85 checkM False err = err
86
87 ifM True  do_it = do_it
88 ifM False do_it = return ()
89 \end{code}
90
91
92 %************************************************************************
93 %*                                                                      *
94                         initTc
95 %*                                                                      *
96 %************************************************************************
97
98 \begin{code}
99 initTc :: HscEnv -> PersistentCompilerState
100        -> Module 
101        -> TcM r
102        -> IO (PersistentCompilerState, Maybe r)
103                 -- Nothing => error thrown by the thing inside
104                 -- (error messages should have been printed already)
105
106 initTc  (HscEnv { hsc_mode   = ghci_mode,
107                   hsc_HPT    = hpt,
108                   hsc_dflags = dflags })
109         pcs mod do_this
110  = do { us       <- mkSplitUniqSupply 'a' ;
111         us_var   <- newIORef us ;
112         errs_var <- newIORef (emptyBag, emptyBag) ;
113         tvs_var  <- newIORef emptyVarSet ;
114         usg_var  <- newIORef emptyUsages ;
115         nc_var   <- newIORef (pcs_nc pcs) ;
116         eps_var  <- newIORef eps ;
117    
118         let {
119              env = Env { env_top = top_env,
120                          env_gbl = gbl_env,
121                          env_lcl = lcl_env,
122                          env_loc = noSrcLoc } ;
123
124              top_env = TopEnv { 
125                 top_mode   = ghci_mode,
126                 top_dflags = dflags,
127                 top_eps    = eps_var,
128                 top_hpt    = hpt,
129                 top_nc     = nc_var,
130                 top_us     = us_var,
131                 top_errs   = errs_var } ;
132
133              gbl_env = TcGblEnv {
134                 tcg_mod      = mod,
135                 tcg_usages   = usg_var,
136                 tcg_rdr_env  = emptyGlobalRdrEnv,
137                 tcg_fix_env  = emptyFixityEnv,
138                 tcg_default  = defaultDefaultTys,
139                 tcg_type_env = emptyNameEnv,
140                 tcg_ist      = mkImpTypeEnv eps hpt,
141                 tcg_inst_env = mkImpInstEnv dflags eps hpt,
142                 tcg_exports  = [],
143                 tcg_imports  = init_imports,
144                 tcg_binds    = EmptyMonoBinds,
145                 tcg_deprecs  = NoDeprecs,
146                 tcg_insts    = [],
147                 tcg_rules    = [],
148                 tcg_fords    = [] } ;
149
150              lcl_env = TcLclEnv {
151                 tcl_ctxt   = [],
152                 tcl_level  = topStage,
153                 tcl_env    = emptyNameEnv,
154                 tcl_tyvars = tvs_var,
155                 tcl_lie    = panic "initTc:LIE" } ;
156                         -- LIE only valid inside a getLIE
157              } ;
158    
159         -- OK, here's the business end!
160         maybe_res <- catch (do { res  <- runTcRn env do_this ;
161                                  return (Just res) })
162                            (\_ -> return Nothing) ;
163
164         -- Print any error messages
165         msgs <- readIORef errs_var ;
166         printErrorsAndWarnings msgs ;
167
168         -- Get final PCS and return
169         eps' <- readIORef eps_var ;
170         nc'  <- readIORef nc_var ;
171         let { pcs' = PCS { pcs_EPS = eps', pcs_nc = nc' } ;
172               final_res | errorsFound msgs = Nothing
173                         | otherwise        = maybe_res } ;
174
175         return (pcs', final_res)
176     }
177   where
178     eps = pcs_EPS pcs
179
180     init_imports = emptyImportAvails { imp_unqual = unitModuleEnv mod emptyAvailEnv }
181         -- Initialise tcg_imports with an empty set of bindings for
182         -- this module, so that if we see 'module M' in the export
183         -- list, and there are no bindings in M, we don't bleat 
184         -- "unknown module M".
185
186 defaultDefaultTys :: [Type]
187 defaultDefaultTys = [integerTy, doubleTy]
188
189 mkImpInstEnv :: DynFlags -> ExternalPackageState -> HomePackageTable -> InstEnv
190 mkImpInstEnv dflags eps hpt
191   = foldModuleEnv (add . md_insts . hm_details) 
192                   (eps_inst_env eps)
193                   hpt
194   where
195           -- We shouldn't get instance conflict errors from
196           -- the package and home type envs
197     add dfuns inst_env = WARN( not (null errs), vcat (map snd errs) ) inst_env'
198                        where
199                          (inst_env', errs) = extendInstEnv dflags inst_env dfuns
200
201 -- mkImpTypeEnv makes the imported symbol table
202 mkImpTypeEnv :: ExternalPackageState -> HomePackageTable
203              -> Name -> Maybe TyThing
204 mkImpTypeEnv pcs hpt = lookup 
205   where
206     pte = eps_PTE pcs
207     lookup name | isInternalName name = Nothing
208                 | otherwise           = lookupType hpt pte name
209 \end{code}
210
211
212 %************************************************************************
213 %*                                                                      *
214                 Simple accessors
215 %*                                                                      *
216 %************************************************************************
217
218 \begin{code}
219 getTopEnv :: TcRn m TopEnv
220 getTopEnv = do { env <- getEnv; return (env_top env) }
221
222 getGblEnv :: TcRn m TcGblEnv
223 getGblEnv = do { env <- getEnv; return (env_gbl env) }
224
225 updGblEnv :: (TcGblEnv -> TcGblEnv) -> TcRn m a -> TcRn m a
226 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) -> 
227                           env { env_gbl = upd gbl })
228
229 setGblEnv :: TcGblEnv -> TcRn m a -> TcRn m a
230 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
231
232 getLclEnv :: TcRn m m
233 getLclEnv = do { env <- getEnv; return (env_lcl env) }
234
235 updLclEnv :: (m -> m) -> TcRn m a -> TcRn m a
236 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) -> 
237                           env { env_lcl = upd lcl })
238
239 setLclEnv :: m -> TcRn m a -> TcRn n a
240 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
241 \end{code}
242
243 Command-line flags
244
245 \begin{code}
246 getDOpts :: TcRn m DynFlags
247 getDOpts = do { env <- getTopEnv; return (top_dflags env) }
248
249 doptM :: DynFlag -> TcRn m Bool
250 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
251
252 ifOptM :: DynFlag -> TcRn m () -> TcRn m ()     -- Do it flag is true
253 ifOptM flag thing_inside = do { b <- doptM flag; 
254                                 if b then thing_inside else return () }
255
256 getGhciMode :: TcRn m GhciMode
257 getGhciMode = do { env <- getTopEnv; return (top_mode env) }
258 \end{code}
259
260 \begin{code}
261 getSrcLocM :: TcRn m SrcLoc
262         -- Avoid clash with Name.getSrcLoc
263 getSrcLocM = do { env <- getEnv; return (env_loc env) }
264
265 addSrcLoc :: SrcLoc -> TcRn m a -> TcRn m a
266 addSrcLoc loc = updEnv (\env -> env { env_loc = loc })
267 \end{code}
268
269 \begin{code}
270 getEps :: TcRn m ExternalPackageState
271 getEps = do { env <- getTopEnv; readMutVar (top_eps env) }
272
273 setEps :: ExternalPackageState -> TcRn m ()
274 setEps eps = do { env <- getTopEnv; writeMutVar (top_eps env) eps }
275
276 getHpt :: TcRn m HomePackageTable
277 getHpt = do { env <- getTopEnv; return (top_hpt env) }
278
279 getModule :: TcRn m Module
280 getModule = do { env <- getGblEnv; return (tcg_mod env) }
281
282 getGlobalRdrEnv :: TcRn m GlobalRdrEnv
283 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
284
285 getImports :: TcRn m ImportAvails
286 getImports = do { env <- getGblEnv; return (tcg_imports env) }
287
288 getFixityEnv :: TcRn m FixityEnv
289 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
290
291 extendFixityEnv :: [(Name,FixitySig Name)] -> RnM a -> RnM a
292 extendFixityEnv new_bit
293   = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) -> 
294                 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})           
295
296 getDefaultTys :: TcRn m [Type]
297 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
298 \end{code}
299
300 \begin{code}
301 getUsageVar :: TcRn m (TcRef EntityUsage)
302 getUsageVar = do { env <- getGblEnv; return (tcg_usages env) }
303
304 getUsages :: TcRn m EntityUsage
305 getUsages = do { usg_var <- getUsageVar; readMutVar usg_var }
306
307 updUsages :: (EntityUsage -> EntityUsage) -> TcRn m () 
308 updUsages upd = do { usg_var <- getUsageVar ;
309                      usg <- readMutVar usg_var ;
310                      writeMutVar usg_var (upd usg) }
311 \end{code}
312
313
314 %************************************************************************
315 %*                                                                      *
316                 Error management
317 %*                                                                      *
318 %************************************************************************
319
320 \begin{code}
321 getErrsVar :: TcRn m (TcRef Messages)
322 getErrsVar = do { env <- getTopEnv; return (top_errs env) }
323
324 setErrsVar :: TcRef Messages -> TcRn m a -> TcRn m a
325 setErrsVar v = updEnv (\ env@(Env { env_top = top_env }) ->
326                          env { env_top = top_env { top_errs = v }})
327
328 addErr :: Message -> TcRn m ()
329 addErr msg = do { loc <- getSrcLocM ; addErrAt loc msg }
330
331 addErrAt :: SrcLoc -> Message -> TcRn m ()
332 addErrAt loc msg
333  = do {  errs_var <- getErrsVar ;
334          rdr_env <- getGlobalRdrEnv ;
335          let { err = addShortErrLocLine loc (unQualInScope rdr_env) msg } ;
336          (warns, errs) <- readMutVar errs_var ;
337          writeMutVar errs_var (warns, errs `snocBag` err) }
338
339 addErrs :: [(SrcLoc,Message)] -> TcRn m ()
340 addErrs msgs = mappM_ add msgs
341              where
342                add (loc,msg) = addErrAt loc msg
343
344 addWarn :: Message -> TcRn m ()
345 addWarn msg
346   = do { errs_var <- getErrsVar ;
347          loc <- getSrcLocM ;
348          rdr_env <- getGlobalRdrEnv ;
349          let { warn = addShortWarnLocLine loc (unQualInScope rdr_env) msg } ;
350          (warns, errs) <- readMutVar errs_var ;
351          writeMutVar errs_var (warns `snocBag` warn, errs) }
352
353 checkErr :: Bool -> Message -> TcRn m ()
354 -- Add the error if the bool is False
355 checkErr ok msg = checkM ok (addErr msg)
356
357 warnIf :: Bool -> Message -> TcRn m ()
358 warnIf True  msg = addWarn msg
359 warnIf False msg = return ()
360
361 addMessages :: Messages -> TcRn m ()
362 addMessages (m_warns, m_errs)
363   = do { errs_var <- getErrsVar ;
364          (warns, errs) <- readMutVar errs_var ;
365          writeMutVar errs_var (warns `unionBags` m_warns,
366                                errs  `unionBags` m_errs) }
367
368 checkGHCI :: Message -> TcRn m ()       -- Check that GHCI is on
369                                         -- otherwise add the error message
370 #ifdef GHCI 
371 checkGHCI m = returnM ()
372 #else
373 checkGHCI m = addErr m
374 #endif
375 \end{code}
376
377
378 \begin{code}
379 recoverM :: TcRn m r    -- Recovery action; do this if the main one fails
380          -> TcRn m r    -- Main action: do this first
381          -> TcRn m r
382 recoverM recover thing 
383   = do { mb_res <- tryM thing ;
384          case mb_res of
385            Left exn  -> recover
386            Right res -> returnM res }
387
388 tryTc :: TcRn m a -> TcRn m (Messages, Maybe a)
389     -- (tryTc m) executes m, and returns
390     --  Just r,  if m succeeds (returning r) and caused no errors
391     --  Nothing, if m fails, or caused errors
392     -- It also returns all the errors accumulated by m
393     --  (even in the Just case, there might be warnings)
394     --
395     -- It always succeeds (never raises an exception)
396 tryTc m 
397  = do { errs_var <- newMutVar emptyMessages ;
398         
399         mb_r <- tryM (setErrsVar errs_var m) ; 
400
401         new_errs <- readMutVar errs_var ;
402
403         return (new_errs, 
404                 case mb_r of
405                   Left exn                       -> Nothing
406                   Right r | errorsFound new_errs -> Nothing
407                           | otherwise            -> Just r) 
408    }
409
410 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
411 -- Just like tryTc, except that it ensures that the LIE
412 -- for the thing is propagated only if there are no errors
413 -- Hence it's restricted to the type-check monad
414 tryTcLIE thing_inside
415   = do { ((errs, mb_r), lie) <- getLIE (tryTc thing_inside) ;
416          ifM (isJust mb_r) (extendLIEs lie) ;
417          return (errs, mb_r) }
418
419 tryTcLIE_ :: TcM r -> TcM r -> TcM r
420 -- (tryM_ r m) tries m; if it succeeds it returns it,
421 -- otherwise it returns r.  Any error messages added by m are discarded,
422 -- whether or not m succeeds.
423 tryTcLIE_ recover main
424   = do { (_msgs, mb_res) <- tryTcLIE main ;
425          case mb_res of
426            Just res -> return res
427            Nothing  -> recover }
428
429 checkNoErrs :: TcM r -> TcM r
430 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
431 -- If m fails then (checkNoErrsTc m) fails.
432 -- If m succeeds, it checks whether m generated any errors messages
433 --      (it might have recovered internally)
434 --      If so, it fails too.
435 -- Regardless, any errors generated by m are propagated to the enclosing context.
436 checkNoErrs main
437   = do { (msgs, mb_res) <- tryTcLIE main ;
438          addMessages msgs ;
439          case mb_res of
440            Just r  -> return r
441            Nothing -> failM
442    }
443
444 ifErrsM :: TcRn m r -> TcRn m r -> TcRn m r
445 --      ifErrsM bale_out main
446 -- does 'bale_out' if there are errors in errors collection
447 -- otherwise does 'main'
448 ifErrsM bale_out normal
449  = do { errs_var <- getErrsVar ;
450         msgs <- readMutVar errs_var ;
451         if errorsFound msgs then
452            bale_out
453         else    
454            normal }
455
456 failIfErrsM :: TcRn m ()
457 -- Useful to avoid error cascades
458 failIfErrsM = ifErrsM failM (return ())
459 \end{code}
460
461 \begin{code}
462 forkM :: SDoc -> TcM a -> TcM (Maybe a)
463 -- Run thing_inside in an interleaved thread.  It gets a separate
464 --      * errs_var, and
465 --      * unique supply, 
466 -- but everything else is shared, so this is DANGEROUS.  
467 --
468 -- It returns Nothing if the computation fails
469 -- 
470 -- It's used for lazily type-checking interface
471 -- signatures, which is pretty benign
472
473 forkM doc thing_inside
474  = do { us <- newUniqueSupply ;
475         unsafeInterleaveM $
476         do { us_var <- newMutVar us ;
477              (msgs, mb_res) <- tryTcLIE (setUsVar us_var thing_inside) ;
478              case mb_res of
479                 Just r  -> return (Just r) 
480                 Nothing -> do {
481                     -- Bleat about errors in the forked thread
482                     ioToTcRn (do { printErrs (hdr_doc defaultErrStyle) ;
483                                    printErrorsAndWarnings msgs }) ;
484                     return Nothing }
485         }}
486   where
487     hdr_doc = text "forkM failed:" <+> doc
488 \end{code}
489
490
491 %************************************************************************
492 %*                                                                      *
493                 Unique supply
494 %*                                                                      *
495 %************************************************************************
496
497 \begin{code}
498 getUsVar :: TcRn m (TcRef UniqSupply)
499 getUsVar = do { env <- getTopEnv; return (top_us env) }
500
501 setUsVar :: TcRef UniqSupply -> TcRn m a -> TcRn m a
502 setUsVar v = updEnv (\ env@(Env { env_top = top_env }) ->
503                        env { env_top = top_env { top_us = v }})
504
505 newUnique :: TcRn m Unique
506 newUnique = do { us <- newUniqueSupply ; 
507                  return (uniqFromSupply us) }
508
509 newUniqueSupply :: TcRn m UniqSupply
510 newUniqueSupply
511  = do { u_var <- getUsVar ;
512         us <- readMutVar u_var ;
513         let { (us1, us2) = splitUniqSupply us } ;
514         writeMutVar u_var us1 ;
515         return us2 }
516 \end{code}
517
518
519 \begin{code}
520 getNameCache :: TcRn m NameCache
521 getNameCache = do { TopEnv { top_nc = nc_var } <- getTopEnv; 
522                     readMutVar nc_var }
523
524 setNameCache :: NameCache -> TcRn m ()
525 setNameCache nc = do { TopEnv { top_nc = nc_var } <- getTopEnv; 
526                        writeMutVar nc_var nc }
527 \end{code}
528
529
530 %************************************************************************
531 %*                                                                      *
532                 Debugging
533 %*                                                                      *
534 %************************************************************************
535
536 \begin{code}
537 traceTc, traceRn :: SDoc -> TcRn a ()
538 traceRn      = dumpOptTcRn Opt_D_dump_rn_trace
539 traceTc      = dumpOptTcRn Opt_D_dump_tc_trace
540 traceSplice  = dumpOptTcRn Opt_D_dump_splices
541 traceHiDiffs = dumpOptTcRn Opt_D_dump_hi_diffs
542
543 dumpOptTcRn :: DynFlag -> SDoc -> TcRn a ()
544 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
545
546 dumpTcRn :: SDoc -> TcRn a ()
547 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
548                     ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
549 \end{code}
550
551
552 %************************************************************************
553 %*                                                                      *
554         Context management and error message generation
555                     for the type checker
556 %*                                                                      *
557 %************************************************************************
558
559 \begin{code}
560 setErrCtxtM, addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
561 setErrCtxtM msg = updCtxt (\ msgs -> [msg])
562 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
563
564 setErrCtxt, addErrCtxt :: Message -> TcM a -> TcM a
565 setErrCtxt msg = setErrCtxtM (\env -> returnM (env, msg))
566 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
567
568 popErrCtxt :: TcM a -> TcM a
569 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
570
571 getErrCtxt :: TcM ErrCtxt
572 getErrCtxt = do { env <- getLclEnv ; return (tcl_ctxt env) }
573
574 -- Helper function for the above
575 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
576 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> 
577                            env { tcl_ctxt = upd ctxt })
578
579 getInstLoc :: InstOrigin -> TcM InstLoc
580 getInstLoc origin
581   = do { loc <- getSrcLocM ; env <- getLclEnv ;
582          return (origin, loc, (tcl_ctxt env)) }
583 \end{code}
584
585     The addErrTc functions add an error message, but do not cause failure.
586     The 'M' variants pass a TidyEnv that has already been used to
587     tidy up the message; we then use it to tidy the context messages
588
589 \begin{code}
590 addErrTc :: Message -> TcM ()
591 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
592
593 addErrsTc :: [Message] -> TcM ()
594 addErrsTc err_msgs = mappM_ addErrTc err_msgs
595
596 addErrTcM :: (TidyEnv, Message) -> TcM ()
597 addErrTcM (tidy_env, err_msg)
598   = do { ctxt <- getErrCtxt ;
599          loc  <- getSrcLocM ;
600          add_err_tcm tidy_env err_msg loc ctxt }
601
602 addInstErrTcM :: InstLoc -> (TidyEnv, Message) -> TcM ()
603 addInstErrTcM inst_loc@(_, loc, ctxt) (tidy_env, err_msg)
604   = add_err_tcm tidy_env err_msg loc full_ctxt
605   where
606     full_ctxt = (\env -> returnM (env, pprInstLoc inst_loc)) : ctxt
607 \end{code}
608
609 The failWith functions add an error message and cause failure
610
611 \begin{code}
612 failWithTc :: Message -> TcM a               -- Add an error message and fail
613 failWithTc err_msg 
614   = addErrTc err_msg >> failM
615
616 failWithTcM :: (TidyEnv, Message) -> TcM a   -- Add an error message and fail
617 failWithTcM local_and_msg
618   = addErrTcM local_and_msg >> failM
619
620 checkTc :: Bool -> Message -> TcM ()         -- Check that the boolean is true
621 checkTc True  err = returnM ()
622 checkTc False err = failWithTc err
623 \end{code}
624
625         Warnings have no 'M' variant, nor failure
626
627 \begin{code}
628 addWarnTc :: Message -> TcM ()
629 addWarnTc msg
630  = do { ctxt <- getErrCtxt ;
631         ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
632         addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
633
634 warnTc :: Bool -> Message -> TcM ()
635 warnTc warn_if_true warn_msg
636   | warn_if_true = addWarnTc warn_msg
637   | otherwise    = return ()
638 \end{code}
639
640         Helper functions
641
642 \begin{code}
643 add_err_tcm tidy_env err_msg loc ctxt
644  = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
645         addErrAt loc (vcat (err_msg : ctxt_to_use ctxt_msgs)) }
646
647 do_ctxt tidy_env []
648  = return []
649 do_ctxt tidy_env (c:cs)
650  = do { (tidy_env', m) <- c tidy_env  ;
651         ms             <- do_ctxt tidy_env' cs  ;
652         return (m:ms) }
653
654 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
655                  | otherwise          = take 3 ctxt
656 \end{code}
657
658 %************************************************************************
659 %*                                                                      *
660              Other stuff specific to type checker
661 %*                                                                      *
662 %************************************************************************
663
664 \begin{code}
665 getLIEVar :: TcM (TcRef LIE)
666 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
667
668 setLIEVar :: TcRef LIE -> TcM a -> TcM a
669 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
670
671 getLIE :: TcM a -> TcM (a, [Inst])
672 -- (getLIE m) runs m, and returns the type constraints it generates
673 getLIE thing_inside
674   = do { lie_var <- newMutVar emptyLIE ;
675          res <- updLclEnv (\ env -> env { tcl_lie = lie_var }) 
676                           thing_inside ;
677          lie <- readMutVar lie_var ;
678          return (res, lieToList lie) }
679
680 extendLIE :: Inst -> TcM ()
681 extendLIE inst
682   = do { lie_var <- getLIEVar ;
683          lie <- readMutVar lie_var ;
684          writeMutVar lie_var (inst `consLIE` lie) }
685
686 extendLIEs :: [Inst] -> TcM ()
687 extendLIEs [] 
688   = returnM ()
689 extendLIEs insts
690   = do { lie_var <- getLIEVar ;
691          lie <- readMutVar lie_var ;
692          writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
693 \end{code}
694
695
696 \begin{code}
697 getStage :: TcM Stage
698 getStage = do { env <- getLclEnv; return (tcl_level env) }
699
700 setStage :: Stage -> TcM a -> TcM a 
701 setStage s = updLclEnv (\ env -> env { tcl_level = s })
702
703 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
704 -- Set the local type envt, but do *not* disturb other fields,
705 -- notably the lie_var
706 setLclTypeEnv lcl_env thing_inside
707   = updLclEnv upd thing_inside
708   where
709     upd env = env { tcl_env = tcl_env lcl_env,
710                     tcl_tyvars = tcl_tyvars lcl_env }
711 \end{code}
712
713
714 %************************************************************************
715 %*                                                                      *
716              Stuff for the renamer's local env
717 %*                                                                      *
718 %************************************************************************
719
720 \begin{code}
721 initRn :: RnMode -> RnM a -> TcRn m a
722 initRn mode thing_inside
723  = do { env <- getGblEnv ;
724         let { lcl_env = RnLclEnv {
725                              rn_mode = mode,
726                              rn_lenv = emptyRdrEnv }} ;
727         setLclEnv lcl_env thing_inside }
728 \end{code}
729
730 \begin{code}
731 getLocalRdrEnv :: RnM LocalRdrEnv
732 getLocalRdrEnv = do { env <- getLclEnv; return (rn_lenv env) }
733
734 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
735 setLocalRdrEnv rdr_env thing_inside 
736   = updLclEnv (\env -> env {rn_lenv = rdr_env}) thing_inside
737
738 getModeRn :: RnM RnMode
739 getModeRn = do { env <- getLclEnv; return (rn_mode env) }
740 \end{code}
741