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