929270b920e9100ba0895514a6ce5f2ddafea28c
[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 import TcRnTypes        -- Re-export all
13 import IOEnv            -- Re-export all
14
15 import HsSyn hiding (LIE)
16 import HscTypes
17 import Module
18 import RdrName
19 import Name
20 import TcType
21 import InstEnv
22 import FamInstEnv
23
24 import Var
25 import Id
26 import VarSet
27 import VarEnv
28 import ErrUtils
29 import SrcLoc
30 import NameEnv
31 import NameSet
32 import OccName
33 import Bag
34 import Outputable
35 import UniqSupply
36 import Unique
37 import LazyUniqFM
38 import DynFlags
39 import StaticFlags
40 import FastString
41 import Panic
42 import Util
43
44 import System.IO
45 import Data.IORef
46 import Control.Monad
47 \end{code}
48
49
50
51 %************************************************************************
52 %*                                                                      *
53                         initTc
54 %*                                                                      *
55 %************************************************************************
56
57 \begin{code}
58
59 initTc :: HscEnv
60        -> HscSource
61        -> Bool          -- True <=> retain renamed syntax trees
62        -> Module 
63        -> TcM r
64        -> IO (Messages, Maybe r)
65                 -- Nothing => error thrown by the thing inside
66                 -- (error messages should have been printed already)
67
68 initTc hsc_env hsc_src keep_rn_syntax mod do_this
69  = do { errs_var     <- newIORef (emptyBag, emptyBag) ;
70         tvs_var      <- newIORef emptyVarSet ;
71         dfuns_var    <- newIORef emptyNameSet ;
72         keep_var     <- newIORef emptyNameSet ;
73         th_var       <- newIORef False ;
74         dfun_n_var   <- newIORef 1 ;
75         type_env_var <- case hsc_type_env_var hsc_env of {
76                            Just (_mod, te_var) -> return te_var ;
77                            Nothing             -> newIORef emptyNameEnv } ;
78         let {
79              maybe_rn_syntax empty_val
80                 | keep_rn_syntax = Just empty_val
81                 | otherwise      = Nothing ;
82                         
83              gbl_env = TcGblEnv {
84                 tcg_mod       = mod,
85                 tcg_src       = hsc_src,
86                 tcg_rdr_env   = hsc_global_rdr_env hsc_env,
87                 tcg_fix_env   = emptyNameEnv,
88                 tcg_field_env = emptyNameEnv,
89                 tcg_default   = Nothing,
90                 tcg_type_env  = hsc_global_type_env hsc_env,
91                 tcg_type_env_var = type_env_var,
92                 tcg_inst_env  = emptyInstEnv,
93                 tcg_fam_inst_env  = emptyFamInstEnv,
94                 tcg_inst_uses = dfuns_var,
95                 tcg_th_used   = th_var,
96                 tcg_exports  = [],
97                 tcg_imports  = emptyImportAvails,
98                 tcg_dus      = emptyDUs,
99
100                 tcg_rn_imports = maybe_rn_syntax [],
101                 tcg_rn_exports = maybe_rn_syntax [],
102                 tcg_rn_decls   = maybe_rn_syntax emptyRnGroup,
103
104                 tcg_binds    = emptyLHsBinds,
105                 tcg_warns  = NoWarnings,
106                 tcg_insts    = [],
107                 tcg_fam_insts= [],
108                 tcg_rules    = [],
109                 tcg_fords    = [],
110                 tcg_dfun_n   = dfun_n_var,
111                 tcg_keep     = keep_var,
112                 tcg_doc      = Nothing,
113                 tcg_hmi      = HaddockModInfo Nothing Nothing Nothing Nothing,
114                 tcg_hpc      = False
115              } ;
116              lcl_env = TcLclEnv {
117                 tcl_errs       = errs_var,
118                 tcl_loc        = mkGeneralSrcSpan (fsLit "Top level"),
119                 tcl_ctxt       = [],
120                 tcl_rdr        = emptyLocalRdrEnv,
121                 tcl_th_ctxt    = topStage,
122                 tcl_arrow_ctxt = NoArrowCtxt,
123                 tcl_env        = emptyNameEnv,
124                 tcl_tyvars     = tvs_var,
125                 tcl_lie        = panic "initTc:LIE"     -- LIE only valid inside a getLIE
126              } ;
127         } ;
128    
129         -- OK, here's the business end!
130         maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
131                      do { r <- tryM do_this
132                         ; case r of
133                           Right res -> return (Just res)
134                           Left _    -> return Nothing } ;
135
136         -- Collect any error messages
137         msgs <- readIORef errs_var ;
138
139         let { dflags = hsc_dflags hsc_env
140             ; final_res | errorsFound dflags msgs = Nothing
141                         | otherwise               = maybe_res } ;
142
143         return (msgs, final_res)
144     }
145
146 initTcPrintErrors       -- Used from the interactive loop only
147        :: HscEnv
148        -> Module 
149        -> TcM r
150        -> IO (Messages, Maybe r)
151 initTcPrintErrors env mod todo = do
152   (msgs, res) <- initTc env HsSrcFile False mod todo
153   return (msgs, res)
154 \end{code}
155
156 %************************************************************************
157 %*                                                                      *
158                 Initialisation
159 %*                                                                      *
160 %************************************************************************
161
162
163 \begin{code}
164 initTcRnIf :: Char              -- Tag for unique supply
165            -> HscEnv
166            -> gbl -> lcl 
167            -> TcRnIf gbl lcl a 
168            -> IO a
169 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
170    = do { us     <- mkSplitUniqSupply uniq_tag ;
171         ; us_var <- newIORef us ;
172
173         ; let { env = Env { env_top = hsc_env,
174                             env_us  = us_var,
175                             env_gbl = gbl_env,
176                             env_lcl = lcl_env} }
177
178         ; runIOEnv env thing_inside
179         }
180 \end{code}
181
182 %************************************************************************
183 %*                                                                      *
184                 Simple accessors
185 %*                                                                      *
186 %************************************************************************
187
188 \begin{code}
189 getTopEnv :: TcRnIf gbl lcl HscEnv
190 getTopEnv = do { env <- getEnv; return (env_top env) }
191
192 getGblEnv :: TcRnIf gbl lcl gbl
193 getGblEnv = do { env <- getEnv; return (env_gbl env) }
194
195 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
196 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) -> 
197                           env { env_gbl = upd gbl })
198
199 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
200 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
201
202 getLclEnv :: TcRnIf gbl lcl lcl
203 getLclEnv = do { env <- getEnv; return (env_lcl env) }
204
205 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
206 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) -> 
207                           env { env_lcl = upd lcl })
208
209 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
210 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
211
212 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
213 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
214
215 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
216 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
217 \end{code}
218
219
220 Command-line flags
221
222 \begin{code}
223 getDOpts :: TcRnIf gbl lcl DynFlags
224 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
225
226 doptM :: DynFlag -> TcRnIf gbl lcl Bool
227 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
228
229 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
230 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
231                          env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
232
233 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
234 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
235                          env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
236
237 -- | Do it flag is true
238 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
239 ifOptM flag thing_inside = do { b <- doptM flag; 
240                                 if b then thing_inside else return () }
241
242 getGhcMode :: TcRnIf gbl lcl GhcMode
243 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
244 \end{code}
245
246 \begin{code}
247 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
248 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
249
250 getEps :: TcRnIf gbl lcl ExternalPackageState
251 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
252
253 -- Updating the EPS.  This should be an atomic operation.
254 -- Note the delicate 'seq' which forces the EPS before putting it in the
255 -- variable.  Otherwise what happens is that we get
256 --      write eps_var (....(unsafeRead eps_var)....)
257 -- and if the .... is strict, that's obviously bottom.  By forcing it beforehand
258 -- we make the unsafeRead happen before we update the variable.
259
260 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
261           -> TcRnIf gbl lcl a
262 updateEps upd_fn = do   { traceIf (text "updating EPS")
263                         ; eps_var <- getEpsVar
264                         ; eps <- readMutVar eps_var
265                         ; let { (eps', val) = upd_fn eps }
266                         ; seq eps' (writeMutVar eps_var eps')
267                         ; return val }
268
269 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
270            -> TcRnIf gbl lcl ()
271 updateEps_ upd_fn = do  { traceIf (text "updating EPS_")
272                         ; eps_var <- getEpsVar
273                         ; eps <- readMutVar eps_var
274                         ; let { eps' = upd_fn eps }
275                         ; seq eps' (writeMutVar eps_var eps') }
276
277 getHpt :: TcRnIf gbl lcl HomePackageTable
278 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
279
280 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
281 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
282                   ; return (eps, hsc_HPT env) }
283 \end{code}
284
285 %************************************************************************
286 %*                                                                      *
287                 Unique supply
288 %*                                                                      *
289 %************************************************************************
290
291 \begin{code}
292 newUnique :: TcRnIf gbl lcl Unique
293 newUnique
294  = do { env <- getEnv ;
295         let { u_var = env_us env } ;
296         us <- readMutVar u_var ;
297         case splitUniqSupply us of { (us1,_) -> do {
298         writeMutVar u_var us1 ;
299         return $! uniqFromSupply us }}}
300    -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
301    -- a chain of unevaluated supplies behind.
302    -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
303    -- throw away one half of the new split supply.  This is safe because this
304    -- is the only place we use that unique.  Using the other half of the split
305    -- supply is safer, but slower.
306
307 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
308 newUniqueSupply
309  = do { env <- getEnv ;
310         let { u_var = env_us env } ;
311         us <- readMutVar u_var ;
312         case splitUniqSupply us of { (us1,us2) -> do {
313         writeMutVar u_var us1 ;
314         return us2 }}}
315
316 newLocalName :: Name -> TcRnIf gbl lcl Name
317 newLocalName name       -- Make a clone
318   = do  { uniq <- newUnique
319         ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
320
321 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
322 newSysLocalIds fs tys
323   = do  { us <- newUniqueSupply
324         ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
325
326 instance MonadUnique (IOEnv (Env gbl lcl)) where
327         getUniqueM = newUnique
328         getUniqueSupplyM = newUniqueSupply
329 \end{code}
330
331
332 %************************************************************************
333 %*                                                                      *
334                 Debugging
335 %*                                                                      *
336 %************************************************************************
337
338 \begin{code}
339 traceTc, traceRn, traceSplice :: SDoc -> TcRn ()
340 traceRn      = traceOptTcRn Opt_D_dump_rn_trace
341 traceTc      = traceOptTcRn Opt_D_dump_tc_trace
342 traceSplice  = traceOptTcRn Opt_D_dump_splices
343
344
345 traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()
346 traceIf      = traceOptIf Opt_D_dump_if_trace
347 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
348
349
350 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n ()  -- No RdrEnv available, so qualify everything
351 traceOptIf flag doc = ifOptM flag $
352                       liftIO (printForUser stderr alwaysQualify doc)
353
354 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
355 traceOptTcRn flag doc = ifOptM flag $ do
356                         { ctxt <- getErrCtxt
357                         ; loc  <- getSrcSpanM
358                         ; env0 <- tcInitTidyEnv
359                         ; ctxt_msgs <- do_ctxt env0 ctxt 
360                         ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
361                         ; dumpTcRn real_doc }
362
363 dumpTcRn :: SDoc -> TcRn ()
364 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
365                     dflags <- getDOpts ;
366                         liftIO (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
367
368 debugDumpTcRn :: SDoc -> TcRn ()
369 debugDumpTcRn doc | opt_NoDebugOutput = return ()
370                   | otherwise         = dumpTcRn doc
371
372 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
373 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
374 \end{code}
375
376
377 %************************************************************************
378 %*                                                                      *
379                 Typechecker global environment
380 %*                                                                      *
381 %************************************************************************
382
383 \begin{code}
384 getModule :: TcRn Module
385 getModule = do { env <- getGblEnv; return (tcg_mod env) }
386
387 setModule :: Module -> TcRn a -> TcRn a
388 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
389
390 tcIsHsBoot :: TcRn Bool
391 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
392
393 getGlobalRdrEnv :: TcRn GlobalRdrEnv
394 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
395
396 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
397 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
398
399 getImports :: TcRn ImportAvails
400 getImports = do { env <- getGblEnv; return (tcg_imports env) }
401
402 getFixityEnv :: TcRn FixityEnv
403 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
404
405 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
406 extendFixityEnv new_bit
407   = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) -> 
408                 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})           
409
410 getRecFieldEnv :: TcRn RecFieldEnv
411 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
412
413 extendRecFieldEnv :: RecFieldEnv -> RnM a -> RnM a
414 extendRecFieldEnv new_bit
415   = updGblEnv (\env@(TcGblEnv { tcg_field_env = old_env }) -> 
416                 env {tcg_field_env = old_env `plusNameEnv` new_bit})         
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 msg = updCtxt (\ msgs -> msg : msgs)
693
694 -- Helper function for the above
695 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
696 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> 
697                            env { tcl_ctxt = upd ctxt })
698
699 -- Conditionally add an error context
700 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
701 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
702 maybeAddErrCtxt Nothing    thing_inside = thing_inside
703
704 popErrCtxt :: TcM a -> TcM a
705 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
706
707 getInstLoc :: InstOrigin -> TcM InstLoc
708 getInstLoc origin
709   = do { loc <- getSrcSpanM ; env <- getLclEnv ;
710          return (InstLoc origin loc (tcl_ctxt env)) }
711
712 addInstCtxt :: InstLoc -> TcM a -> TcM a
713 -- Add the SrcSpan and context from the first Inst in the list
714 --      (they all have similar locations)
715 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
716   = setSrcSpan src_loc (updCtxt (\_ -> ctxt) thing_inside)
717 \end{code}
718
719     The addErrTc functions add an error message, but do not cause failure.
720     The 'M' variants pass a TidyEnv that has already been used to
721     tidy up the message; we then use it to tidy the context messages
722
723 \begin{code}
724 addErrTc :: Message -> TcM ()
725 addErrTc err_msg = do { env0 <- tcInitTidyEnv
726                       ; addErrTcM (env0, err_msg) }
727
728 addErrsTc :: [Message] -> TcM ()
729 addErrsTc err_msgs = mapM_ addErrTc err_msgs
730
731 addErrTcM :: (TidyEnv, Message) -> TcM ()
732 addErrTcM (tidy_env, err_msg)
733   = do { ctxt <- getErrCtxt ;
734          loc  <- getSrcSpanM ;
735          add_err_tcm tidy_env err_msg loc ctxt }
736 \end{code}
737
738 The failWith functions add an error message and cause failure
739
740 \begin{code}
741 failWithTc :: Message -> TcM a               -- Add an error message and fail
742 failWithTc err_msg 
743   = addErrTc err_msg >> failM
744
745 failWithTcM :: (TidyEnv, Message) -> TcM a   -- Add an error message and fail
746 failWithTcM local_and_msg
747   = addErrTcM local_and_msg >> failM
748
749 checkTc :: Bool -> Message -> TcM ()         -- Check that the boolean is true
750 checkTc True  _   = return ()
751 checkTc False err = failWithTc err
752 \end{code}
753
754         Warnings have no 'M' variant, nor failure
755
756 \begin{code}
757 addWarnTc :: Message -> TcM ()
758 addWarnTc msg = do { env0 <- tcInitTidyEnv 
759                    ; addWarnTcM (env0, msg) }
760
761 addWarnTcM :: (TidyEnv, Message) -> TcM ()
762 addWarnTcM (env0, msg)
763  = do { ctxt <- getErrCtxt ;
764         ctxt_msgs <- do_ctxt env0 ctxt ;
765         addReport (vcat (ptext (sLit "Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
766
767 warnTc :: Bool -> Message -> TcM ()
768 warnTc warn_if_true warn_msg
769   | warn_if_true = addWarnTc warn_msg
770   | otherwise    = return ()
771 \end{code}
772
773 -----------------------------------
774          Tidying
775
776 We initialise the "tidy-env", used for tidying types before printing,
777 by building a reverse map from the in-scope type variables to the
778 OccName that the programmer originally used for them
779
780 \begin{code}
781 tcInitTidyEnv :: TcM TidyEnv
782 tcInitTidyEnv
783   = do  { lcl_env <- getLclEnv
784         ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
785                           | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
786                           , tcIsTyVarTy ty ]
787         ; return (foldl add emptyTidyEnv nm_tv_prs) }
788   where
789     add (env,subst) (name, tyvar)
790         = case tidyOccName env (nameOccName name) of
791             (env', occ') ->  (env', extendVarEnv subst tyvar tyvar')
792                 where
793                   tyvar' = setTyVarName tyvar name'
794                   name'  = tidyNameOcc name occ'
795 \end{code}
796
797 -----------------------------------
798         Other helper functions
799
800 \begin{code}
801 add_err_tcm :: TidyEnv -> Message -> SrcSpan
802             -> [TidyEnv -> TcM (TidyEnv, SDoc)]
803             -> TcM ()
804 add_err_tcm tidy_env err_msg loc ctxt
805  = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
806         addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
807
808 do_ctxt :: TidyEnv -> [TidyEnv -> TcM (TidyEnv, SDoc)] -> TcM [SDoc]
809 do_ctxt _ []
810  = return []
811 do_ctxt tidy_env (c:cs)
812  = do { (tidy_env', m) <- c tidy_env  ;
813         ms             <- do_ctxt tidy_env' cs  ;
814         return (m:ms) }
815
816 ctxt_to_use :: [SDoc] -> [SDoc]
817 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
818                  | otherwise          = take 3 ctxt
819 \end{code}
820
821 debugTc is useful for monadic debugging code
822
823 \begin{code}
824 debugTc :: TcM () -> TcM ()
825 debugTc thing
826  | debugIsOn = thing
827  | otherwise = return ()
828 \end{code}
829
830  %************************************************************************
831 %*                                                                      *
832              Type constraints (the so-called LIE)
833 %*                                                                      *
834 %************************************************************************
835
836 \begin{code}
837 nextDFunIndex :: TcM Int        -- Get the next dfun index
838 nextDFunIndex = do { env <- getGblEnv
839                    ; let dfun_n_var = tcg_dfun_n env
840                    ; n <- readMutVar dfun_n_var
841                    ; writeMutVar dfun_n_var (n+1)
842                    ; return n }
843
844 getLIEVar :: TcM (TcRef LIE)
845 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
846
847 setLIEVar :: TcRef LIE -> TcM a -> TcM a
848 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
849
850 getLIE :: TcM a -> TcM (a, [Inst])
851 -- (getLIE m) runs m, and returns the type constraints it generates
852 getLIE thing_inside
853   = do { lie_var <- newMutVar emptyLIE ;
854          res <- updLclEnv (\ env -> env { tcl_lie = lie_var }) 
855                           thing_inside ;
856          lie <- readMutVar lie_var ;
857          return (res, lieToList lie) }
858
859 extendLIE :: Inst -> TcM ()
860 extendLIE inst
861   = do { lie_var <- getLIEVar ;
862          lie <- readMutVar lie_var ;
863          writeMutVar lie_var (inst `consLIE` lie) }
864
865 extendLIEs :: [Inst] -> TcM ()
866 extendLIEs [] 
867   = return ()
868 extendLIEs insts
869   = do { lie_var <- getLIEVar ;
870          lie <- readMutVar lie_var ;
871          writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
872 \end{code}
873
874 \begin{code}
875 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
876 -- Set the local type envt, but do *not* disturb other fields,
877 -- notably the lie_var
878 setLclTypeEnv lcl_env thing_inside
879   = updLclEnv upd thing_inside
880   where
881     upd env = env { tcl_env = tcl_env lcl_env,
882                     tcl_tyvars = tcl_tyvars lcl_env }
883 \end{code}
884
885
886 %************************************************************************
887 %*                                                                      *
888              Template Haskell context
889 %*                                                                      *
890 %************************************************************************
891
892 \begin{code}
893 recordThUse :: TcM ()
894 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
895
896 keepAliveTc :: Id -> TcM ()     -- Record the name in the keep-alive set
897 keepAliveTc id 
898   | isLocalId id = do { env <- getGblEnv; 
899                       ; updMutVar (tcg_keep env) (`addOneToNameSet` idName id) }
900   | otherwise = return ()
901
902 keepAliveSetTc :: NameSet -> TcM ()     -- Record the name in the keep-alive set
903 keepAliveSetTc ns = do { env <- getGblEnv; 
904                        ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
905
906 getStage :: TcM ThStage
907 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
908
909 setStage :: ThStage -> TcM a -> TcM a 
910 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
911 \end{code}
912
913
914 %************************************************************************
915 %*                                                                      *
916              Stuff for the renamer's local env
917 %*                                                                      *
918 %************************************************************************
919
920 \begin{code}
921 getLocalRdrEnv :: RnM LocalRdrEnv
922 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
923
924 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
925 setLocalRdrEnv rdr_env thing_inside 
926   = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
927 \end{code}
928
929
930 %************************************************************************
931 %*                                                                      *
932              Stuff for interface decls
933 %*                                                                      *
934 %************************************************************************
935
936 \begin{code}
937 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
938 mkIfLclEnv mod loc = IfLclEnv { if_mod     = mod,
939                                 if_loc     = loc,
940                                 if_tv_env  = emptyUFM,
941                                 if_id_env  = emptyUFM }
942
943 initIfaceTcRn :: IfG a -> TcRn a
944 initIfaceTcRn thing_inside
945   = do  { tcg_env <- getGblEnv 
946         ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
947               ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
948         ; setEnvs (if_env, ()) thing_inside }
949
950 initIfaceExtCore :: IfL a -> TcRn a
951 initIfaceExtCore thing_inside
952   = do  { tcg_env <- getGblEnv 
953         ; let { mod = tcg_mod tcg_env
954               ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
955               ; if_env = IfGblEnv { 
956                         if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
957               ; if_lenv = mkIfLclEnv mod doc
958           }
959         ; setEnvs (if_env, if_lenv) thing_inside }
960
961 initIfaceCheck :: HscEnv -> IfG a -> IO a
962 -- Used when checking the up-to-date-ness of the old Iface
963 -- Initialise the environment with no useful info at all
964 initIfaceCheck hsc_env do_this
965  = do let rec_types = case hsc_type_env_var hsc_env of
966                          Just (mod,var) -> Just (mod, readMutVar var)
967                          Nothing        -> Nothing
968           gbl_env = IfGblEnv { if_rec_types = rec_types }
969       initTcRnIf 'i' hsc_env gbl_env () do_this
970
971 initIfaceTc :: ModIface 
972             -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
973 -- Used when type-checking checking an up-to-date interface file
974 -- No type envt from the current module, but we do know the module dependencies
975 initIfaceTc iface do_this
976  = do   { tc_env_var <- newMutVar emptyTypeEnv
977         ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
978               ; if_lenv = mkIfLclEnv mod doc
979            }
980         ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
981     }
982   where
983     mod = mi_module iface
984     doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
985
986 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
987 -- Used when sucking in new Rules in SimplCore
988 -- We have available the type envt of the module being compiled, and we must use it
989 initIfaceRules hsc_env guts do_this
990  = do   { let {
991              type_info = (mg_module guts, return (mg_types guts))
992            ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
993            }
994
995         -- Run the thing; any exceptions just bubble out from here
996         ; initTcRnIf 'i' hsc_env gbl_env () do_this
997     }
998
999 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
1000 initIfaceLcl mod loc_doc thing_inside 
1001   = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1002
1003 getIfModule :: IfL Module
1004 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1005
1006 --------------------
1007 failIfM :: Message -> IfL a
1008 -- The Iface monad doesn't have a place to accumulate errors, so we
1009 -- just fall over fast if one happens; it "shouldnt happen".
1010 -- We use IfL here so that we can get context info out of the local env
1011 failIfM msg
1012   = do  { env <- getLclEnv
1013         ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1014         ; liftIO (printErrs (full_msg defaultErrStyle))
1015         ; failM }
1016
1017 --------------------
1018 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1019 -- Run thing_inside in an interleaved thread.  
1020 -- It shares everything with the parent thread, so this is DANGEROUS.  
1021 --
1022 -- It returns Nothing if the computation fails
1023 -- 
1024 -- It's used for lazily type-checking interface
1025 -- signatures, which is pretty benign
1026
1027 forkM_maybe doc thing_inside
1028  = do { unsafeInterleaveM $
1029         do { traceIf (text "Starting fork {" <+> doc)
1030            ; mb_res <- tryM $
1031                        updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $ 
1032                        thing_inside
1033            ; case mb_res of
1034                 Right r  -> do  { traceIf (text "} ending fork" <+> doc)
1035                                 ; return (Just r) }
1036                 Left exn -> do {
1037
1038                     -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1039                     -- Otherwise we silently discard errors. Errors can legitimately
1040                     -- happen when compiling interface signatures (see tcInterfaceSigs)
1041                       ifOptM Opt_D_dump_if_trace 
1042                              (print_errs (hang (text "forkM failed:" <+> doc)
1043                                              4 (text (show exn))))
1044
1045                     ; traceIf (text "} ending fork (badly)" <+> doc)
1046                     ; return Nothing }
1047         }}
1048   where
1049     print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1050
1051 forkM :: SDoc -> IfL a -> IfL a
1052 forkM doc thing_inside
1053  = do   { mb_res <- forkM_maybe doc thing_inside
1054         ; return (case mb_res of 
1055                         Nothing -> pgmError "Cannot continue after interface file error"
1056                                    -- pprPanic "forkM" doc
1057                         Just r  -> r) }
1058 \end{code}