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