[project @ 2004-01-05 12:11:42 by simonpj]
[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, mkLocMessage )
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  = emptyNameSet,
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 $ 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
402  = do {  errs_var <- getErrsVar ;
403          rdr_env <- getGlobalRdrEnv ;
404          let { err = mkErrMsg loc (unQualInScope rdr_env) msg } ;
405          (warns, errs) <- readMutVar errs_var ;
406          writeMutVar errs_var (warns, errs `snocBag` err) }
407
408 addErrs :: [(SrcSpan,Message)] -> TcRn ()
409 addErrs msgs = mappM_ add msgs
410              where
411                add (loc,msg) = addErrAt loc msg
412
413 addReport :: Message -> TcRn ()
414 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
415
416 addReportAt :: SrcSpan -> Message -> TcRn ()
417 addReportAt loc msg
418   = do { errs_var <- getErrsVar ;
419          rdr_env <- getGlobalRdrEnv ;
420          let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
421          (warns, errs) <- readMutVar errs_var ;
422          writeMutVar errs_var (warns `snocBag` warn, errs) }
423
424 addWarn :: Message -> TcRn ()
425 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
426
427 addWarnAt :: SrcSpan -> Message -> TcRn ()
428 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
429
430 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
431 addLocWarn (L loc e) fn = addReportAt loc (fn e)
432
433 checkErr :: Bool -> Message -> TcRn ()
434 -- Add the error if the bool is False
435 checkErr ok msg = checkM ok (addErr msg)
436
437 warnIf :: Bool -> Message -> TcRn ()
438 warnIf True  msg = addWarn msg
439 warnIf False msg = return ()
440
441 addMessages :: Messages -> TcRn ()
442 addMessages (m_warns, m_errs)
443   = do { errs_var <- getErrsVar ;
444          (warns, errs) <- readMutVar errs_var ;
445          writeMutVar errs_var (warns `unionBags` m_warns,
446                                errs  `unionBags` m_errs) }
447
448 discardWarnings :: TcRn a -> TcRn a
449 -- Ignore warnings inside the thing inside;
450 -- used to ignore-unused-variable warnings inside derived code
451 -- With -dppr-debug, the effects is switched off, so you can still see
452 -- what warnings derived code would give
453 discardWarnings thing_inside
454   | opt_PprStyle_Debug = thing_inside
455   | otherwise
456   = do  { errs_var <- newMutVar emptyMessages
457         ; result <- setErrsVar errs_var thing_inside
458         ; (_warns, errs) <- readMutVar errs_var
459         ; addMessages (emptyBag, errs)
460         ; return result }
461 \end{code}
462
463
464 \begin{code}
465 recoverM :: TcRn r      -- Recovery action; do this if the main one fails
466          -> TcRn r      -- Main action: do this first
467          -> TcRn r
468 recoverM recover thing 
469   = do { mb_res <- try_m thing ;
470          case mb_res of
471            Left exn  -> recover
472            Right res -> returnM res }
473
474 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
475     -- (tryTc m) executes m, and returns
476     --  Just r,  if m succeeds (returning r) and caused no errors
477     --  Nothing, if m fails, or caused errors
478     -- It also returns all the errors accumulated by m
479     --  (even in the Just case, there might be warnings)
480     --
481     -- It always succeeds (never raises an exception)
482 tryTc m 
483  = do { errs_var <- newMutVar emptyMessages ;
484         
485         mb_r <- try_m (setErrsVar errs_var m) ; 
486
487         new_errs <- readMutVar errs_var ;
488
489         dflags <- getDOpts ;
490
491         return (new_errs, 
492                 case mb_r of
493                   Left exn -> Nothing
494                   Right r | errorsFound dflags new_errs -> Nothing
495                           | otherwise                   -> Just r) 
496    }
497
498 try_m :: TcRn r -> TcRn (Either Exception r)
499 -- Does try_m, with a debug-trace on failure
500 try_m thing 
501   = do { mb_r <- tryM thing ;
502          case mb_r of 
503              Left exn -> do { traceTc (exn_msg exn); return mb_r }
504              Right r  -> return mb_r }
505   where
506     exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
507
508 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
509 -- Just like tryTc, except that it ensures that the LIE
510 -- for the thing is propagated only if there are no errors
511 -- Hence it's restricted to the type-check monad
512 tryTcLIE thing_inside
513   = do { ((errs, mb_r), lie) <- getLIE (tryTc thing_inside) ;
514          ifM (isJust mb_r) (extendLIEs lie) ;
515          return (errs, mb_r) }
516
517 tryTcLIE_ :: TcM r -> TcM r -> TcM r
518 -- (tryTcLIE_ r m) tries m; if it succeeds it returns it,
519 -- otherwise it returns r.  Any error messages added by m are discarded,
520 -- whether or not m succeeds.
521 tryTcLIE_ recover main
522   = do { (_msgs, mb_res) <- tryTcLIE main ;
523          case mb_res of
524            Just res -> return res
525            Nothing  -> recover }
526
527 checkNoErrs :: TcM r -> TcM r
528 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
529 -- If m fails then (checkNoErrsTc m) fails.
530 -- If m succeeds, it checks whether m generated any errors messages
531 --      (it might have recovered internally)
532 --      If so, it fails too.
533 -- Regardless, any errors generated by m are propagated to the enclosing context.
534 checkNoErrs main
535   = do { (msgs, mb_res) <- tryTcLIE main ;
536          addMessages msgs ;
537          case mb_res of
538            Just r  -> return r
539            Nothing -> failM
540    }
541
542 ifErrsM :: TcRn r -> TcRn r -> TcRn r
543 --      ifErrsM bale_out main
544 -- does 'bale_out' if there are errors in errors collection
545 -- otherwise does 'main'
546 ifErrsM bale_out normal
547  = do { errs_var <- getErrsVar ;
548         msgs <- readMutVar errs_var ;
549         dflags <- getDOpts ;
550         if errorsFound dflags msgs then
551            bale_out
552         else    
553            normal }
554
555 failIfErrsM :: TcRn ()
556 -- Useful to avoid error cascades
557 failIfErrsM = ifErrsM failM (return ())
558 \end{code}
559
560
561 %************************************************************************
562 %*                                                                      *
563         Context management and error message generation
564                     for the type checker
565 %*                                                                      *
566 %************************************************************************
567
568 \begin{code}
569 setErrCtxtM, addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
570 setErrCtxtM msg = updCtxt (\ msgs -> [msg])
571 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
572
573 setErrCtxt, addErrCtxt :: Message -> TcM a -> TcM a
574 setErrCtxt msg = setErrCtxtM (\env -> returnM (env, msg))
575 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
576
577 popErrCtxt :: TcM a -> TcM a
578 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
579
580 getErrCtxt :: TcM ErrCtxt
581 getErrCtxt = do { env <- getLclEnv ; return (tcl_ctxt env) }
582
583 -- Helper function for the above
584 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
585 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> 
586                            env { tcl_ctxt = upd ctxt })
587
588 getInstLoc :: InstOrigin -> TcM InstLoc
589 getInstLoc origin
590   = do { loc <- getSrcSpanM ; env <- getLclEnv ;
591          return (InstLoc origin loc (tcl_ctxt env)) }
592
593 addInstCtxt :: InstLoc -> TcM a -> TcM a
594 -- Add the SrcSpan and context from the first Inst in the list
595 --      (they all have similar locations)
596 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
597   = addSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
598 \end{code}
599
600     The addErrTc functions add an error message, but do not cause failure.
601     The 'M' variants pass a TidyEnv that has already been used to
602     tidy up the message; we then use it to tidy the context messages
603
604 \begin{code}
605 addErrTc :: Message -> TcM ()
606 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
607
608 addErrsTc :: [Message] -> TcM ()
609 addErrsTc err_msgs = mappM_ addErrTc err_msgs
610
611 addErrTcM :: (TidyEnv, Message) -> TcM ()
612 addErrTcM (tidy_env, err_msg)
613   = do { ctxt <- getErrCtxt ;
614          loc  <- getSrcSpanM ;
615          add_err_tcm tidy_env err_msg loc ctxt }
616 \end{code}
617
618 The failWith functions add an error message and cause failure
619
620 \begin{code}
621 failWithTc :: Message -> TcM a               -- Add an error message and fail
622 failWithTc err_msg 
623   = addErrTc err_msg >> failM
624
625 failWithTcM :: (TidyEnv, Message) -> TcM a   -- Add an error message and fail
626 failWithTcM local_and_msg
627   = addErrTcM local_and_msg >> failM
628
629 checkTc :: Bool -> Message -> TcM ()         -- Check that the boolean is true
630 checkTc True  err = returnM ()
631 checkTc False err = failWithTc err
632 \end{code}
633
634         Warnings have no 'M' variant, nor failure
635
636 \begin{code}
637 addWarnTc :: Message -> TcM ()
638 addWarnTc msg
639  = do { ctxt <- getErrCtxt ;
640         ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
641         addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
642
643 warnTc :: Bool -> Message -> TcM ()
644 warnTc warn_if_true warn_msg
645   | warn_if_true = addWarnTc warn_msg
646   | otherwise    = return ()
647 \end{code}
648
649         Helper functions
650
651 \begin{code}
652 add_err_tcm tidy_env err_msg loc ctxt
653  = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
654         addErrAt loc (vcat (err_msg : ctxt_to_use ctxt_msgs)) }
655
656 do_ctxt tidy_env []
657  = return []
658 do_ctxt tidy_env (c:cs)
659  = do { (tidy_env', m) <- c tidy_env  ;
660         ms             <- do_ctxt tidy_env' cs  ;
661         return (m:ms) }
662
663 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
664                  | otherwise          = take 3 ctxt
665 \end{code}
666
667 %************************************************************************
668 %*                                                                      *
669              Type constraints (the so-called LIE)
670 %*                                                                      *
671 %************************************************************************
672
673 \begin{code}
674 getLIEVar :: TcM (TcRef LIE)
675 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
676
677 setLIEVar :: TcRef LIE -> TcM a -> TcM a
678 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
679
680 getLIE :: TcM a -> TcM (a, [Inst])
681 -- (getLIE m) runs m, and returns the type constraints it generates
682 getLIE thing_inside
683   = do { lie_var <- newMutVar emptyLIE ;
684          res <- updLclEnv (\ env -> env { tcl_lie = lie_var }) 
685                           thing_inside ;
686          lie <- readMutVar lie_var ;
687          return (res, lieToList lie) }
688
689 extendLIE :: Inst -> TcM ()
690 extendLIE inst
691   = do { lie_var <- getLIEVar ;
692          lie <- readMutVar lie_var ;
693          writeMutVar lie_var (inst `consLIE` lie) }
694
695 extendLIEs :: [Inst] -> TcM ()
696 extendLIEs [] 
697   = returnM ()
698 extendLIEs insts
699   = do { lie_var <- getLIEVar ;
700          lie <- readMutVar lie_var ;
701          writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
702 \end{code}
703
704 \begin{code}
705 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
706 -- Set the local type envt, but do *not* disturb other fields,
707 -- notably the lie_var
708 setLclTypeEnv lcl_env thing_inside
709   = updLclEnv upd thing_inside
710   where
711     upd env = env { tcl_env = tcl_env lcl_env,
712                     tcl_tyvars = tcl_tyvars lcl_env }
713 \end{code}
714
715
716 %************************************************************************
717 %*                                                                      *
718              Template Haskell context
719 %*                                                                      *
720 %************************************************************************
721
722 \begin{code}
723 getStage :: TcM ThStage
724 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
725
726 setStage :: ThStage -> TcM a -> TcM a 
727 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
728 \end{code}
729
730
731 %************************************************************************
732 %*                                                                      *
733              Arrow context
734 %*                                                                      *
735 %************************************************************************
736
737 \begin{code}
738 popArrowBinders :: TcM a -> TcM a       -- Move to the left of a (-<); see comments in TcRnTypes
739 popArrowBinders 
740   = updLclEnv (\ env -> env { tcl_arrow_ctxt = pop (tcl_arrow_ctxt env)  })
741   where
742     pop (ArrCtxt {proc_level = curr_lvl, proc_banned = banned})
743         = ASSERT( not (curr_lvl `elem` banned) )
744           ArrCtxt {proc_level = curr_lvl, proc_banned = curr_lvl : banned}
745
746 getBannedProcLevels :: TcM [ProcLevel]
747   = do { env <- getLclEnv; return (proc_banned (tcl_arrow_ctxt env)) }
748
749 incProcLevel :: TcM a -> TcM a
750 incProcLevel 
751   = updLclEnv (\ env -> env { tcl_arrow_ctxt = inc (tcl_arrow_ctxt env) })
752   where
753     inc ctxt = ctxt { proc_level = proc_level ctxt + 1 }
754 \end{code}
755
756
757 %************************************************************************
758 %*                                                                      *
759              Stuff for the renamer's local env
760 %*                                                                      *
761 %************************************************************************
762
763 \begin{code}
764 getLocalRdrEnv :: RnM LocalRdrEnv
765 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
766
767 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
768 setLocalRdrEnv rdr_env thing_inside 
769   = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
770 \end{code}
771
772
773 %************************************************************************
774 %*                                                                      *
775              Stuff for interface decls
776 %*                                                                      *
777 %************************************************************************
778
779 \begin{code}
780 initIfaceTcRn :: IfG a -> TcRn a
781 initIfaceTcRn thing_inside
782   = do  { tcg_env <- getGblEnv 
783         ; let { if_env = IfGblEnv { 
784                         if_rec_types = Just (tcg_mod tcg_env, get_type_env),
785                         if_is_boot   = imp_dep_mods (tcg_imports tcg_env) }
786               ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
787         ; setEnvs (if_env, ()) thing_inside }
788
789 initIfaceExtCore :: IfL a -> TcRn a
790 initIfaceExtCore thing_inside
791   = do  { tcg_env <- getGblEnv 
792         ; let { mod = tcg_mod tcg_env
793               ; if_env = IfGblEnv { 
794                         if_rec_types = Just (mod, return (tcg_type_env tcg_env)), 
795                         if_is_boot   = imp_dep_mods (tcg_imports tcg_env) }
796               ; if_lenv = IfLclEnv { if_mod     = moduleName mod,
797                                      if_tv_env  = emptyOccEnv,
798                                      if_id_env  = emptyOccEnv }
799           }
800         ; setEnvs (if_env, if_lenv) thing_inside }
801
802 initIfaceCheck :: HscEnv -> IfG a -> IO a
803 -- Used when checking the up-to-date-ness of the old Iface
804 -- Initialise the environment with no useful info at all
805 initIfaceCheck hsc_env do_this
806  = do   { let { gbl_env = IfGblEnv { if_is_boot   = emptyModuleEnv,
807                                      if_rec_types = Nothing } ;
808            }
809         ; initTcRnIf 'i' hsc_env gbl_env () do_this
810     }
811
812 initIfaceTc :: HscEnv -> ModIface 
813             -> (TcRef TypeEnv -> IfL a) -> IO a
814 -- Used when type-checking checking an up-to-date interface file
815 -- No type envt from the current module, but we do know the module dependencies
816 initIfaceTc hsc_env iface do_this
817  = do   { tc_env_var <- newIORef emptyTypeEnv
818         ; let { gbl_env = IfGblEnv { if_is_boot   = mkModDeps (dep_mods (mi_deps iface)),
819                                      if_rec_types = Just (mod, readMutVar tc_env_var) } ;
820               ; if_lenv = IfLclEnv { if_mod     = moduleName mod,
821                                      if_tv_env  = emptyOccEnv,
822                                      if_id_env  = emptyOccEnv }
823            }
824         ; initTcRnIf 'i' hsc_env gbl_env if_lenv (do_this tc_env_var)
825     }
826   where
827     mod = mi_module iface
828
829 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
830 -- Used when sucking in new Rules in SimplCore
831 -- We have available the type envt of the module being compiled, and we must use it
832 initIfaceRules hsc_env guts do_this
833  = do   { let {
834              is_boot = mkModDeps (dep_mods (mg_deps guts))
835                         -- Urgh!  But we do somehow need to get the info
836                         -- on whether (for this particular compilation) we should
837                         -- import a hi-boot file or not.
838            ; type_info = (mg_module guts, return (mg_types guts))
839            ; gbl_env = IfGblEnv { if_is_boot   = is_boot,
840                                   if_rec_types = Just type_info } ;
841            }
842
843         -- Run the thing; any exceptions just bubble out from here
844         ; initTcRnIf 'i' hsc_env gbl_env () do_this
845     }
846
847 initIfaceLcl :: ModuleName -> IfL a -> IfM lcl a
848 initIfaceLcl mod thing_inside 
849   = setLclEnv (IfLclEnv { if_mod      = mod,
850                            if_tv_env  = emptyOccEnv,
851                            if_id_env  = emptyOccEnv })
852               thing_inside
853
854
855 --------------------
856 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
857 -- Run thing_inside in an interleaved thread.  
858 -- It shares everything with the parent thread, so this is DANGEROUS.  
859 --
860 -- It returns Nothing if the computation fails
861 -- 
862 -- It's used for lazily type-checking interface
863 -- signatures, which is pretty benign
864
865 forkM_maybe doc thing_inside
866  = do { unsafeInterleaveM $
867         do { traceIf (text "Starting fork {" <+> doc)
868            ; mb_res <- tryM thing_inside ;
869              case mb_res of
870                 Right r  -> do  { traceIf (text "} ending fork" <+> doc)
871                                 ; return (Just r) }
872                 Left exn -> do {
873
874                     -- Bleat about errors in the forked thread, if -ddump-if-trace is on
875                     -- Otherwise we silently discard errors. Errors can legitimately
876                     -- happen when compiling interface signatures (see tcInterfaceSigs)
877                       ifOptM Opt_D_dump_if_trace 
878                              (print_errs (hang (text "forkM failed:" <+> doc)
879                                              4 (text (show exn))))
880
881                     ; traceIf (text "} ending fork (badly)" <+> doc)
882                     ; return Nothing }
883         }}
884   where
885     print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
886
887 forkM :: SDoc -> IfL a -> IfL a
888 forkM doc thing_inside
889  = do   { mb_res <- forkM_maybe doc thing_inside
890         ; return (case mb_res of 
891                         Nothing -> pprPanic "forkM" doc
892                         Just r  -> r) }
893 \end{code}