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