Generalise Package Support
[ghc-hetmet.git] / 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 #if defined(GHCI) && defined(BREAKPOINT)
14 import TypeRep          ( Type(..), liftedTypeKind )
15 import Var              ( mkTyVar, mkGlobalId )
16 import IdInfo           ( GlobalIdDetails(..), vanillaIdInfo )
17 import OccName          ( mkOccName, tvName )
18 import SrcLoc           ( noSrcLoc  )
19 import TysWiredIn       ( intTy, stringTy, mkListTy, unitTy, boolTy )
20 import PrelNames        ( breakpointJumpName, breakpointCondJumpName )
21 import NameEnv          ( mkNameEnv )
22 #endif
23
24 import HsSyn            ( emptyLHsBinds )
25 import HscTypes         ( HscEnv(..), ModGuts(..), ModIface(..),
26                           TypeEnv, emptyTypeEnv, HscSource(..), isHsBoot,
27                           ExternalPackageState(..), HomePackageTable,
28                           Deprecs(..), FixityEnv, FixItem, 
29                           mkPrintUnqualified )
30 import Module           ( Module, moduleName )
31 import RdrName          ( GlobalRdrEnv, LocalRdrEnv, emptyLocalRdrEnv )
32 import Name             ( Name, mkInternalName, tidyNameOcc, nameOccName, getSrcLoc )
33 import Type             ( Type )
34 import TcType           ( tcIsTyVarTy, tcGetTyVar )
35 import NameEnv          ( extendNameEnvList, nameEnvElts )
36 import InstEnv          ( emptyInstEnv )
37
38 import Var              ( setTyVarName )
39 import VarSet           ( emptyVarSet )
40 import VarEnv           ( TidyEnv, emptyTidyEnv, extendVarEnv )
41 import ErrUtils         ( Message, Messages, emptyMessages, errorsFound, 
42                           mkWarnMsg, printErrorsAndWarnings,
43                           mkLocMessage, mkLongErrMsg )
44 import SrcLoc           ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
45 import NameEnv          ( emptyNameEnv )
46 import NameSet          ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
47 import OccName          ( emptyOccEnv, tidyOccName )
48 import Bag              ( emptyBag )
49 import Outputable
50 import UniqSupply       ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
51 import UniqFM           ( unitUFM )
52 import Unique           ( Unique )
53 import DynFlags         ( DynFlags(..), DynFlag(..), dopt, dopt_set, GhcMode )
54 import StaticFlags      ( opt_PprStyle_Debug )
55 import Bag              ( snocBag, unionBags )
56 import Panic            ( showException )
57  
58 import IO               ( stderr )
59 import DATA_IOREF       ( newIORef, readIORef )
60 import EXCEPTION        ( Exception )
61 \end{code}
62
63
64
65 %************************************************************************
66 %*                                                                      *
67                         initTc
68 %*                                                                      *
69 %************************************************************************
70
71 \begin{code}
72 ioToTcRn :: IO r -> TcRn r
73 ioToTcRn = ioToIOEnv
74 \end{code}
75
76 \begin{code}
77 initTc :: HscEnv
78        -> HscSource
79        -> Module 
80        -> TcM r
81        -> IO (Messages, Maybe r)
82                 -- Nothing => error thrown by the thing inside
83                 -- (error messages should have been printed already)
84
85 initTc hsc_env hsc_src mod do_this
86  = do { errs_var     <- newIORef (emptyBag, emptyBag) ;
87         tvs_var      <- newIORef emptyVarSet ;
88         type_env_var <- newIORef emptyNameEnv ;
89         dfuns_var    <- newIORef emptyNameSet ;
90         keep_var     <- newIORef emptyNameSet ;
91         th_var       <- newIORef False ;
92         dfun_n_var   <- newIORef 1 ;
93         let {
94              gbl_env = TcGblEnv {
95                 tcg_mod      = mod,
96                 tcg_src      = hsc_src,
97                 tcg_rdr_env  = hsc_global_rdr_env hsc_env,
98                 tcg_fix_env  = emptyNameEnv,
99                 tcg_default  = Nothing,
100                 tcg_type_env = hsc_global_type_env hsc_env,
101                 tcg_type_env_var = type_env_var,
102                 tcg_inst_env  = emptyInstEnv,
103                 tcg_inst_uses = dfuns_var,
104                 tcg_th_used   = th_var,
105                 tcg_exports  = emptyNameSet,
106                 tcg_imports  = init_imports,
107                 tcg_dus      = emptyDUs,
108                 tcg_rn_imports = Nothing,
109                 tcg_rn_exports = Nothing,
110                 tcg_rn_decls = Nothing,
111                 tcg_binds    = emptyLHsBinds,
112                 tcg_deprecs  = NoDeprecs,
113                 tcg_insts    = [],
114                 tcg_rules    = [],
115                 tcg_fords    = [],
116                 tcg_dfun_n   = dfun_n_var,
117                 tcg_keep     = keep_var
118              } ;
119              lcl_env = TcLclEnv {
120                 tcl_errs       = errs_var,
121                 tcl_loc        = mkGeneralSrcSpan FSLIT("Top level"),
122                 tcl_ctxt       = [],
123                 tcl_rdr        = emptyLocalRdrEnv,
124                 tcl_th_ctxt    = topStage,
125                 tcl_arrow_ctxt = NoArrowCtxt,
126                 tcl_env        = emptyNameEnv,
127                 tcl_tyvars     = tvs_var,
128                 tcl_lie        = panic "initTc:LIE"     -- LIE only valid inside a getLIE
129              } ;
130         } ;
131    
132         -- OK, here's the business end!
133         maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
134                      do {
135 #if defined(GHCI) && defined(BREAKPOINT)
136                           unique <- newUnique ;
137                           let { var = mkInternalName unique (mkOccName tvName "a") noSrcLoc;
138                                 tyvar = mkTyVar var liftedTypeKind;
139                                 basicType extra = (FunTy intTy
140                                                    (FunTy (mkListTy unitTy)
141                                                     (FunTy stringTy
142                                                      (ForAllTy tyvar
143                                                       (extra
144                                                        (FunTy (TyVarTy tyvar)
145                                                         (TyVarTy tyvar)))))));
146                                 breakpointJumpType
147                                     = mkGlobalId VanillaGlobal breakpointJumpName
148                                                  (basicType id) vanillaIdInfo;
149                                 breakpointCondJumpType
150                                     = mkGlobalId VanillaGlobal breakpointCondJumpName
151                                                  (basicType (FunTy boolTy)) vanillaIdInfo;
152                                 new_env = mkNameEnv [(breakpointJumpName
153                                                      , ATcId breakpointJumpType topLevel False)
154                                                      ,(breakpointCondJumpName
155                                                      , ATcId breakpointCondJumpType topLevel False)];
156                               };
157                           r <- tryM (updLclEnv (\gbl -> gbl{tcl_env=new_env}) do_this)
158 #else
159                           r <- tryM do_this
160 #endif
161                         ; case r of
162                           Right res -> return (Just res)
163                           Left _    -> return Nothing } ;
164
165         -- Collect any error messages
166         msgs <- readIORef errs_var ;
167
168         let { dflags = hsc_dflags hsc_env
169             ; final_res | errorsFound dflags msgs = Nothing
170                         | otherwise               = maybe_res } ;
171
172         return (msgs, final_res)
173     }
174   where
175     init_imports = emptyImportAvails {imp_env = 
176                                         unitUFM (moduleName mod) emptyNameSet}
177         -- Initialise tcg_imports with an empty set of bindings for
178         -- this module, so that if we see 'module M' in the export
179         -- list, and there are no bindings in M, we don't bleat 
180         -- "unknown module M".
181
182 initTcPrintErrors       -- Used from the interactive loop only
183        :: HscEnv
184        -> Module 
185        -> TcM r
186        -> IO (Maybe r)
187 initTcPrintErrors env mod todo = do
188   (msgs, res) <- initTc env HsSrcFile mod todo
189   printErrorsAndWarnings (hsc_dflags env) msgs
190   return res
191 \end{code}
192
193
194 %************************************************************************
195 %*                                                                      *
196                 Initialisation
197 %*                                                                      *
198 %************************************************************************
199
200
201 \begin{code}
202 initTcRnIf :: Char              -- Tag for unique supply
203            -> HscEnv
204            -> gbl -> lcl 
205            -> TcRnIf gbl lcl a 
206            -> IO a
207 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
208    = do { us     <- mkSplitUniqSupply uniq_tag ;
209         ; us_var <- newIORef us ;
210
211         ; let { env = Env { env_top = hsc_env,
212                             env_us  = us_var,
213                             env_gbl = gbl_env,
214                             env_lcl = lcl_env } }
215
216         ; runIOEnv env thing_inside
217         }
218 \end{code}
219
220 %************************************************************************
221 %*                                                                      *
222                 Simple accessors
223 %*                                                                      *
224 %************************************************************************
225
226 \begin{code}
227 getTopEnv :: TcRnIf gbl lcl HscEnv
228 getTopEnv = do { env <- getEnv; return (env_top env) }
229
230 getGblEnv :: TcRnIf gbl lcl gbl
231 getGblEnv = do { env <- getEnv; return (env_gbl env) }
232
233 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
234 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) -> 
235                           env { env_gbl = upd gbl })
236
237 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
238 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
239
240 getLclEnv :: TcRnIf gbl lcl lcl
241 getLclEnv = do { env <- getEnv; return (env_lcl env) }
242
243 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
244 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) -> 
245                           env { env_lcl = upd lcl })
246
247 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
248 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
249
250 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
251 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
252
253 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
254 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
255 \end{code}
256
257
258 Command-line flags
259
260 \begin{code}
261 getDOpts :: TcRnIf gbl lcl DynFlags
262 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
263
264 doptM :: DynFlag -> TcRnIf gbl lcl Bool
265 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
266
267 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
268 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
269                          env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
270
271 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()     -- Do it flag is true
272 ifOptM flag thing_inside = do { b <- doptM flag; 
273                                 if b then thing_inside else return () }
274
275 getGhcMode :: TcRnIf gbl lcl GhcMode
276 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
277 \end{code}
278
279 \begin{code}
280 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
281 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
282
283 getEps :: TcRnIf gbl lcl ExternalPackageState
284 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
285
286 -- Updating the EPS.  This should be an atomic operation.
287 -- Note the delicate 'seq' which forces the EPS before putting it in the
288 -- variable.  Otherwise what happens is that we get
289 --      write eps_var (....(unsafeRead eps_var)....)
290 -- and if the .... is strict, that's obviously bottom.  By forcing it beforehand
291 -- we make the unsafeRead happen before we update the variable.
292
293 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
294           -> TcRnIf gbl lcl a
295 updateEps upd_fn = do   { traceIf (text "updating EPS")
296                         ; eps_var <- getEpsVar
297                         ; eps <- readMutVar eps_var
298                         ; let { (eps', val) = upd_fn eps }
299                         ; seq eps' (writeMutVar eps_var eps')
300                         ; return val }
301
302 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
303            -> TcRnIf gbl lcl ()
304 updateEps_ upd_fn = do  { traceIf (text "updating EPS_")
305                         ; eps_var <- getEpsVar
306                         ; eps <- readMutVar eps_var
307                         ; let { eps' = upd_fn eps }
308                         ; seq eps' (writeMutVar eps_var eps') }
309
310 getHpt :: TcRnIf gbl lcl HomePackageTable
311 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
312
313 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
314 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
315                   ; return (eps, hsc_HPT env) }
316 \end{code}
317
318 %************************************************************************
319 %*                                                                      *
320                 Unique supply
321 %*                                                                      *
322 %************************************************************************
323
324 \begin{code}
325 newUnique :: TcRnIf gbl lcl Unique
326 newUnique = do { us <- newUniqueSupply ; 
327                  return (uniqFromSupply us) }
328
329 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
330 newUniqueSupply
331  = do { env <- getEnv ;
332         let { u_var = env_us env } ;
333         us <- readMutVar u_var ;
334         let { (us1, us2) = splitUniqSupply us } ;
335         writeMutVar u_var us1 ;
336         return us2 }
337
338 newLocalName :: Name -> TcRnIf gbl lcl Name
339 newLocalName name       -- Make a clone
340   = newUnique           `thenM` \ uniq ->
341     returnM (mkInternalName uniq (nameOccName name) (getSrcLoc name))
342 \end{code}
343
344
345 %************************************************************************
346 %*                                                                      *
347                 Debugging
348 %*                                                                      *
349 %************************************************************************
350
351 \begin{code}
352 traceTc, traceRn :: SDoc -> TcRn ()
353 traceRn      = traceOptTcRn Opt_D_dump_rn_trace
354 traceTc      = traceOptTcRn Opt_D_dump_tc_trace
355 traceSplice  = traceOptTcRn Opt_D_dump_splices
356
357
358 traceIf :: SDoc -> TcRnIf m n ()        
359 traceIf      = traceOptIf Opt_D_dump_if_trace
360 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
361
362
363 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n ()  -- No RdrEnv available, so qualify everything
364 traceOptIf flag doc = ifOptM flag $
365                      ioToIOEnv (printForUser stderr alwaysQualify doc)
366
367 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
368 traceOptTcRn flag doc = ifOptM flag $ do
369                         { ctxt <- getErrCtxt
370                         ; loc  <- getSrcSpanM
371                         ; env0 <- tcInitTidyEnv
372                         ; ctxt_msgs <- do_ctxt env0 ctxt 
373                         ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
374                         ; dumpTcRn real_doc }
375
376 dumpTcRn :: SDoc -> TcRn ()
377 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
378                     ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
379
380 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
381 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
382 \end{code}
383
384
385 %************************************************************************
386 %*                                                                      *
387                 Typechecker global environment
388 %*                                                                      *
389 %************************************************************************
390
391 \begin{code}
392 getModule :: TcRn Module
393 getModule = do { env <- getGblEnv; return (tcg_mod env) }
394
395 setModule :: Module -> TcRn a -> TcRn a
396 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
397
398 tcIsHsBoot :: TcRn Bool
399 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
400
401 getGlobalRdrEnv :: TcRn GlobalRdrEnv
402 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
403
404 getImports :: TcRn ImportAvails
405 getImports = do { env <- getGblEnv; return (tcg_imports env) }
406
407 getFixityEnv :: TcRn FixityEnv
408 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
409
410 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
411 extendFixityEnv new_bit
412   = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) -> 
413                 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})           
414
415 getDefaultTys :: TcRn (Maybe [Type])
416 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
417 \end{code}
418
419 %************************************************************************
420 %*                                                                      *
421                 Error management
422 %*                                                                      *
423 %************************************************************************
424
425 \begin{code}
426 getSrcSpanM :: TcRn SrcSpan
427         -- Avoid clash with Name.getSrcLoc
428 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
429
430 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
431 setSrcSpan loc thing_inside
432   | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
433   | otherwise         = thing_inside    -- Don't overwrite useful info with useless
434
435 addLocM :: (a -> TcM b) -> Located a -> TcM b
436 addLocM fn (L loc a) = setSrcSpan loc $ fn a
437
438 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
439 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
440
441 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
442 wrapLocFstM fn (L loc a) =
443   setSrcSpan loc $ do
444     (b,c) <- fn a
445     return (L loc b, c)
446
447 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
448 wrapLocSndM fn (L loc a) =
449   setSrcSpan loc $ do
450     (b,c) <- fn a
451     return (b, L loc c)
452 \end{code}
453
454
455 \begin{code}
456 getErrsVar :: TcRn (TcRef Messages)
457 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
458
459 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
460 setErrsVar v = updLclEnv (\ env -> env { tcl_errs =  v })
461
462 addErr :: Message -> TcRn ()
463 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
464
465 addLocErr :: Located e -> (e -> Message) -> TcRn ()
466 addLocErr (L loc e) fn = addErrAt loc (fn e)
467
468 addErrAt :: SrcSpan -> Message -> TcRn ()
469 addErrAt loc msg = addLongErrAt loc msg empty
470
471 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
472 addLongErrAt loc msg extra
473   = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;  
474          errs_var <- getErrsVar ;
475          rdr_env <- getGlobalRdrEnv ;
476          let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
477          (warns, errs) <- readMutVar errs_var ;
478          writeMutVar errs_var (warns, errs `snocBag` err) }
479
480 addErrs :: [(SrcSpan,Message)] -> TcRn ()
481 addErrs msgs = mappM_ add msgs
482              where
483                add (loc,msg) = addErrAt loc msg
484
485 addReport :: Message -> TcRn ()
486 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
487
488 addReportAt :: SrcSpan -> Message -> TcRn ()
489 addReportAt loc msg
490   = do { errs_var <- getErrsVar ;
491          rdr_env <- getGlobalRdrEnv ;
492          let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
493          (warns, errs) <- readMutVar errs_var ;
494          writeMutVar errs_var (warns `snocBag` warn, errs) }
495
496 addWarn :: Message -> TcRn ()
497 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
498
499 addWarnAt :: SrcSpan -> Message -> TcRn ()
500 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
501
502 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
503 addLocWarn (L loc e) fn = addReportAt loc (fn e)
504
505 checkErr :: Bool -> Message -> TcRn ()
506 -- Add the error if the bool is False
507 checkErr ok msg = checkM ok (addErr msg)
508
509 warnIf :: Bool -> Message -> TcRn ()
510 warnIf True  msg = addWarn msg
511 warnIf False msg = return ()
512
513 addMessages :: Messages -> TcRn ()
514 addMessages (m_warns, m_errs)
515   = do { errs_var <- getErrsVar ;
516          (warns, errs) <- readMutVar errs_var ;
517          writeMutVar errs_var (warns `unionBags` m_warns,
518                                errs  `unionBags` m_errs) }
519
520 discardWarnings :: TcRn a -> TcRn a
521 -- Ignore warnings inside the thing inside;
522 -- used to ignore-unused-variable warnings inside derived code
523 -- With -dppr-debug, the effects is switched off, so you can still see
524 -- what warnings derived code would give
525 discardWarnings thing_inside
526   | opt_PprStyle_Debug = thing_inside
527   | otherwise
528   = do  { errs_var <- newMutVar emptyMessages
529         ; result <- setErrsVar errs_var thing_inside
530         ; (_warns, errs) <- readMutVar errs_var
531         ; addMessages (emptyBag, errs)
532         ; return result }
533 \end{code}
534
535
536 \begin{code}
537 try_m :: TcRn r -> TcRn (Either Exception r)
538 -- Does try_m, with a debug-trace on failure
539 try_m thing 
540   = do { mb_r <- tryM thing ;
541          case mb_r of 
542              Left exn -> do { traceTc (exn_msg exn); return mb_r }
543              Right r  -> return mb_r }
544   where
545     exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
546
547 -----------------------
548 recoverM :: TcRn r      -- Recovery action; do this if the main one fails
549          -> TcRn r      -- Main action: do this first
550          -> TcRn r
551 -- Errors in 'thing' are retained
552 recoverM recover thing 
553   = do { mb_res <- try_m thing ;
554          case mb_res of
555            Left exn  -> recover
556            Right res -> returnM res }
557
558 -----------------------
559 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
560 -- (tryTc m) executes m, and returns
561 --      Just r,  if m succeeds (returning r)
562 --      Nothing, if m fails
563 -- It also returns all the errors and warnings accumulated by m
564 -- It always succeeds (never raises an exception)
565 tryTc m 
566  = do { errs_var <- newMutVar emptyMessages ;
567         res  <- try_m (setErrsVar errs_var m) ; 
568         msgs <- readMutVar errs_var ;
569         return (msgs, case res of
570                             Left exn  -> Nothing
571                             Right val -> Just val)
572         -- The exception is always the IOEnv built-in
573         -- in exception; see IOEnv.failM
574    }
575
576 -----------------------
577 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
578 -- Run the thing, returning 
579 --      Just r,  if m succceeds with no error messages
580 --      Nothing, if m fails, or if it succeeds but has error messages
581 -- Either way, the messages are returned; even in the Just case
582 -- there might be warnings
583 tryTcErrs thing 
584   = do  { (msgs, res) <- tryTc thing
585         ; dflags <- getDOpts
586         ; let errs_found = errorsFound dflags msgs
587         ; return (msgs, case res of
588                           Nothing -> Nothing
589                           Just val | errs_found -> Nothing
590                                    | otherwise  -> Just val)
591         }
592
593 -----------------------
594 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
595 -- Just like tryTcErrs, except that it ensures that the LIE
596 -- for the thing is propagated only if there are no errors
597 -- Hence it's restricted to the type-check monad
598 tryTcLIE thing_inside
599   = do  { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
600         ; case mb_res of
601             Nothing  -> return (msgs, Nothing)
602             Just val -> do { extendLIEs lie; return (msgs, Just val) }
603         }
604
605 -----------------------
606 tryTcLIE_ :: TcM r -> TcM r -> TcM r
607 -- (tryTcLIE_ r m) tries m; 
608 --      if m succeeds with no error messages, it's the answer
609 --      otherwise tryTcLIE_ drops everything from m and tries r instead.
610 tryTcLIE_ recover main
611   = do  { (msgs, mb_res) <- tryTcLIE main
612         ; case mb_res of
613              Just val -> do { addMessages msgs  -- There might be warnings
614                              ; return val }
615              Nothing  -> recover                -- Discard all msgs
616         }
617
618 -----------------------
619 checkNoErrs :: TcM r -> TcM r
620 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
621 -- If m fails then (checkNoErrsTc m) fails.
622 -- If m succeeds, it checks whether m generated any errors messages
623 --      (it might have recovered internally)
624 --      If so, it fails too.
625 -- Regardless, any errors generated by m are propagated to the enclosing context.
626 checkNoErrs main
627   = do  { (msgs, mb_res) <- tryTcLIE main
628         ; addMessages msgs
629         ; case mb_res of
630             Nothing   -> failM
631             Just val -> return val
632         } 
633
634 ifErrsM :: TcRn r -> TcRn r -> TcRn r
635 --      ifErrsM bale_out main
636 -- does 'bale_out' if there are errors in errors collection
637 -- otherwise does 'main'
638 ifErrsM bale_out normal
639  = do { errs_var <- getErrsVar ;
640         msgs <- readMutVar errs_var ;
641         dflags <- getDOpts ;
642         if errorsFound dflags msgs then
643            bale_out
644         else    
645            normal }
646
647 failIfErrsM :: TcRn ()
648 -- Useful to avoid error cascades
649 failIfErrsM = ifErrsM failM (return ())
650 \end{code}
651
652
653 %************************************************************************
654 %*                                                                      *
655         Context management and error message generation
656                     for the type checker
657 %*                                                                      *
658 %************************************************************************
659
660 \begin{code}
661 getErrCtxt :: TcM ErrCtxt
662 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
663
664 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
665 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
666
667 addErrCtxt :: Message -> TcM a -> TcM a
668 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
669
670 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
671 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
672
673 -- Helper function for the above
674 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
675 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> 
676                            env { tcl_ctxt = upd ctxt })
677
678 -- Conditionally add an error context
679 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
680 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
681 maybeAddErrCtxt Nothing    thing_inside = thing_inside
682
683 popErrCtxt :: TcM a -> TcM a
684 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
685
686 getInstLoc :: InstOrigin -> TcM InstLoc
687 getInstLoc origin
688   = do { loc <- getSrcSpanM ; env <- getLclEnv ;
689          return (InstLoc origin loc (tcl_ctxt env)) }
690
691 addInstCtxt :: InstLoc -> TcM a -> TcM a
692 -- Add the SrcSpan and context from the first Inst in the list
693 --      (they all have similar locations)
694 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
695   = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
696 \end{code}
697
698     The addErrTc functions add an error message, but do not cause failure.
699     The 'M' variants pass a TidyEnv that has already been used to
700     tidy up the message; we then use it to tidy the context messages
701
702 \begin{code}
703 addErrTc :: Message -> TcM ()
704 addErrTc err_msg = do { env0 <- tcInitTidyEnv
705                       ; addErrTcM (env0, err_msg) }
706
707 addErrsTc :: [Message] -> TcM ()
708 addErrsTc err_msgs = mappM_ addErrTc err_msgs
709
710 addErrTcM :: (TidyEnv, Message) -> TcM ()
711 addErrTcM (tidy_env, err_msg)
712   = do { ctxt <- getErrCtxt ;
713          loc  <- getSrcSpanM ;
714          add_err_tcm tidy_env err_msg loc ctxt }
715 \end{code}
716
717 The failWith functions add an error message and cause failure
718
719 \begin{code}
720 failWithTc :: Message -> TcM a               -- Add an error message and fail
721 failWithTc err_msg 
722   = addErrTc err_msg >> failM
723
724 failWithTcM :: (TidyEnv, Message) -> TcM a   -- Add an error message and fail
725 failWithTcM local_and_msg
726   = addErrTcM local_and_msg >> failM
727
728 checkTc :: Bool -> Message -> TcM ()         -- Check that the boolean is true
729 checkTc True  err = returnM ()
730 checkTc False err = failWithTc err
731 \end{code}
732
733         Warnings have no 'M' variant, nor failure
734
735 \begin{code}
736 addWarnTc :: Message -> TcM ()
737 addWarnTc msg
738  = do { ctxt <- getErrCtxt ;
739         env0 <- tcInitTidyEnv ;
740         ctxt_msgs <- do_ctxt env0 ctxt ;
741         addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
742
743 warnTc :: Bool -> Message -> TcM ()
744 warnTc warn_if_true warn_msg
745   | warn_if_true = addWarnTc warn_msg
746   | otherwise    = return ()
747 \end{code}
748
749 -----------------------------------
750          Tidying
751
752 We initialise the "tidy-env", used for tidying types before printing,
753 by building a reverse map from the in-scope type variables to the
754 OccName that the programmer originally used for them
755
756 \begin{code}
757 tcInitTidyEnv :: TcM TidyEnv
758 tcInitTidyEnv
759   = do  { lcl_env <- getLclEnv
760         ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
761                           | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
762                           , tcIsTyVarTy ty ]
763         ; return (foldl add emptyTidyEnv nm_tv_prs) }
764   where
765     add (env,subst) (name, tyvar)
766         = case tidyOccName env (nameOccName name) of
767             (env', occ') ->  (env', extendVarEnv subst tyvar tyvar')
768                 where
769                   tyvar' = setTyVarName tyvar name'
770                   name'  = tidyNameOcc name occ'
771 \end{code}
772
773 -----------------------------------
774         Other helper functions
775
776 \begin{code}
777 add_err_tcm tidy_env err_msg loc ctxt
778  = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
779         addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
780
781 do_ctxt tidy_env []
782  = return []
783 do_ctxt tidy_env (c:cs)
784  = do { (tidy_env', m) <- c tidy_env  ;
785         ms             <- do_ctxt tidy_env' cs  ;
786         return (m:ms) }
787
788 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
789                  | otherwise          = take 3 ctxt
790 \end{code}
791
792 debugTc is useful for monadic debugging code
793
794 \begin{code}
795 debugTc :: TcM () -> TcM ()
796 #ifdef DEBUG
797 debugTc thing = thing
798 #else
799 debugTc thing = return ()
800 #endif
801 \end{code}
802
803  %************************************************************************
804 %*                                                                      *
805              Type constraints (the so-called LIE)
806 %*                                                                      *
807 %************************************************************************
808
809 \begin{code}
810 nextDFunIndex :: TcM Int        -- Get the next dfun index
811 nextDFunIndex = do { env <- getGblEnv
812                    ; let dfun_n_var = tcg_dfun_n env
813                    ; n <- readMutVar dfun_n_var
814                    ; writeMutVar dfun_n_var (n+1)
815                    ; return n }
816
817 getLIEVar :: TcM (TcRef LIE)
818 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
819
820 setLIEVar :: TcRef LIE -> TcM a -> TcM a
821 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
822
823 getLIE :: TcM a -> TcM (a, [Inst])
824 -- (getLIE m) runs m, and returns the type constraints it generates
825 getLIE thing_inside
826   = do { lie_var <- newMutVar emptyLIE ;
827          res <- updLclEnv (\ env -> env { tcl_lie = lie_var }) 
828                           thing_inside ;
829          lie <- readMutVar lie_var ;
830          return (res, lieToList lie) }
831
832 extendLIE :: Inst -> TcM ()
833 extendLIE inst
834   = do { lie_var <- getLIEVar ;
835          lie <- readMutVar lie_var ;
836          writeMutVar lie_var (inst `consLIE` lie) }
837
838 extendLIEs :: [Inst] -> TcM ()
839 extendLIEs [] 
840   = returnM ()
841 extendLIEs insts
842   = do { lie_var <- getLIEVar ;
843          lie <- readMutVar lie_var ;
844          writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
845 \end{code}
846
847 \begin{code}
848 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
849 -- Set the local type envt, but do *not* disturb other fields,
850 -- notably the lie_var
851 setLclTypeEnv lcl_env thing_inside
852   = updLclEnv upd thing_inside
853   where
854     upd env = env { tcl_env = tcl_env lcl_env,
855                     tcl_tyvars = tcl_tyvars lcl_env }
856 \end{code}
857
858
859 %************************************************************************
860 %*                                                                      *
861              Template Haskell context
862 %*                                                                      *
863 %************************************************************************
864
865 \begin{code}
866 recordThUse :: TcM ()
867 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
868
869 keepAliveTc :: Name -> TcM ()   -- Record the name in the keep-alive set
870 keepAliveTc n = do { env <- getGblEnv; 
871                    ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
872
873 keepAliveSetTc :: NameSet -> TcM ()     -- Record the name in the keep-alive set
874 keepAliveSetTc ns = do { env <- getGblEnv; 
875                        ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
876
877 getStage :: TcM ThStage
878 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
879
880 setStage :: ThStage -> TcM a -> TcM a 
881 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
882 \end{code}
883
884
885 %************************************************************************
886 %*                                                                      *
887              Stuff for the renamer's local env
888 %*                                                                      *
889 %************************************************************************
890
891 \begin{code}
892 getLocalRdrEnv :: RnM LocalRdrEnv
893 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
894
895 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
896 setLocalRdrEnv rdr_env thing_inside 
897   = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
898 \end{code}
899
900
901 %************************************************************************
902 %*                                                                      *
903              Stuff for interface decls
904 %*                                                                      *
905 %************************************************************************
906
907 \begin{code}
908 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
909 mkIfLclEnv mod loc = IfLclEnv { if_mod     = mod,
910                                 if_loc     = loc,
911                                 if_tv_env  = emptyOccEnv,
912                                 if_id_env  = emptyOccEnv }
913
914 initIfaceTcRn :: IfG a -> TcRn a
915 initIfaceTcRn thing_inside
916   = do  { tcg_env <- getGblEnv 
917         ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
918               ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
919         ; setEnvs (if_env, ()) thing_inside }
920
921 initIfaceExtCore :: IfL a -> TcRn a
922 initIfaceExtCore thing_inside
923   = do  { tcg_env <- getGblEnv 
924         ; let { mod = tcg_mod tcg_env
925               ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
926               ; if_env = IfGblEnv { 
927                         if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
928               ; if_lenv = mkIfLclEnv mod doc
929           }
930         ; setEnvs (if_env, if_lenv) thing_inside }
931
932 initIfaceCheck :: HscEnv -> IfG a -> IO a
933 -- Used when checking the up-to-date-ness of the old Iface
934 -- Initialise the environment with no useful info at all
935 initIfaceCheck hsc_env do_this
936  = do   { let gbl_env = IfGblEnv { if_rec_types = Nothing }
937         ; initTcRnIf 'i' hsc_env gbl_env () do_this
938     }
939
940 initIfaceTc :: ModIface 
941             -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
942 -- Used when type-checking checking an up-to-date interface file
943 -- No type envt from the current module, but we do know the module dependencies
944 initIfaceTc iface do_this
945  = do   { tc_env_var <- newMutVar emptyTypeEnv
946         ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
947               ; if_lenv = mkIfLclEnv mod doc
948            }
949         ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
950     }
951   where
952     mod = mi_module iface
953     doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
954
955 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
956 -- Used when sucking in new Rules in SimplCore
957 -- We have available the type envt of the module being compiled, and we must use it
958 initIfaceRules hsc_env guts do_this
959  = do   { let {
960              type_info = (mg_module guts, return (mg_types guts))
961            ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
962            }
963
964         -- Run the thing; any exceptions just bubble out from here
965         ; initTcRnIf 'i' hsc_env gbl_env () do_this
966     }
967
968 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
969 initIfaceLcl mod loc_doc thing_inside 
970   = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
971
972 getIfModule :: IfL Module
973 getIfModule = do { env <- getLclEnv; return (if_mod env) }
974
975 --------------------
976 failIfM :: Message -> IfL a
977 -- The Iface monad doesn't have a place to accumulate errors, so we
978 -- just fall over fast if one happens; it "shouldnt happen".
979 -- We use IfL here so that we can get context info out of the local env
980 failIfM msg
981   = do  { env <- getLclEnv
982         ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
983         ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
984         ; failM }
985
986 --------------------
987 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
988 -- Run thing_inside in an interleaved thread.  
989 -- It shares everything with the parent thread, so this is DANGEROUS.  
990 --
991 -- It returns Nothing if the computation fails
992 -- 
993 -- It's used for lazily type-checking interface
994 -- signatures, which is pretty benign
995
996 forkM_maybe doc thing_inside
997  = do { unsafeInterleaveM $
998         do { traceIf (text "Starting fork {" <+> doc)
999            ; mb_res <- tryM $
1000                        updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $ 
1001                        thing_inside
1002            ; case mb_res of
1003                 Right r  -> do  { traceIf (text "} ending fork" <+> doc)
1004                                 ; return (Just r) }
1005                 Left exn -> do {
1006
1007                     -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1008                     -- Otherwise we silently discard errors. Errors can legitimately
1009                     -- happen when compiling interface signatures (see tcInterfaceSigs)
1010                       ifOptM Opt_D_dump_if_trace 
1011                              (print_errs (hang (text "forkM failed:" <+> doc)
1012                                              4 (text (show exn))))
1013
1014                     ; traceIf (text "} ending fork (badly)" <+> doc)
1015                     ; return Nothing }
1016         }}
1017   where
1018     print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1019
1020 forkM :: SDoc -> IfL a -> IfL a
1021 forkM doc thing_inside
1022  = do   { mb_res <- forkM_maybe doc thing_inside
1023         ; return (case mb_res of 
1024                         Nothing -> pgmError "Cannot continue after interface file error"
1025                                    -- pprPanic "forkM" doc
1026                         Just r  -> r) }
1027 \end{code}
1028
1029