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