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