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