[project @ 2003-02-04 12:33:05 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         ie_var   <- newIORef (mkImpInstEnv dflags eps hpt) ;
120
121         let {
122              env = Env { env_top = top_env,
123                          env_gbl = gbl_env,
124                          env_lcl = lcl_env,
125                          env_loc = noSrcLoc } ;
126
127              top_env = TopEnv { 
128                 top_mode   = ghci_mode,
129                 top_dflags = dflags,
130                 top_eps    = eps_var,
131                 top_hpt    = hpt,
132                 top_nc     = nc_var,
133                 top_us     = us_var,
134                 top_errs   = errs_var } ;
135
136              gbl_env = TcGblEnv {
137                 tcg_mod      = mod,
138                 tcg_usages   = usg_var,
139                 tcg_rdr_env  = emptyGlobalRdrEnv,
140                 tcg_fix_env  = emptyFixityEnv,
141                 tcg_default  = defaultDefaultTys,
142                 tcg_type_env = emptyNameEnv,
143                 tcg_inst_env = ie_var,
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 --      * LIE var is set to bottom (should never be used)
480 -- but everything else is shared, so this is DANGEROUS.  
481 --
482 -- It returns Nothing if the computation fails
483 -- 
484 -- It's used for lazily type-checking interface
485 -- signatures, which is pretty benign
486
487 forkM doc thing_inside
488  = do { us <- newUniqueSupply ;
489         unsafeInterleaveM $
490         do { us_var <- newMutVar us ;
491              (msgs, mb_res) <- tryTc (setLIEVar (panic "forkM: LIE used") $
492                                       setUsVar us_var thing_inside) ;
493              case mb_res of
494                 Just r  -> return (Just r) 
495                 Nothing -> do {
496
497                     -- Bleat about errors in the forked thread, if -ddump-tc-trace is on
498                     -- Otherwise we silently discard errors. Errors can legitimately
499                     -- happen when compiling interface signatures (see tcInterfaceSigs)
500                     ifOptM Opt_D_dump_tc_trace 
501                       (ioToTcRn (do { printErrs (hdr_doc defaultErrStyle) ;
502                                       printErrorsAndWarnings msgs })) ;
503
504                     return Nothing }
505         }}
506   where
507     hdr_doc = text "forkM failed:" <+> doc
508 \end{code}
509
510
511 %************************************************************************
512 %*                                                                      *
513                 Unique supply
514 %*                                                                      *
515 %************************************************************************
516
517 \begin{code}
518 getUsVar :: TcRn m (TcRef UniqSupply)
519 getUsVar = do { env <- getTopEnv; return (top_us env) }
520
521 setUsVar :: TcRef UniqSupply -> TcRn m a -> TcRn m a
522 setUsVar v = updEnv (\ env@(Env { env_top = top_env }) ->
523                        env { env_top = top_env { top_us = v }})
524
525 newUnique :: TcRn m Unique
526 newUnique = do { us <- newUniqueSupply ; 
527                  return (uniqFromSupply us) }
528
529 newUniqueSupply :: TcRn m UniqSupply
530 newUniqueSupply
531  = do { u_var <- getUsVar ;
532         us <- readMutVar u_var ;
533         let { (us1, us2) = splitUniqSupply us } ;
534         writeMutVar u_var us1 ;
535         return us2 }
536 \end{code}
537
538
539 \begin{code}
540 getNameCache :: TcRn m NameCache
541 getNameCache = do { TopEnv { top_nc = nc_var } <- getTopEnv; 
542                     readMutVar nc_var }
543
544 setNameCache :: NameCache -> TcRn m ()
545 setNameCache nc = do { TopEnv { top_nc = nc_var } <- getTopEnv; 
546                        writeMutVar nc_var nc }
547 \end{code}
548
549
550 %************************************************************************
551 %*                                                                      *
552                 Debugging
553 %*                                                                      *
554 %************************************************************************
555
556 \begin{code}
557 traceTc, traceRn :: SDoc -> TcRn a ()
558 traceRn      = dumpOptTcRn Opt_D_dump_rn_trace
559 traceTc      = dumpOptTcRn Opt_D_dump_tc_trace
560 traceSplice  = dumpOptTcRn Opt_D_dump_splices
561 traceHiDiffs = dumpOptTcRn Opt_D_dump_hi_diffs
562
563 dumpOptTcRn :: DynFlag -> SDoc -> TcRn a ()
564 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
565
566 dumpTcRn :: SDoc -> TcRn a ()
567 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
568                     ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
569 \end{code}
570
571
572 %************************************************************************
573 %*                                                                      *
574         Context management and error message generation
575                     for the type checker
576 %*                                                                      *
577 %************************************************************************
578
579 \begin{code}
580 setErrCtxtM, addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
581 setErrCtxtM msg = updCtxt (\ msgs -> [msg])
582 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
583
584 setErrCtxt, addErrCtxt :: Message -> TcM a -> TcM a
585 setErrCtxt msg = setErrCtxtM (\env -> returnM (env, msg))
586 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
587
588 popErrCtxt :: TcM a -> TcM a
589 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
590
591 getErrCtxt :: TcM ErrCtxt
592 getErrCtxt = do { env <- getLclEnv ; return (tcl_ctxt env) }
593
594 -- Helper function for the above
595 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
596 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> 
597                            env { tcl_ctxt = upd ctxt })
598
599 getInstLoc :: InstOrigin -> TcM InstLoc
600 getInstLoc origin
601   = do { loc <- getSrcLocM ; env <- getLclEnv ;
602          return (InstLoc origin loc (tcl_ctxt env)) }
603
604 addInstCtxt :: InstLoc -> TcM a -> TcM a
605 -- Add the SrcLoc and context from the first Inst in the list
606 --      (they all have similar locations)
607 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
608   = addSrcLoc src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
609 \end{code}
610
611     The addErrTc functions add an error message, but do not cause failure.
612     The 'M' variants pass a TidyEnv that has already been used to
613     tidy up the message; we then use it to tidy the context messages
614
615 \begin{code}
616 addErrTc :: Message -> TcM ()
617 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
618
619 addErrsTc :: [Message] -> TcM ()
620 addErrsTc err_msgs = mappM_ addErrTc err_msgs
621
622 addErrTcM :: (TidyEnv, Message) -> TcM ()
623 addErrTcM (tidy_env, err_msg)
624   = do { ctxt <- getErrCtxt ;
625          loc  <- getSrcLocM ;
626          add_err_tcm tidy_env err_msg loc ctxt }
627 \end{code}
628
629 The failWith functions add an error message and cause failure
630
631 \begin{code}
632 failWithTc :: Message -> TcM a               -- Add an error message and fail
633 failWithTc err_msg 
634   = addErrTc err_msg >> failM
635
636 failWithTcM :: (TidyEnv, Message) -> TcM a   -- Add an error message and fail
637 failWithTcM local_and_msg
638   = addErrTcM local_and_msg >> failM
639
640 checkTc :: Bool -> Message -> TcM ()         -- Check that the boolean is true
641 checkTc True  err = returnM ()
642 checkTc False err = failWithTc err
643 \end{code}
644
645         Warnings have no 'M' variant, nor failure
646
647 \begin{code}
648 addWarnTc :: Message -> TcM ()
649 addWarnTc msg
650  = do { ctxt <- getErrCtxt ;
651         ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
652         addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
653
654 warnTc :: Bool -> Message -> TcM ()
655 warnTc warn_if_true warn_msg
656   | warn_if_true = addWarnTc warn_msg
657   | otherwise    = return ()
658 \end{code}
659
660         Helper functions
661
662 \begin{code}
663 add_err_tcm tidy_env err_msg loc ctxt
664  = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
665         addErrAt loc (vcat (err_msg : ctxt_to_use ctxt_msgs)) }
666
667 do_ctxt tidy_env []
668  = return []
669 do_ctxt tidy_env (c:cs)
670  = do { (tidy_env', m) <- c tidy_env  ;
671         ms             <- do_ctxt tidy_env' cs  ;
672         return (m:ms) }
673
674 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
675                  | otherwise          = take 3 ctxt
676 \end{code}
677
678 %************************************************************************
679 %*                                                                      *
680              Other stuff specific to type checker
681 %*                                                                      *
682 %************************************************************************
683
684 \begin{code}
685 getLIEVar :: TcM (TcRef LIE)
686 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
687
688 setLIEVar :: TcRef LIE -> TcM a -> TcM a
689 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
690
691 getLIE :: TcM a -> TcM (a, [Inst])
692 -- (getLIE m) runs m, and returns the type constraints it generates
693 getLIE thing_inside
694   = do { lie_var <- newMutVar emptyLIE ;
695          res <- updLclEnv (\ env -> env { tcl_lie = lie_var }) 
696                           thing_inside ;
697          lie <- readMutVar lie_var ;
698          return (res, lieToList lie) }
699
700 extendLIE :: Inst -> TcM ()
701 extendLIE inst
702   = do { lie_var <- getLIEVar ;
703          lie <- readMutVar lie_var ;
704          writeMutVar lie_var (inst `consLIE` lie) }
705
706 extendLIEs :: [Inst] -> TcM ()
707 extendLIEs [] 
708   = returnM ()
709 extendLIEs insts
710   = do { lie_var <- getLIEVar ;
711          lie <- readMutVar lie_var ;
712          writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
713 \end{code}
714
715
716 \begin{code}
717 getStage :: TcM Stage
718 getStage = do { env <- getLclEnv; return (tcl_level env) }
719
720 setStage :: Stage -> TcM a -> TcM a 
721 setStage s = updLclEnv (\ env -> env { tcl_level = s })
722
723 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
724 -- Set the local type envt, but do *not* disturb other fields,
725 -- notably the lie_var
726 setLclTypeEnv lcl_env thing_inside
727   = updLclEnv upd thing_inside
728   where
729     upd env = env { tcl_env = tcl_env lcl_env,
730                     tcl_tyvars = tcl_tyvars lcl_env }
731 \end{code}
732
733
734 %************************************************************************
735 %*                                                                      *
736              Stuff for the renamer's local env
737 %*                                                                      *
738 %************************************************************************
739
740 \begin{code}
741 initRn :: RnMode -> RnM a -> TcRn m a
742 initRn mode thing_inside
743  = do { env <- getGblEnv ;
744         let { lcl_env = RnLclEnv {
745                              rn_mode = mode,
746                              rn_lenv = emptyRdrEnv }} ;
747         setLclEnv lcl_env thing_inside }
748 \end{code}
749
750 \begin{code}
751 getLocalRdrEnv :: RnM LocalRdrEnv
752 getLocalRdrEnv = do { env <- getLclEnv; return (rn_lenv env) }
753
754 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
755 setLocalRdrEnv rdr_env thing_inside 
756   = updLclEnv (\env -> env {rn_lenv = rdr_env}) thing_inside
757
758 getModeRn :: RnM RnMode
759 getModeRn = do { env <- getLclEnv; return (rn_mode env) }
760 \end{code}
761