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