[project @ 2003-12-10 14:15:16 by simonmar]
[ghc-hetmet.git] / ghc / 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 import HscTypes         ( HscEnv(..), ModGuts(..), ModIface(..),
14                           TyThing, Dependencies(..), TypeEnv, emptyTypeEnv,
15                           ExternalPackageState(..), HomePackageTable,
16                           ModDetails(..), HomeModInfo(..), 
17                           Deprecs(..), FixityEnv, FixItem,
18                           GhciMode, lookupType, unQualInScope )
19 import Module           ( Module, ModuleName, unitModuleEnv, foldModuleEnv, emptyModuleEnv )
20 import RdrName          ( GlobalRdrEnv, emptyGlobalRdrEnv,      
21                           LocalRdrEnv, emptyLocalRdrEnv )
22 import Name             ( Name, isInternalName )
23 import Type             ( Type )
24 import NameEnv          ( extendNameEnvList )
25 import InstEnv          ( InstEnv, emptyInstEnv, extendInstEnv )
26
27 import VarSet           ( emptyVarSet )
28 import VarEnv           ( TidyEnv, emptyTidyEnv )
29 import ErrUtils         ( Message, Messages, emptyMessages, errorsFound, 
30                           mkErrMsg, mkWarnMsg, printErrorsAndWarnings )
31 import SrcLoc           ( mkGeneralSrcSpan, SrcSpan, Located(..) )
32 import NameEnv          ( emptyNameEnv )
33 import NameSet          ( emptyDUs, emptyNameSet )
34 import OccName          ( emptyOccEnv )
35 import Module           ( moduleName )
36 import Bag              ( emptyBag )
37 import Outputable
38 import UniqSupply       ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
39 import Unique           ( Unique )
40 import CmdLineOpts      ( DynFlags, DynFlag(..), dopt, opt_PprStyle_Debug, dopt_set )
41 import Bag              ( snocBag, unionBags )
42 import Panic            ( showException )
43  
44 import Maybe            ( isJust )
45 import IO               ( stderr )
46 import DATA_IOREF       ( newIORef, readIORef )
47 import EXCEPTION        ( Exception )
48 \end{code}
49
50
51
52 %************************************************************************
53 %*                                                                      *
54                         initTc
55 %*                                                                      *
56 %************************************************************************
57
58 \begin{code}
59 ioToTcRn :: IO r -> TcRn r
60 ioToTcRn = ioToIOEnv
61 \end{code}
62
63 \begin{code}
64 initTc :: HscEnv
65        -> Module 
66        -> TcM r
67        -> IO (Maybe r)
68                 -- Nothing => error thrown by the thing inside
69                 -- (error messages should have been printed already)
70
71 initTc hsc_env mod do_this
72  = do { errs_var     <- newIORef (emptyBag, emptyBag) ;
73         tvs_var      <- newIORef emptyVarSet ;
74         type_env_var <- newIORef emptyNameEnv ;
75         dfuns_var    <- newIORef emptyNameSet ;
76
77         let {
78              gbl_env = TcGblEnv {
79                 tcg_mod      = mod,
80                 tcg_rdr_env  = emptyGlobalRdrEnv,
81                 tcg_fix_env  = emptyNameEnv,
82                 tcg_default  = Nothing,
83                 tcg_type_env = emptyNameEnv,
84                 tcg_type_env_var = type_env_var,
85                 tcg_inst_env  = mkImpInstEnv hsc_env,
86                 tcg_inst_uses = dfuns_var,
87                 tcg_exports  = [],
88                 tcg_imports  = init_imports,
89                 tcg_dus      = emptyDUs,
90                 tcg_binds    = emptyBag,
91                 tcg_deprecs  = NoDeprecs,
92                 tcg_insts    = [],
93                 tcg_rules    = [],
94                 tcg_fords    = [],
95                 tcg_keep     = emptyNameSet
96              } ;
97              lcl_env = TcLclEnv {
98                 tcl_errs       = errs_var,
99                 tcl_loc        = mkGeneralSrcSpan FSLIT("Top level of module"),
100                 tcl_ctxt       = [],
101                 tcl_rdr        = emptyLocalRdrEnv,
102                 tcl_th_ctxt    = topStage,
103                 tcl_arrow_ctxt = topArrowCtxt,
104                 tcl_env        = emptyNameEnv,
105                 tcl_tyvars     = tvs_var,
106                 tcl_lie        = panic "initTc:LIE"     -- LIE only valid inside a getLIE
107              } ;
108         } ;
109    
110         -- OK, here's the business end!
111         maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
112                              do { r <- tryM do_this 
113                                 ; case r of
114                                     Right res -> return (Just res)
115                                     Left _    -> return Nothing } ;
116
117         -- Print any error messages
118         msgs <- readIORef errs_var ;
119         printErrorsAndWarnings msgs ;
120
121         let { dflags = hsc_dflags hsc_env
122             ; final_res | errorsFound dflags msgs = Nothing
123                         | otherwise               = maybe_res } ;
124
125         return final_res
126     }
127   where
128     init_imports = emptyImportAvails { imp_qual = unitModuleEnv mod emptyAvailEnv }
129         -- Initialise tcg_imports with an empty set of bindings for
130         -- this module, so that if we see 'module M' in the export
131         -- list, and there are no bindings in M, we don't bleat 
132         -- "unknown module M".
133
134 mkImpInstEnv :: HscEnv -> InstEnv
135 -- At the moment we (wrongly) build an instance environment from all the
136 -- home-package modules we have already compiled.
137 -- We should really only get instances from modules below us in the 
138 -- module import tree.
139 mkImpInstEnv (HscEnv {hsc_dflags = dflags, hsc_HPT = hpt})
140   = foldModuleEnv (add . md_insts . hm_details) emptyInstEnv hpt
141   where
142     add dfuns inst_env = foldl extendInstEnv inst_env dfuns
143
144 -- mkImpTypeEnv makes the imported symbol table
145 mkImpTypeEnv :: ExternalPackageState -> HomePackageTable
146              -> Name -> Maybe TyThing
147 mkImpTypeEnv pcs hpt = lookup 
148   where
149     pte = eps_PTE pcs
150     lookup name | isInternalName name = Nothing
151                 | otherwise           = lookupType hpt pte name
152 \end{code}
153
154
155 %************************************************************************
156 %*                                                                      *
157                 Initialisation
158 %*                                                                      *
159 %************************************************************************
160
161
162 \begin{code}
163 initTcRnIf :: Char              -- Tag for unique supply
164            -> HscEnv
165            -> gbl -> lcl 
166            -> TcRnIf gbl lcl a 
167            -> IO a
168 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
169    = do { us     <- mkSplitUniqSupply uniq_tag ;
170         ; us_var <- newIORef us ;
171
172         ; let { env = Env { env_top = hsc_env,
173                             env_us  = us_var,
174                             env_gbl = gbl_env,
175                             env_lcl = lcl_env } }
176
177         ; runIOEnv env thing_inside
178         }
179 \end{code}
180
181 %************************************************************************
182 %*                                                                      *
183                 Simple accessors
184 %*                                                                      *
185 %************************************************************************
186
187 \begin{code}
188 getTopEnv :: TcRnIf gbl lcl HscEnv
189 getTopEnv = do { env <- getEnv; return (env_top env) }
190
191 getGblEnv :: TcRnIf gbl lcl gbl
192 getGblEnv = do { env <- getEnv; return (env_gbl env) }
193
194 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
195 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) -> 
196                           env { env_gbl = upd gbl })
197
198 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
199 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
200
201 getLclEnv :: TcRnIf gbl lcl lcl
202 getLclEnv = do { env <- getEnv; return (env_lcl env) }
203
204 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
205 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) -> 
206                           env { env_lcl = upd lcl })
207
208 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
209 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
210
211 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
212 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
213
214 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
215 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
216 \end{code}
217
218
219 Command-line flags
220
221 \begin{code}
222 getDOpts :: TcRnIf gbl lcl DynFlags
223 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
224
225 doptM :: DynFlag -> TcRnIf gbl lcl Bool
226 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
227
228 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
229 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
230                          env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
231
232 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()     -- Do it flag is true
233 ifOptM flag thing_inside = do { b <- doptM flag; 
234                                 if b then thing_inside else return () }
235
236 getGhciMode :: TcRnIf gbl lcl GhciMode
237 getGhciMode = do { env <- getTopEnv; return (hsc_mode env) }
238 \end{code}
239
240 \begin{code}
241 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
242 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
243
244 getEps :: TcRnIf gbl lcl ExternalPackageState
245 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
246
247 setEps :: ExternalPackageState -> TcRnIf gbl lcl ()
248 setEps eps = do { env <- getTopEnv; writeMutVar (hsc_EPS env) eps }
249
250 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
251           -> TcRnIf gbl lcl a
252 updateEps upd_fn = do   { eps_var <- getEpsVar
253                         ; eps <- readMutVar eps_var
254                         ; let { (eps', val) = upd_fn eps }
255                         ; writeMutVar eps_var eps'
256                         ; return val }
257
258 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
259            -> TcRnIf gbl lcl ()
260 updateEps_ upd_fn = do  { eps_var <- getEpsVar
261                         ; updMutVar eps_var upd_fn }
262
263 getHpt :: TcRnIf gbl lcl HomePackageTable
264 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
265 \end{code}
266
267 %************************************************************************
268 %*                                                                      *
269                 Unique supply
270 %*                                                                      *
271 %************************************************************************
272
273 \begin{code}
274 newUnique :: TcRnIf gbl lcl Unique
275 newUnique = do { us <- newUniqueSupply ; 
276                  return (uniqFromSupply us) }
277
278 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
279 newUniqueSupply
280  = do { env <- getEnv ;
281         let { u_var = env_us env } ;
282         us <- readMutVar u_var ;
283         let { (us1, us2) = splitUniqSupply us } ;
284         writeMutVar u_var us1 ;
285         return us2 }
286 \end{code}
287
288
289 %************************************************************************
290 %*                                                                      *
291                 Debugging
292 %*                                                                      *
293 %************************************************************************
294
295 \begin{code}
296 traceTc, traceRn :: SDoc -> TcRn ()
297 traceRn      = dumpOptTcRn Opt_D_dump_rn_trace
298 traceTc      = dumpOptTcRn Opt_D_dump_tc_trace
299 traceSplice  = dumpOptTcRn Opt_D_dump_splices
300
301
302 traceIf :: SDoc -> TcRnIf m n ()        
303 traceIf      = dumpOptIf Opt_D_dump_if_trace
304 traceHiDiffs = dumpOptIf Opt_D_dump_hi_diffs
305
306
307 dumpOptIf :: DynFlag -> SDoc -> TcRnIf m n ()  -- No RdrEnv available, so qualify everything
308 dumpOptIf flag doc = ifOptM flag $
309                      ioToIOEnv (printForUser stderr alwaysQualify doc)
310
311 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
312 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
313
314 dumpTcRn :: SDoc -> TcRn ()
315 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
316                     ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
317 \end{code}
318
319
320 %************************************************************************
321 %*                                                                      *
322                 Typechecker global environment
323 %*                                                                      *
324 %************************************************************************
325
326 \begin{code}
327 getModule :: TcRn Module
328 getModule = do { env <- getGblEnv; return (tcg_mod env) }
329
330 getGlobalRdrEnv :: TcRn GlobalRdrEnv
331 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
332
333 getImports :: TcRn ImportAvails
334 getImports = do { env <- getGblEnv; return (tcg_imports env) }
335
336 getFixityEnv :: TcRn FixityEnv
337 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
338
339 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
340 extendFixityEnv new_bit
341   = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) -> 
342                 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})           
343
344 getDefaultTys :: TcRn (Maybe [Type])
345 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
346 \end{code}
347
348 %************************************************************************
349 %*                                                                      *
350                 Error management
351 %*                                                                      *
352 %************************************************************************
353
354 \begin{code}
355 getSrcSpanM :: TcRn SrcSpan
356         -- Avoid clash with Name.getSrcLoc
357 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
358
359 addSrcSpan :: SrcSpan -> TcRn a -> TcRn a
360 addSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc })
361
362 addLocM :: (a -> TcM b) -> Located a -> TcM b
363 addLocM fn (L loc a) = addSrcSpan loc $ fn a
364
365 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
366 wrapLocM fn (L loc a) = addSrcSpan loc $ do b <- fn a; return (L loc b)
367
368 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
369 wrapLocFstM fn (L loc a) =
370   addSrcSpan loc $ do
371     (b,c) <- fn a
372     return (L loc b, c)
373
374 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
375 wrapLocSndM fn (L loc a) =
376   addSrcSpan loc $ do
377     (b,c) <- fn a
378     return (b, L loc c)
379 \end{code}
380
381
382 \begin{code}
383 getErrsVar :: TcRn (TcRef Messages)
384 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
385
386 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
387 setErrsVar v = updLclEnv (\ env -> env { tcl_errs =  v })
388
389 addErr :: Message -> TcRn ()
390 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
391
392 addLocErr :: Located e -> (e -> Message) -> TcRn ()
393 addLocErr (L loc e) fn = addErrAt loc (fn e)
394
395 addErrAt :: SrcSpan -> Message -> TcRn ()
396 addErrAt loc msg
397  = do {  errs_var <- getErrsVar ;
398          rdr_env <- getGlobalRdrEnv ;
399          let { err = mkErrMsg loc (unQualInScope rdr_env) msg } ;
400          (warns, errs) <- readMutVar errs_var ;
401          writeMutVar errs_var (warns, errs `snocBag` err) }
402
403 addErrs :: [(SrcSpan,Message)] -> TcRn ()
404 addErrs msgs = mappM_ add msgs
405              where
406                add (loc,msg) = addErrAt loc msg
407
408 addReport :: Message -> TcRn ()
409 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
410
411 addReportAt :: SrcSpan -> Message -> TcRn ()
412 addReportAt loc msg
413   = do { errs_var <- getErrsVar ;
414          rdr_env <- getGlobalRdrEnv ;
415          let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
416          (warns, errs) <- readMutVar errs_var ;
417          writeMutVar errs_var (warns `snocBag` warn, errs) }
418
419 addWarn :: Message -> TcRn ()
420 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
421
422 addWarnAt :: SrcSpan -> Message -> TcRn ()
423 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
424
425 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
426 addLocWarn (L loc e) fn = addReportAt loc (fn e)
427
428 checkErr :: Bool -> Message -> TcRn ()
429 -- Add the error if the bool is False
430 checkErr ok msg = checkM ok (addErr msg)
431
432 warnIf :: Bool -> Message -> TcRn ()
433 warnIf True  msg = addWarn msg
434 warnIf False msg = return ()
435
436 addMessages :: Messages -> TcRn ()
437 addMessages (m_warns, m_errs)
438   = do { errs_var <- getErrsVar ;
439          (warns, errs) <- readMutVar errs_var ;
440          writeMutVar errs_var (warns `unionBags` m_warns,
441                                errs  `unionBags` m_errs) }
442
443 discardWarnings :: TcRn a -> TcRn a
444 -- Ignore warnings inside the thing inside;
445 -- used to ignore-unused-variable warnings inside derived code
446 -- With -dppr-debug, the effects is switched off, so you can still see
447 -- what warnings derived code would give
448 discardWarnings thing_inside
449   | opt_PprStyle_Debug = thing_inside
450   | otherwise
451   = do  { errs_var <- newMutVar emptyMessages
452         ; result <- setErrsVar errs_var thing_inside
453         ; (_warns, errs) <- readMutVar errs_var
454         ; addMessages (emptyBag, errs)
455         ; return result }
456 \end{code}
457
458
459 \begin{code}
460 recoverM :: TcRn r      -- Recovery action; do this if the main one fails
461          -> TcRn r      -- Main action: do this first
462          -> TcRn r
463 recoverM recover thing 
464   = do { mb_res <- try_m thing ;
465          case mb_res of
466            Left exn  -> recover
467            Right res -> returnM res }
468
469 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
470     -- (tryTc m) executes m, and returns
471     --  Just r,  if m succeeds (returning r) and caused no errors
472     --  Nothing, if m fails, or caused errors
473     -- It also returns all the errors accumulated by m
474     --  (even in the Just case, there might be warnings)
475     --
476     -- It always succeeds (never raises an exception)
477 tryTc m 
478  = do { errs_var <- newMutVar emptyMessages ;
479         
480         mb_r <- try_m (setErrsVar errs_var m) ; 
481
482         new_errs <- readMutVar errs_var ;
483
484         dflags <- getDOpts ;
485
486         return (new_errs, 
487                 case mb_r of
488                   Left exn -> Nothing
489                   Right r | errorsFound dflags new_errs -> Nothing
490                           | otherwise                   -> Just r) 
491    }
492
493 try_m :: TcRn r -> TcRn (Either Exception r)
494 -- Does try_m, with a debug-trace on failure
495 try_m thing 
496   = do { mb_r <- tryM thing ;
497          case mb_r of 
498              Left exn -> do { traceTc (exn_msg exn); return mb_r }
499              Right r  -> return mb_r }
500   where
501     exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
502
503 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
504 -- Just like tryTc, except that it ensures that the LIE
505 -- for the thing is propagated only if there are no errors
506 -- Hence it's restricted to the type-check monad
507 tryTcLIE thing_inside
508   = do { ((errs, mb_r), lie) <- getLIE (tryTc thing_inside) ;
509          ifM (isJust mb_r) (extendLIEs lie) ;
510          return (errs, mb_r) }
511
512 tryTcLIE_ :: TcM r -> TcM r -> TcM r
513 -- (tryTcLIE_ r m) tries m; if it succeeds it returns it,
514 -- otherwise it returns r.  Any error messages added by m are discarded,
515 -- whether or not m succeeds.
516 tryTcLIE_ recover main
517   = do { (_msgs, mb_res) <- tryTcLIE main ;
518          case mb_res of
519            Just res -> return res
520            Nothing  -> recover }
521
522 checkNoErrs :: TcM r -> TcM r
523 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
524 -- If m fails then (checkNoErrsTc m) fails.
525 -- If m succeeds, it checks whether m generated any errors messages
526 --      (it might have recovered internally)
527 --      If so, it fails too.
528 -- Regardless, any errors generated by m are propagated to the enclosing context.
529 checkNoErrs main
530   = do { (msgs, mb_res) <- tryTcLIE main ;
531          addMessages msgs ;
532          case mb_res of
533            Just r  -> return r
534            Nothing -> failM
535    }
536
537 ifErrsM :: TcRn r -> TcRn r -> TcRn r
538 --      ifErrsM bale_out main
539 -- does 'bale_out' if there are errors in errors collection
540 -- otherwise does 'main'
541 ifErrsM bale_out normal
542  = do { errs_var <- getErrsVar ;
543         msgs <- readMutVar errs_var ;
544         dflags <- getDOpts ;
545         if errorsFound dflags msgs then
546            bale_out
547         else    
548            normal }
549
550 failIfErrsM :: TcRn ()
551 -- Useful to avoid error cascades
552 failIfErrsM = ifErrsM failM (return ())
553 \end{code}
554
555
556 %************************************************************************
557 %*                                                                      *
558         Context management and error message generation
559                     for the type checker
560 %*                                                                      *
561 %************************************************************************
562
563 \begin{code}
564 setErrCtxtM, addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
565 setErrCtxtM msg = updCtxt (\ msgs -> [msg])
566 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
567
568 setErrCtxt, addErrCtxt :: Message -> TcM a -> TcM a
569 setErrCtxt msg = setErrCtxtM (\env -> returnM (env, msg))
570 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
571
572 popErrCtxt :: TcM a -> TcM a
573 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
574
575 getErrCtxt :: TcM ErrCtxt
576 getErrCtxt = do { env <- getLclEnv ; return (tcl_ctxt env) }
577
578 -- Helper function for the above
579 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
580 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> 
581                            env { tcl_ctxt = upd ctxt })
582
583 getInstLoc :: InstOrigin -> TcM InstLoc
584 getInstLoc origin
585   = do { loc <- getSrcSpanM ; env <- getLclEnv ;
586          return (InstLoc origin loc (tcl_ctxt env)) }
587
588 addInstCtxt :: InstLoc -> TcM a -> TcM a
589 -- Add the SrcSpan and context from the first Inst in the list
590 --      (they all have similar locations)
591 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
592   = addSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
593 \end{code}
594
595     The addErrTc functions add an error message, but do not cause failure.
596     The 'M' variants pass a TidyEnv that has already been used to
597     tidy up the message; we then use it to tidy the context messages
598
599 \begin{code}
600 addErrTc :: Message -> TcM ()
601 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
602
603 addErrsTc :: [Message] -> TcM ()
604 addErrsTc err_msgs = mappM_ addErrTc err_msgs
605
606 addErrTcM :: (TidyEnv, Message) -> TcM ()
607 addErrTcM (tidy_env, err_msg)
608   = do { ctxt <- getErrCtxt ;
609          loc  <- getSrcSpanM ;
610          add_err_tcm tidy_env err_msg loc ctxt }
611 \end{code}
612
613 The failWith functions add an error message and cause failure
614
615 \begin{code}
616 failWithTc :: Message -> TcM a               -- Add an error message and fail
617 failWithTc err_msg 
618   = addErrTc err_msg >> failM
619
620 failWithTcM :: (TidyEnv, Message) -> TcM a   -- Add an error message and fail
621 failWithTcM local_and_msg
622   = addErrTcM local_and_msg >> failM
623
624 checkTc :: Bool -> Message -> TcM ()         -- Check that the boolean is true
625 checkTc True  err = returnM ()
626 checkTc False err = failWithTc err
627 \end{code}
628
629         Warnings have no 'M' variant, nor failure
630
631 \begin{code}
632 addWarnTc :: Message -> TcM ()
633 addWarnTc msg
634  = do { ctxt <- getErrCtxt ;
635         ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
636         addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
637
638 warnTc :: Bool -> Message -> TcM ()
639 warnTc warn_if_true warn_msg
640   | warn_if_true = addWarnTc warn_msg
641   | otherwise    = return ()
642 \end{code}
643
644         Helper functions
645
646 \begin{code}
647 add_err_tcm tidy_env err_msg loc ctxt
648  = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
649         addErrAt loc (vcat (err_msg : ctxt_to_use ctxt_msgs)) }
650
651 do_ctxt tidy_env []
652  = return []
653 do_ctxt tidy_env (c:cs)
654  = do { (tidy_env', m) <- c tidy_env  ;
655         ms             <- do_ctxt tidy_env' cs  ;
656         return (m:ms) }
657
658 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
659                  | otherwise          = take 3 ctxt
660 \end{code}
661
662 %************************************************************************
663 %*                                                                      *
664              Type constraints (the so-called LIE)
665 %*                                                                      *
666 %************************************************************************
667
668 \begin{code}
669 getLIEVar :: TcM (TcRef LIE)
670 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
671
672 setLIEVar :: TcRef LIE -> TcM a -> TcM a
673 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
674
675 getLIE :: TcM a -> TcM (a, [Inst])
676 -- (getLIE m) runs m, and returns the type constraints it generates
677 getLIE thing_inside
678   = do { lie_var <- newMutVar emptyLIE ;
679          res <- updLclEnv (\ env -> env { tcl_lie = lie_var }) 
680                           thing_inside ;
681          lie <- readMutVar lie_var ;
682          return (res, lieToList lie) }
683
684 extendLIE :: Inst -> TcM ()
685 extendLIE inst
686   = do { lie_var <- getLIEVar ;
687          lie <- readMutVar lie_var ;
688          writeMutVar lie_var (inst `consLIE` lie) }
689
690 extendLIEs :: [Inst] -> TcM ()
691 extendLIEs [] 
692   = returnM ()
693 extendLIEs insts
694   = do { lie_var <- getLIEVar ;
695          lie <- readMutVar lie_var ;
696          writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
697 \end{code}
698
699 \begin{code}
700 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
701 -- Set the local type envt, but do *not* disturb other fields,
702 -- notably the lie_var
703 setLclTypeEnv lcl_env thing_inside
704   = updLclEnv upd thing_inside
705   where
706     upd env = env { tcl_env = tcl_env lcl_env,
707                     tcl_tyvars = tcl_tyvars lcl_env }
708 \end{code}
709
710
711 %************************************************************************
712 %*                                                                      *
713              Template Haskell context
714 %*                                                                      *
715 %************************************************************************
716
717 \begin{code}
718 getStage :: TcM ThStage
719 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
720
721 setStage :: ThStage -> TcM a -> TcM a 
722 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
723 \end{code}
724
725
726 %************************************************************************
727 %*                                                                      *
728              Arrow context
729 %*                                                                      *
730 %************************************************************************
731
732 \begin{code}
733 popArrowBinders :: TcM a -> TcM a       -- Move to the left of a (-<); see comments in TcRnTypes
734 popArrowBinders 
735   = updLclEnv (\ env -> env { tcl_arrow_ctxt = pop (tcl_arrow_ctxt env)  })
736   where
737     pop (ArrCtxt {proc_level = curr_lvl, proc_banned = banned})
738         = ASSERT( not (curr_lvl `elem` banned) )
739           ArrCtxt {proc_level = curr_lvl, proc_banned = curr_lvl : banned}
740
741 getBannedProcLevels :: TcM [ProcLevel]
742   = do { env <- getLclEnv; return (proc_banned (tcl_arrow_ctxt env)) }
743
744 incProcLevel :: TcM a -> TcM a
745 incProcLevel 
746   = updLclEnv (\ env -> env { tcl_arrow_ctxt = inc (tcl_arrow_ctxt env) })
747   where
748     inc ctxt = ctxt { proc_level = proc_level ctxt + 1 }
749 \end{code}
750
751
752 %************************************************************************
753 %*                                                                      *
754              Stuff for the renamer's local env
755 %*                                                                      *
756 %************************************************************************
757
758 \begin{code}
759 getLocalRdrEnv :: RnM LocalRdrEnv
760 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
761
762 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
763 setLocalRdrEnv rdr_env thing_inside 
764   = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
765 \end{code}
766
767
768 %************************************************************************
769 %*                                                                      *
770              Stuff for interface decls
771 %*                                                                      *
772 %************************************************************************
773
774 \begin{code}
775 initIfaceTcRn :: IfG a -> TcRn a
776 initIfaceTcRn thing_inside
777   = do  { tcg_env <- getGblEnv 
778         ; let { if_env = IfGblEnv { 
779                         if_rec_types = Just (tcg_mod tcg_env, get_type_env),
780                         if_is_boot   = imp_dep_mods (tcg_imports tcg_env) }
781               ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
782         ; setEnvs (if_env, ()) thing_inside }
783
784 initIfaceExtCore :: IfL a -> TcRn a
785 initIfaceExtCore thing_inside
786   = do  { tcg_env <- getGblEnv 
787         ; let { mod = tcg_mod tcg_env
788               ; if_env = IfGblEnv { 
789                         if_rec_types = Just (mod, return (tcg_type_env tcg_env)), 
790                         if_is_boot   = imp_dep_mods (tcg_imports tcg_env) }
791               ; if_lenv = IfLclEnv { if_mod     = moduleName mod,
792                                      if_tv_env  = emptyOccEnv,
793                                      if_id_env  = emptyOccEnv }
794           }
795         ; setEnvs (if_env, if_lenv) thing_inside }
796
797 initIfaceCheck :: HscEnv -> IfG a -> IO a
798 -- Used when checking the up-to-date-ness of the old Iface
799 -- Initialise the environment with no useful info at all
800 initIfaceCheck hsc_env do_this
801  = do   { let { gbl_env = IfGblEnv { if_is_boot   = emptyModuleEnv,
802                                      if_rec_types = Nothing } ;
803            }
804         ; initTcRnIf 'i' hsc_env gbl_env () do_this
805     }
806
807 initIfaceTc :: HscEnv -> ModIface 
808             -> (TcRef TypeEnv -> IfL a) -> IO a
809 -- Used when type-checking checking an up-to-date interface file
810 -- No type envt from the current module, but we do know the module dependencies
811 initIfaceTc hsc_env iface do_this
812  = do   { tc_env_var <- newIORef emptyTypeEnv
813         ; let { gbl_env = IfGblEnv { if_is_boot   = mkModDeps (dep_mods (mi_deps iface)),
814                                      if_rec_types = Just (mod, readMutVar tc_env_var) } ;
815               ; if_lenv = IfLclEnv { if_mod     = moduleName mod,
816                                      if_tv_env  = emptyOccEnv,
817                                      if_id_env  = emptyOccEnv }
818            }
819         ; initTcRnIf 'i' hsc_env gbl_env if_lenv (do_this tc_env_var)
820     }
821   where
822     mod = mi_module iface
823
824 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
825 -- Used when sucking in new Rules in SimplCore
826 -- We have available the type envt of the module being compiled, and we must use it
827 initIfaceRules hsc_env guts do_this
828  = do   { let {
829              is_boot = mkModDeps (dep_mods (mg_deps guts))
830                         -- Urgh!  But we do somehow need to get the info
831                         -- on whether (for this particular compilation) we should
832                         -- import a hi-boot file or not.
833            ; type_info = (mg_module guts, return (mg_types guts))
834            ; gbl_env = IfGblEnv { if_is_boot   = is_boot,
835                                   if_rec_types = Just type_info } ;
836            }
837
838         -- Run the thing; any exceptions just bubble out from here
839         ; initTcRnIf 'i' hsc_env gbl_env () do_this
840     }
841
842 initIfaceLcl :: ModuleName -> IfL a -> IfM lcl a
843 initIfaceLcl mod thing_inside 
844   = setLclEnv (IfLclEnv { if_mod      = mod,
845                            if_tv_env  = emptyOccEnv,
846                            if_id_env  = emptyOccEnv })
847               thing_inside
848
849
850 --------------------
851 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
852 -- Run thing_inside in an interleaved thread.  
853 -- It shares everything with the parent thread, so this is DANGEROUS.  
854 --
855 -- It returns Nothing if the computation fails
856 -- 
857 -- It's used for lazily type-checking interface
858 -- signatures, which is pretty benign
859
860 forkM_maybe doc thing_inside
861  = do { unsafeInterleaveM $
862         do { traceIf (text "Starting fork {" <+> doc)
863            ; mb_res <- tryM thing_inside ;
864              case mb_res of
865                 Right r  -> do  { traceIf (text "} ending fork" <+> doc)
866                                 ; return (Just r) }
867                 Left exn -> do {
868
869                     -- Bleat about errors in the forked thread, if -ddump-if-trace is on
870                     -- Otherwise we silently discard errors. Errors can legitimately
871                     -- happen when compiling interface signatures (see tcInterfaceSigs)
872                       ifOptM Opt_D_dump_if_trace 
873                              (print_errs (hang (text "forkM failed:" <+> doc)
874                                              4 (text (show exn))))
875
876                     ; traceIf (text "} ending fork (badly)" <+> doc)
877                     ; return Nothing }
878         }}
879   where
880     print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
881
882 forkM :: SDoc -> IfL a -> IfL a
883 forkM doc thing_inside
884  = do   { mb_res <- forkM_maybe doc thing_inside
885         ; return (case mb_res of 
886                         Nothing -> pprPanic "forkM" doc
887                         Just r  -> r) }
888 \end{code}