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