[project @ 2004-01-23 13:55:28 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                           mkLocMessage, mkLongErrMsg )
32 import SrcLoc           ( mkGeneralSrcSpan, SrcSpan, Located(..) )
33 import NameEnv          ( emptyNameEnv )
34 import NameSet          ( emptyDUs, emptyNameSet )
35 import OccName          ( emptyOccEnv )
36 import Module           ( moduleName )
37 import Bag              ( emptyBag )
38 import Outputable
39 import UniqSupply       ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
40 import Unique           ( Unique )
41 import CmdLineOpts      ( DynFlags, DynFlag(..), dopt, opt_PprStyle_Debug, dopt_set )
42 import Bag              ( snocBag, unionBags )
43 import Panic            ( showException )
44  
45 import Maybe            ( isJust )
46 import IO               ( stderr )
47 import DATA_IOREF       ( newIORef, readIORef )
48 import EXCEPTION        ( Exception )
49 \end{code}
50
51
52
53 %************************************************************************
54 %*                                                                      *
55                         initTc
56 %*                                                                      *
57 %************************************************************************
58
59 \begin{code}
60 ioToTcRn :: IO r -> TcRn r
61 ioToTcRn = ioToIOEnv
62 \end{code}
63
64 \begin{code}
65 initTc :: HscEnv
66        -> Module 
67        -> TcM r
68        -> IO (Messages, Maybe r)
69                 -- Nothing => error thrown by the thing inside
70                 -- (error messages should have been printed already)
71
72 initTc hsc_env mod do_this
73  = do { errs_var     <- newIORef (emptyBag, emptyBag) ;
74         tvs_var      <- newIORef emptyVarSet ;
75         type_env_var <- newIORef emptyNameEnv ;
76         dfuns_var    <- newIORef emptyNameSet ;
77
78         let {
79              gbl_env = TcGblEnv {
80                 tcg_mod      = mod,
81                 tcg_rdr_env  = emptyGlobalRdrEnv,
82                 tcg_fix_env  = emptyNameEnv,
83                 tcg_default  = Nothing,
84                 tcg_type_env = emptyNameEnv,
85                 tcg_type_env_var = type_env_var,
86                 tcg_inst_env  = mkImpInstEnv hsc_env,
87                 tcg_inst_uses = dfuns_var,
88                 tcg_exports  = emptyNameSet,
89                 tcg_imports  = init_imports,
90                 tcg_dus      = emptyDUs,
91                 tcg_binds    = emptyBag,
92                 tcg_deprecs  = NoDeprecs,
93                 tcg_insts    = [],
94                 tcg_rules    = [],
95                 tcg_fords    = [],
96                 tcg_keep     = emptyNameSet
97              } ;
98              lcl_env = TcLclEnv {
99                 tcl_errs       = errs_var,
100                 tcl_loc        = mkGeneralSrcSpan FSLIT("Top level of module"),
101                 tcl_ctxt       = [],
102                 tcl_rdr        = emptyLocalRdrEnv,
103                 tcl_th_ctxt    = topStage,
104                 tcl_arrow_ctxt = topArrowCtxt,
105                 tcl_env        = emptyNameEnv,
106                 tcl_tyvars     = tvs_var,
107                 tcl_lie        = panic "initTc:LIE"     -- LIE only valid inside a getLIE
108              } ;
109         } ;
110    
111         -- OK, here's the business end!
112         maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
113                              do { r <- tryM do_this 
114                                 ; case r of
115                                     Right res -> return (Just res)
116                                     Left _    -> return Nothing } ;
117
118         -- Collect any error messages
119         msgs <- readIORef errs_var ;
120
121         let { dflags = hsc_dflags hsc_env
122             ; final_res | errorsFound dflags msgs = Nothing
123                         | otherwise               = maybe_res } ;
124
125         return (msgs, 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 $ do
313                         { ctxt <- getErrCtxt
314                         ; loc  <- getSrcSpanM
315                         ; ctxt_msgs <- do_ctxt emptyTidyEnv ctxt 
316                         ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
317                         ; dumpTcRn real_doc }
318
319 dumpTcRn :: SDoc -> TcRn ()
320 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
321                     ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
322 \end{code}
323
324
325 %************************************************************************
326 %*                                                                      *
327                 Typechecker global environment
328 %*                                                                      *
329 %************************************************************************
330
331 \begin{code}
332 getModule :: TcRn Module
333 getModule = do { env <- getGblEnv; return (tcg_mod env) }
334
335 getGlobalRdrEnv :: TcRn GlobalRdrEnv
336 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
337
338 getImports :: TcRn ImportAvails
339 getImports = do { env <- getGblEnv; return (tcg_imports env) }
340
341 getFixityEnv :: TcRn FixityEnv
342 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
343
344 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
345 extendFixityEnv new_bit
346   = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) -> 
347                 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})           
348
349 getDefaultTys :: TcRn (Maybe [Type])
350 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
351 \end{code}
352
353 %************************************************************************
354 %*                                                                      *
355                 Error management
356 %*                                                                      *
357 %************************************************************************
358
359 \begin{code}
360 getSrcSpanM :: TcRn SrcSpan
361         -- Avoid clash with Name.getSrcLoc
362 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
363
364 addSrcSpan :: SrcSpan -> TcRn a -> TcRn a
365 addSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc })
366
367 addLocM :: (a -> TcM b) -> Located a -> TcM b
368 addLocM fn (L loc a) = addSrcSpan loc $ fn a
369
370 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
371 wrapLocM fn (L loc a) = addSrcSpan loc $ do b <- fn a; return (L loc b)
372
373 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
374 wrapLocFstM fn (L loc a) =
375   addSrcSpan loc $ do
376     (b,c) <- fn a
377     return (L loc b, c)
378
379 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
380 wrapLocSndM fn (L loc a) =
381   addSrcSpan loc $ do
382     (b,c) <- fn a
383     return (b, L loc c)
384 \end{code}
385
386
387 \begin{code}
388 getErrsVar :: TcRn (TcRef Messages)
389 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
390
391 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
392 setErrsVar v = updLclEnv (\ env -> env { tcl_errs =  v })
393
394 addErr :: Message -> TcRn ()
395 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
396
397 addLocErr :: Located e -> (e -> Message) -> TcRn ()
398 addLocErr (L loc e) fn = addErrAt loc (fn e)
399
400 addErrAt :: SrcSpan -> Message -> TcRn ()
401 addErrAt loc msg = addLongErrAt loc msg empty
402
403 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
404 addLongErrAt loc msg extra
405  = do {  errs_var <- getErrsVar ;
406          rdr_env <- getGlobalRdrEnv ;
407          let { err = mkLongErrMsg loc (unQualInScope rdr_env) msg extra } ;
408          (warns, errs) <- readMutVar errs_var ;
409          writeMutVar errs_var (warns, errs `snocBag` err) }
410
411 addErrs :: [(SrcSpan,Message)] -> TcRn ()
412 addErrs msgs = mappM_ add msgs
413              where
414                add (loc,msg) = addErrAt loc msg
415
416 addReport :: Message -> TcRn ()
417 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
418
419 addReportAt :: SrcSpan -> Message -> TcRn ()
420 addReportAt loc msg
421   = do { errs_var <- getErrsVar ;
422          rdr_env <- getGlobalRdrEnv ;
423          let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
424          (warns, errs) <- readMutVar errs_var ;
425          writeMutVar errs_var (warns `snocBag` warn, errs) }
426
427 addWarn :: Message -> TcRn ()
428 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
429
430 addWarnAt :: SrcSpan -> Message -> TcRn ()
431 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
432
433 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
434 addLocWarn (L loc e) fn = addReportAt loc (fn e)
435
436 checkErr :: Bool -> Message -> TcRn ()
437 -- Add the error if the bool is False
438 checkErr ok msg = checkM ok (addErr msg)
439
440 warnIf :: Bool -> Message -> TcRn ()
441 warnIf True  msg = addWarn msg
442 warnIf False msg = return ()
443
444 addMessages :: Messages -> TcRn ()
445 addMessages (m_warns, m_errs)
446   = do { errs_var <- getErrsVar ;
447          (warns, errs) <- readMutVar errs_var ;
448          writeMutVar errs_var (warns `unionBags` m_warns,
449                                errs  `unionBags` m_errs) }
450
451 discardWarnings :: TcRn a -> TcRn a
452 -- Ignore warnings inside the thing inside;
453 -- used to ignore-unused-variable warnings inside derived code
454 -- With -dppr-debug, the effects is switched off, so you can still see
455 -- what warnings derived code would give
456 discardWarnings thing_inside
457   | opt_PprStyle_Debug = thing_inside
458   | otherwise
459   = do  { errs_var <- newMutVar emptyMessages
460         ; result <- setErrsVar errs_var thing_inside
461         ; (_warns, errs) <- readMutVar errs_var
462         ; addMessages (emptyBag, errs)
463         ; return result }
464 \end{code}
465
466
467 \begin{code}
468 recoverM :: TcRn r      -- Recovery action; do this if the main one fails
469          -> TcRn r      -- Main action: do this first
470          -> TcRn r
471 recoverM recover thing 
472   = do { mb_res <- try_m thing ;
473          case mb_res of
474            Left exn  -> recover
475            Right res -> returnM res }
476
477 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
478     -- (tryTc m) executes m, and returns
479     --  Just r,  if m succeeds (returning r) and caused no errors
480     --  Nothing, if m fails, or caused errors
481     -- It also returns all the errors accumulated by m
482     --  (even in the Just case, there might be warnings)
483     --
484     -- It always succeeds (never raises an exception)
485 tryTc m 
486  = do { errs_var <- newMutVar emptyMessages ;
487         
488         mb_r <- try_m (setErrsVar errs_var m) ; 
489
490         new_errs <- readMutVar errs_var ;
491
492         dflags <- getDOpts ;
493
494         return (new_errs, 
495                 case mb_r of
496                   Left exn -> Nothing
497                   Right r | errorsFound dflags new_errs -> Nothing
498                           | otherwise                   -> Just r) 
499    }
500
501 try_m :: TcRn r -> TcRn (Either Exception r)
502 -- Does try_m, with a debug-trace on failure
503 try_m thing 
504   = do { mb_r <- tryM thing ;
505          case mb_r of 
506              Left exn -> do { traceTc (exn_msg exn); return mb_r }
507              Right r  -> return mb_r }
508   where
509     exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
510
511 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
512 -- Just like tryTc, except that it ensures that the LIE
513 -- for the thing is propagated only if there are no errors
514 -- Hence it's restricted to the type-check monad
515 tryTcLIE thing_inside
516   = do { ((errs, mb_r), lie) <- getLIE (tryTc thing_inside) ;
517          ifM (isJust mb_r) (extendLIEs lie) ;
518          return (errs, mb_r) }
519
520 tryTcLIE_ :: TcM r -> TcM r -> TcM r
521 -- (tryTcLIE_ r m) tries m; if it succeeds it returns it,
522 -- otherwise it returns r.  Any error messages added by m are discarded,
523 -- whether or not m succeeds.
524 tryTcLIE_ recover main
525   = do { (_msgs, mb_res) <- tryTcLIE main ;
526          case mb_res of
527            Just res -> return res
528            Nothing  -> recover }
529
530 checkNoErrs :: TcM r -> TcM r
531 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
532 -- If m fails then (checkNoErrsTc m) fails.
533 -- If m succeeds, it checks whether m generated any errors messages
534 --      (it might have recovered internally)
535 --      If so, it fails too.
536 -- Regardless, any errors generated by m are propagated to the enclosing context.
537 checkNoErrs main
538   = do { (msgs, mb_res) <- tryTcLIE main ;
539          addMessages msgs ;
540          case mb_res of
541            Just r  -> return r
542            Nothing -> failM
543    }
544
545 ifErrsM :: TcRn r -> TcRn r -> TcRn r
546 --      ifErrsM bale_out main
547 -- does 'bale_out' if there are errors in errors collection
548 -- otherwise does 'main'
549 ifErrsM bale_out normal
550  = do { errs_var <- getErrsVar ;
551         msgs <- readMutVar errs_var ;
552         dflags <- getDOpts ;
553         if errorsFound dflags msgs then
554            bale_out
555         else    
556            normal }
557
558 failIfErrsM :: TcRn ()
559 -- Useful to avoid error cascades
560 failIfErrsM = ifErrsM failM (return ())
561 \end{code}
562
563
564 %************************************************************************
565 %*                                                                      *
566         Context management and error message generation
567                     for the type checker
568 %*                                                                      *
569 %************************************************************************
570
571 \begin{code}
572 setErrCtxtM, addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
573 setErrCtxtM msg = updCtxt (\ msgs -> [msg])
574 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
575
576 setErrCtxt, addErrCtxt :: Message -> TcM a -> TcM a
577 setErrCtxt msg = setErrCtxtM (\env -> returnM (env, msg))
578 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
579
580 popErrCtxt :: TcM a -> TcM a
581 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
582
583 getErrCtxt :: TcM ErrCtxt
584 getErrCtxt = do { env <- getLclEnv ; return (tcl_ctxt env) }
585
586 -- Helper function for the above
587 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
588 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> 
589                            env { tcl_ctxt = upd ctxt })
590
591 getInstLoc :: InstOrigin -> TcM InstLoc
592 getInstLoc origin
593   = do { loc <- getSrcSpanM ; env <- getLclEnv ;
594          return (InstLoc origin loc (tcl_ctxt env)) }
595
596 addInstCtxt :: InstLoc -> TcM a -> TcM a
597 -- Add the SrcSpan and context from the first Inst in the list
598 --      (they all have similar locations)
599 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
600   = addSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
601 \end{code}
602
603     The addErrTc functions add an error message, but do not cause failure.
604     The 'M' variants pass a TidyEnv that has already been used to
605     tidy up the message; we then use it to tidy the context messages
606
607 \begin{code}
608 addErrTc :: Message -> TcM ()
609 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
610
611 addErrsTc :: [Message] -> TcM ()
612 addErrsTc err_msgs = mappM_ addErrTc err_msgs
613
614 addErrTcM :: (TidyEnv, Message) -> TcM ()
615 addErrTcM (tidy_env, err_msg)
616   = do { ctxt <- getErrCtxt ;
617          loc  <- getSrcSpanM ;
618          add_err_tcm tidy_env err_msg loc ctxt }
619 \end{code}
620
621 The failWith functions add an error message and cause failure
622
623 \begin{code}
624 failWithTc :: Message -> TcM a               -- Add an error message and fail
625 failWithTc err_msg 
626   = addErrTc err_msg >> failM
627
628 failWithTcM :: (TidyEnv, Message) -> TcM a   -- Add an error message and fail
629 failWithTcM local_and_msg
630   = addErrTcM local_and_msg >> failM
631
632 checkTc :: Bool -> Message -> TcM ()         -- Check that the boolean is true
633 checkTc True  err = returnM ()
634 checkTc False err = failWithTc err
635 \end{code}
636
637         Warnings have no 'M' variant, nor failure
638
639 \begin{code}
640 addWarnTc :: Message -> TcM ()
641 addWarnTc msg
642  = do { ctxt <- getErrCtxt ;
643         ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
644         addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
645
646 warnTc :: Bool -> Message -> TcM ()
647 warnTc warn_if_true warn_msg
648   | warn_if_true = addWarnTc warn_msg
649   | otherwise    = return ()
650 \end{code}
651
652         Helper functions
653
654 \begin{code}
655 add_err_tcm tidy_env err_msg loc ctxt
656  = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
657         addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
658
659 do_ctxt tidy_env []
660  = return []
661 do_ctxt tidy_env (c:cs)
662  = do { (tidy_env', m) <- c tidy_env  ;
663         ms             <- do_ctxt tidy_env' cs  ;
664         return (m:ms) }
665
666 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
667                  | otherwise          = take 3 ctxt
668 \end{code}
669
670 %************************************************************************
671 %*                                                                      *
672              Type constraints (the so-called LIE)
673 %*                                                                      *
674 %************************************************************************
675
676 \begin{code}
677 getLIEVar :: TcM (TcRef LIE)
678 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
679
680 setLIEVar :: TcRef LIE -> TcM a -> TcM a
681 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
682
683 getLIE :: TcM a -> TcM (a, [Inst])
684 -- (getLIE m) runs m, and returns the type constraints it generates
685 getLIE thing_inside
686   = do { lie_var <- newMutVar emptyLIE ;
687          res <- updLclEnv (\ env -> env { tcl_lie = lie_var }) 
688                           thing_inside ;
689          lie <- readMutVar lie_var ;
690          return (res, lieToList lie) }
691
692 extendLIE :: Inst -> TcM ()
693 extendLIE inst
694   = do { lie_var <- getLIEVar ;
695          lie <- readMutVar lie_var ;
696          writeMutVar lie_var (inst `consLIE` lie) }
697
698 extendLIEs :: [Inst] -> TcM ()
699 extendLIEs [] 
700   = returnM ()
701 extendLIEs insts
702   = do { lie_var <- getLIEVar ;
703          lie <- readMutVar lie_var ;
704          writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
705 \end{code}
706
707 \begin{code}
708 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
709 -- Set the local type envt, but do *not* disturb other fields,
710 -- notably the lie_var
711 setLclTypeEnv lcl_env thing_inside
712   = updLclEnv upd thing_inside
713   where
714     upd env = env { tcl_env = tcl_env lcl_env,
715                     tcl_tyvars = tcl_tyvars lcl_env }
716 \end{code}
717
718
719 %************************************************************************
720 %*                                                                      *
721              Template Haskell context
722 %*                                                                      *
723 %************************************************************************
724
725 \begin{code}
726 getStage :: TcM ThStage
727 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
728
729 setStage :: ThStage -> TcM a -> TcM a 
730 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
731 \end{code}
732
733
734 %************************************************************************
735 %*                                                                      *
736              Arrow context
737 %*                                                                      *
738 %************************************************************************
739
740 \begin{code}
741 popArrowBinders :: TcM a -> TcM a       -- Move to the left of a (-<); see comments in TcRnTypes
742 popArrowBinders 
743   = updLclEnv (\ env -> env { tcl_arrow_ctxt = pop (tcl_arrow_ctxt env)  })
744   where
745     pop (ArrCtxt {proc_level = curr_lvl, proc_banned = banned})
746         = ASSERT( not (curr_lvl `elem` banned) )
747           ArrCtxt {proc_level = curr_lvl, proc_banned = curr_lvl : banned}
748
749 getBannedProcLevels :: TcM [ProcLevel]
750   = do { env <- getLclEnv; return (proc_banned (tcl_arrow_ctxt env)) }
751
752 incProcLevel :: TcM a -> TcM a
753 incProcLevel 
754   = updLclEnv (\ env -> env { tcl_arrow_ctxt = inc (tcl_arrow_ctxt env) })
755   where
756     inc ctxt = ctxt { proc_level = proc_level ctxt + 1 }
757 \end{code}
758
759
760 %************************************************************************
761 %*                                                                      *
762              Stuff for the renamer's local env
763 %*                                                                      *
764 %************************************************************************
765
766 \begin{code}
767 getLocalRdrEnv :: RnM LocalRdrEnv
768 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
769
770 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
771 setLocalRdrEnv rdr_env thing_inside 
772   = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
773 \end{code}
774
775
776 %************************************************************************
777 %*                                                                      *
778              Stuff for interface decls
779 %*                                                                      *
780 %************************************************************************
781
782 \begin{code}
783 initIfaceTcRn :: IfG a -> TcRn a
784 initIfaceTcRn thing_inside
785   = do  { tcg_env <- getGblEnv 
786         ; let { if_env = IfGblEnv { 
787                         if_rec_types = Just (tcg_mod tcg_env, get_type_env),
788                         if_is_boot   = imp_dep_mods (tcg_imports tcg_env) }
789               ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
790         ; setEnvs (if_env, ()) thing_inside }
791
792 initIfaceExtCore :: IfL a -> TcRn a
793 initIfaceExtCore thing_inside
794   = do  { tcg_env <- getGblEnv 
795         ; let { mod = tcg_mod tcg_env
796               ; if_env = IfGblEnv { 
797                         if_rec_types = Just (mod, return (tcg_type_env tcg_env)), 
798                         if_is_boot   = imp_dep_mods (tcg_imports tcg_env) }
799               ; if_lenv = IfLclEnv { if_mod     = moduleName mod,
800                                      if_tv_env  = emptyOccEnv,
801                                      if_id_env  = emptyOccEnv }
802           }
803         ; setEnvs (if_env, if_lenv) thing_inside }
804
805 initIfaceCheck :: HscEnv -> IfG a -> IO a
806 -- Used when checking the up-to-date-ness of the old Iface
807 -- Initialise the environment with no useful info at all
808 initIfaceCheck hsc_env do_this
809  = do   { let { gbl_env = IfGblEnv { if_is_boot   = emptyModuleEnv,
810                                      if_rec_types = Nothing } ;
811            }
812         ; initTcRnIf 'i' hsc_env gbl_env () do_this
813     }
814
815 initIfaceTc :: HscEnv -> ModIface 
816             -> (TcRef TypeEnv -> IfL a) -> IO a
817 -- Used when type-checking checking an up-to-date interface file
818 -- No type envt from the current module, but we do know the module dependencies
819 initIfaceTc hsc_env iface do_this
820  = do   { tc_env_var <- newIORef emptyTypeEnv
821         ; let { gbl_env = IfGblEnv { if_is_boot   = mkModDeps (dep_mods (mi_deps iface)),
822                                      if_rec_types = Just (mod, readMutVar tc_env_var) } ;
823               ; if_lenv = IfLclEnv { if_mod     = moduleName mod,
824                                      if_tv_env  = emptyOccEnv,
825                                      if_id_env  = emptyOccEnv }
826            }
827         ; initTcRnIf 'i' hsc_env gbl_env if_lenv (do_this tc_env_var)
828     }
829   where
830     mod = mi_module iface
831
832 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
833 -- Used when sucking in new Rules in SimplCore
834 -- We have available the type envt of the module being compiled, and we must use it
835 initIfaceRules hsc_env guts do_this
836  = do   { let {
837              is_boot = mkModDeps (dep_mods (mg_deps guts))
838                         -- Urgh!  But we do somehow need to get the info
839                         -- on whether (for this particular compilation) we should
840                         -- import a hi-boot file or not.
841            ; type_info = (mg_module guts, return (mg_types guts))
842            ; gbl_env = IfGblEnv { if_is_boot   = is_boot,
843                                   if_rec_types = Just type_info } ;
844            }
845
846         -- Run the thing; any exceptions just bubble out from here
847         ; initTcRnIf 'i' hsc_env gbl_env () do_this
848     }
849
850 initIfaceLcl :: ModuleName -> IfL a -> IfM lcl a
851 initIfaceLcl mod thing_inside 
852   = setLclEnv (IfLclEnv { if_mod      = mod,
853                            if_tv_env  = emptyOccEnv,
854                            if_id_env  = emptyOccEnv })
855               thing_inside
856
857
858 --------------------
859 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
860 -- Run thing_inside in an interleaved thread.  
861 -- It shares everything with the parent thread, so this is DANGEROUS.  
862 --
863 -- It returns Nothing if the computation fails
864 -- 
865 -- It's used for lazily type-checking interface
866 -- signatures, which is pretty benign
867
868 forkM_maybe doc thing_inside
869  = do { unsafeInterleaveM $
870         do { traceIf (text "Starting fork {" <+> doc)
871            ; mb_res <- tryM thing_inside ;
872              case mb_res of
873                 Right r  -> do  { traceIf (text "} ending fork" <+> doc)
874                                 ; return (Just r) }
875                 Left exn -> do {
876
877                     -- Bleat about errors in the forked thread, if -ddump-if-trace is on
878                     -- Otherwise we silently discard errors. Errors can legitimately
879                     -- happen when compiling interface signatures (see tcInterfaceSigs)
880                       ifOptM Opt_D_dump_if_trace 
881                              (print_errs (hang (text "forkM failed:" <+> doc)
882                                              4 (text (show exn))))
883
884                     ; traceIf (text "} ending fork (badly)" <+> doc)
885                     ; return Nothing }
886         }}
887   where
888     print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
889
890 forkM :: SDoc -> IfL a -> IfL a
891 forkM doc thing_inside
892  = do   { mb_res <- forkM_maybe doc thing_inside
893         ; return (case mb_res of 
894                         Nothing -> pprPanic "forkM" doc
895                         Just r  -> r) }
896 \end{code}