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