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