8 #include "HsVersions.h"
10 import TcRnTypes -- Re-export all
11 import IOEnv -- Re-export all
13 import HsSyn ( emptyLHsBinds )
14 import HscTypes ( HscEnv(..), ModGuts(..), ModIface(..),
15 TyThing, TypeEnv, emptyTypeEnv, HscSource(..), isHsBoot,
16 ExternalPackageState(..), HomePackageTable,
17 Deprecs(..), FixityEnv, FixItem,
18 lookupType, unQualInScope )
19 import Module ( Module, unitModuleEnv )
20 import RdrName ( GlobalRdrEnv, emptyGlobalRdrEnv,
21 LocalRdrEnv, emptyLocalRdrEnv )
22 import Name ( Name, isInternalName )
24 import NameEnv ( extendNameEnvList )
25 import InstEnv ( emptyInstEnv )
27 import VarSet ( emptyVarSet )
28 import VarEnv ( TidyEnv, emptyTidyEnv, emptyVarEnv )
29 import ErrUtils ( Message, Messages, emptyMessages, errorsFound,
30 mkWarnMsg, printErrorsAndWarnings, pprBagOfErrors,
31 mkLocMessage, mkLongErrMsg )
32 import SrcLoc ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
33 import NameEnv ( emptyNameEnv )
34 import NameSet ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
35 import OccName ( emptyOccEnv )
36 import Bag ( emptyBag )
38 import UniqSupply ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
39 import Unique ( Unique )
40 import DynFlags ( DynFlags(..), DynFlag(..), dopt, dopt_set, GhcMode )
41 import StaticFlags ( opt_PprStyle_Debug )
42 import Bag ( snocBag, unionBags, unitBag )
43 import Panic ( showException )
46 import DATA_IOREF ( newIORef, readIORef )
47 import EXCEPTION ( Exception )
52 %************************************************************************
56 %************************************************************************
59 ioToTcRn :: IO r -> TcRn r
68 -> IO (Messages, Maybe r)
69 -- Nothing => error thrown by the thing inside
70 -- (error messages should have been printed already)
72 initTc hsc_env hsc_src mod do_this
73 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
74 tvs_var <- newIORef emptyVarSet ;
75 type_env_var <- newIORef emptyNameEnv ;
76 dfuns_var <- newIORef emptyNameSet ;
77 keep_var <- newIORef emptyNameSet ;
78 th_var <- newIORef False ;
79 dfun_n_var <- newIORef 1 ;
85 tcg_rdr_env = emptyGlobalRdrEnv,
86 tcg_fix_env = emptyNameEnv,
87 tcg_default = Nothing,
88 tcg_type_env = emptyNameEnv,
89 tcg_type_env_var = type_env_var,
90 tcg_inst_env = emptyInstEnv,
91 tcg_inst_uses = dfuns_var,
93 tcg_exports = emptyNameSet,
94 tcg_imports = init_imports,
96 tcg_rn_decls = Nothing,
97 tcg_binds = emptyLHsBinds,
98 tcg_deprecs = NoDeprecs,
102 tcg_dfun_n = dfun_n_var,
107 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
109 tcl_rdr = emptyLocalRdrEnv,
110 tcl_th_ctxt = topStage,
111 tcl_arrow_ctxt = NoArrowCtxt,
112 tcl_env = emptyNameEnv,
113 tcl_tyvars = tvs_var,
114 tcl_lie = panic "initTc:LIE", -- LIE only valid inside a getLIE
115 tcl_gadt = emptyVarEnv
119 -- OK, here's the business end!
120 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
121 do { r <- tryM do_this
123 Right res -> return (Just res)
124 Left _ -> return Nothing } ;
126 -- Collect any error messages
127 msgs <- readIORef errs_var ;
129 let { dflags = hsc_dflags hsc_env
130 ; final_res | errorsFound dflags msgs = Nothing
131 | otherwise = maybe_res } ;
133 return (msgs, final_res)
136 init_imports = emptyImportAvails { imp_env = unitModuleEnv mod emptyNameSet }
137 -- Initialise tcg_imports with an empty set of bindings for
138 -- this module, so that if we see 'module M' in the export
139 -- list, and there are no bindings in M, we don't bleat
140 -- "unknown module M".
142 initTcPrintErrors -- Used from the interactive loop only
147 initTcPrintErrors env mod todo = do
148 (msgs, res) <- initTc env HsSrcFile mod todo
149 printErrorsAndWarnings msgs
152 -- mkImpTypeEnv makes the imported symbol table
153 mkImpTypeEnv :: ExternalPackageState -> HomePackageTable
154 -> Name -> Maybe TyThing
155 mkImpTypeEnv pcs hpt = lookup
158 lookup name | isInternalName name = Nothing
159 | otherwise = lookupType hpt pte name
163 %************************************************************************
167 %************************************************************************
171 initTcRnIf :: Char -- Tag for unique supply
176 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
177 = do { us <- mkSplitUniqSupply uniq_tag ;
178 ; us_var <- newIORef us ;
180 ; let { env = Env { env_top = hsc_env,
183 env_lcl = lcl_env } }
185 ; runIOEnv env thing_inside
189 %************************************************************************
193 %************************************************************************
196 getTopEnv :: TcRnIf gbl lcl HscEnv
197 getTopEnv = do { env <- getEnv; return (env_top env) }
199 getGblEnv :: TcRnIf gbl lcl gbl
200 getGblEnv = do { env <- getEnv; return (env_gbl env) }
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 })
206 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
207 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
209 getLclEnv :: TcRnIf gbl lcl lcl
210 getLclEnv = do { env <- getEnv; return (env_lcl env) }
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 })
216 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
217 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
219 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
220 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
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 })
230 getDOpts :: TcRnIf gbl lcl DynFlags
231 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
233 doptM :: DynFlag -> TcRnIf gbl lcl Bool
234 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
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}} )
240 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
241 ifOptM flag thing_inside = do { b <- doptM flag;
242 if b then thing_inside else return () }
244 getGhciMode :: TcRnIf gbl lcl GhcMode
245 getGhciMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
249 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
250 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
252 getEps :: TcRnIf gbl lcl ExternalPackageState
253 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
255 -- Updating the EPS. This should be an atomic operation.
256 -- Note the delicate 'seq' which forces the EPS before putting it in the
257 -- variable. Otherwise what happens is that we get
258 -- write eps_var (....(unsafeRead eps_var)....)
259 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
260 -- we make the unsafeRead happen before we update the variable.
262 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
264 updateEps upd_fn = do { traceIf (text "updating EPS")
265 ; eps_var <- getEpsVar
266 ; eps <- readMutVar eps_var
267 ; let { (eps', val) = upd_fn eps }
268 ; seq eps' (writeMutVar eps_var eps')
271 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
273 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
274 ; eps_var <- getEpsVar
275 ; eps <- readMutVar eps_var
276 ; let { eps' = upd_fn eps }
277 ; seq eps' (writeMutVar eps_var eps') }
279 getHpt :: TcRnIf gbl lcl HomePackageTable
280 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
282 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
283 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
284 ; return (eps, hsc_HPT env) }
287 %************************************************************************
291 %************************************************************************
294 newUnique :: TcRnIf gbl lcl Unique
295 newUnique = do { us <- newUniqueSupply ;
296 return (uniqFromSupply us) }
298 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
300 = do { env <- getEnv ;
301 let { u_var = env_us env } ;
302 us <- readMutVar u_var ;
303 let { (us1, us2) = splitUniqSupply us } ;
304 writeMutVar u_var us1 ;
309 %************************************************************************
313 %************************************************************************
316 traceTc, traceRn :: SDoc -> TcRn ()
317 traceRn = dumpOptTcRn Opt_D_dump_rn_trace
318 traceTc = dumpOptTcRn Opt_D_dump_tc_trace
319 traceSplice = dumpOptTcRn Opt_D_dump_splices
322 traceIf :: SDoc -> TcRnIf m n ()
323 traceIf = dumpOptIf Opt_D_dump_if_trace
324 traceHiDiffs = dumpOptIf Opt_D_dump_hi_diffs
327 dumpOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
328 dumpOptIf flag doc = ifOptM flag $
329 ioToIOEnv (printForUser stderr alwaysQualify doc)
331 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
332 dumpOptTcRn flag doc = ifOptM flag $ do
335 ; ctxt_msgs <- do_ctxt emptyTidyEnv ctxt
336 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
337 ; dumpTcRn real_doc }
339 dumpTcRn :: SDoc -> TcRn ()
340 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
341 ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
345 %************************************************************************
347 Typechecker global environment
349 %************************************************************************
352 getModule :: TcRn Module
353 getModule = do { env <- getGblEnv; return (tcg_mod env) }
355 tcIsHsBoot :: TcRn Bool
356 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
358 getGlobalRdrEnv :: TcRn GlobalRdrEnv
359 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
361 getImports :: TcRn ImportAvails
362 getImports = do { env <- getGblEnv; return (tcg_imports env) }
364 getFixityEnv :: TcRn FixityEnv
365 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
367 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
368 extendFixityEnv new_bit
369 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
370 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
372 getDefaultTys :: TcRn (Maybe [Type])
373 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
376 %************************************************************************
380 %************************************************************************
383 getSrcSpanM :: TcRn SrcSpan
384 -- Avoid clash with Name.getSrcLoc
385 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
387 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
388 setSrcSpan loc thing_inside
389 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
390 | otherwise = thing_inside -- Don't overwrite useful info with useless
392 addLocM :: (a -> TcM b) -> Located a -> TcM b
393 addLocM fn (L loc a) = setSrcSpan loc $ fn a
395 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
396 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
398 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
399 wrapLocFstM fn (L loc a) =
404 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
405 wrapLocSndM fn (L loc a) =
413 getErrsVar :: TcRn (TcRef Messages)
414 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
416 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
417 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
419 addErr :: Message -> TcRn ()
420 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
422 addLocErr :: Located e -> (e -> Message) -> TcRn ()
423 addLocErr (L loc e) fn = addErrAt loc (fn e)
425 addErrAt :: SrcSpan -> Message -> TcRn ()
426 addErrAt loc msg = addLongErrAt loc msg empty
428 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
429 addLongErrAt loc msg extra
430 = do { errs_var <- getErrsVar ;
431 rdr_env <- getGlobalRdrEnv ;
432 let { err = mkLongErrMsg loc (unQualInScope rdr_env) msg extra } ;
433 (warns, errs) <- readMutVar errs_var ;
434 traceTc (ptext SLIT("Adding error:") <+> \ _ -> pprBagOfErrors (unitBag err)) ;
435 -- Ugh! traceTc is too specific; unitBag is horrible
436 writeMutVar errs_var (warns, errs `snocBag` err) }
438 addErrs :: [(SrcSpan,Message)] -> TcRn ()
439 addErrs msgs = mappM_ add msgs
441 add (loc,msg) = addErrAt loc msg
443 addReport :: Message -> TcRn ()
444 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
446 addReportAt :: SrcSpan -> Message -> TcRn ()
448 = do { errs_var <- getErrsVar ;
449 rdr_env <- getGlobalRdrEnv ;
450 let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
451 (warns, errs) <- readMutVar errs_var ;
452 writeMutVar errs_var (warns `snocBag` warn, errs) }
454 addWarn :: Message -> TcRn ()
455 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
457 addWarnAt :: SrcSpan -> Message -> TcRn ()
458 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
460 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
461 addLocWarn (L loc e) fn = addReportAt loc (fn e)
463 checkErr :: Bool -> Message -> TcRn ()
464 -- Add the error if the bool is False
465 checkErr ok msg = checkM ok (addErr msg)
467 warnIf :: Bool -> Message -> TcRn ()
468 warnIf True msg = addWarn msg
469 warnIf False msg = return ()
471 addMessages :: Messages -> TcRn ()
472 addMessages (m_warns, m_errs)
473 = do { errs_var <- getErrsVar ;
474 (warns, errs) <- readMutVar errs_var ;
475 writeMutVar errs_var (warns `unionBags` m_warns,
476 errs `unionBags` m_errs) }
478 discardWarnings :: TcRn a -> TcRn a
479 -- Ignore warnings inside the thing inside;
480 -- used to ignore-unused-variable warnings inside derived code
481 -- With -dppr-debug, the effects is switched off, so you can still see
482 -- what warnings derived code would give
483 discardWarnings thing_inside
484 | opt_PprStyle_Debug = thing_inside
486 = do { errs_var <- newMutVar emptyMessages
487 ; result <- setErrsVar errs_var thing_inside
488 ; (_warns, errs) <- readMutVar errs_var
489 ; addMessages (emptyBag, errs)
495 try_m :: TcRn r -> TcRn (Either Exception r)
496 -- Does try_m, with a debug-trace on failure
498 = do { mb_r <- tryM thing ;
500 Left exn -> do { traceTc (exn_msg exn); return mb_r }
501 Right r -> return mb_r }
503 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
505 -----------------------
506 recoverM :: TcRn r -- Recovery action; do this if the main one fails
507 -> TcRn r -- Main action: do this first
509 -- Errors in 'thing' are retained
510 recoverM recover thing
511 = do { mb_res <- try_m thing ;
514 Right res -> returnM res }
516 -----------------------
517 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
518 -- (tryTc m) executes m, and returns
519 -- Just r, if m succeeds (returning r)
520 -- Nothing, if m fails
521 -- It also returns all the errors and warnings accumulated by m
522 -- It always succeeds (never raises an exception)
524 = do { errs_var <- newMutVar emptyMessages ;
525 res <- try_m (setErrsVar errs_var m) ;
526 msgs <- readMutVar errs_var ;
527 return (msgs, case res of
529 Right val -> Just val)
530 -- The exception is always the IOEnv built-in
531 -- in exception; see IOEnv.failM
534 -----------------------
535 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
536 -- Run the thing, returning
537 -- Just r, if m succceeds with no error messages
538 -- Nothing, if m fails, or if it succeeds but has error messages
539 -- Either way, the messages are returned; even in the Just case
540 -- there might be warnings
542 = do { (msgs, res) <- tryTc thing
544 ; let errs_found = errorsFound dflags msgs
545 ; return (msgs, case res of
547 Just val | errs_found -> Nothing
548 | otherwise -> Just val)
551 -----------------------
552 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
553 -- Just like tryTcErrs, except that it ensures that the LIE
554 -- for the thing is propagated only if there are no errors
555 -- Hence it's restricted to the type-check monad
556 tryTcLIE thing_inside
557 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
559 Nothing -> return (msgs, Nothing)
560 Just val -> do { extendLIEs lie; return (msgs, Just val) }
563 -----------------------
564 tryTcLIE_ :: TcM r -> TcM r -> TcM r
565 -- (tryTcLIE_ r m) tries m;
566 -- if m succeeds with no error messages, it's the answer
567 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
568 tryTcLIE_ recover main
569 = do { (msgs, mb_res) <- tryTcLIE main
571 Just val -> do { addMessages msgs -- There might be warnings
573 Nothing -> recover -- Discard all msgs
576 -----------------------
577 checkNoErrs :: TcM r -> TcM r
578 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
579 -- If m fails then (checkNoErrsTc m) fails.
580 -- If m succeeds, it checks whether m generated any errors messages
581 -- (it might have recovered internally)
582 -- If so, it fails too.
583 -- Regardless, any errors generated by m are propagated to the enclosing context.
585 = do { (msgs, mb_res) <- tryTcLIE main
589 Just val -> return val
592 ifErrsM :: TcRn r -> TcRn r -> TcRn r
593 -- ifErrsM bale_out main
594 -- does 'bale_out' if there are errors in errors collection
595 -- otherwise does 'main'
596 ifErrsM bale_out normal
597 = do { errs_var <- getErrsVar ;
598 msgs <- readMutVar errs_var ;
600 if errorsFound dflags msgs then
605 failIfErrsM :: TcRn ()
606 -- Useful to avoid error cascades
607 failIfErrsM = ifErrsM failM (return ())
611 %************************************************************************
613 Context management and error message generation
616 %************************************************************************
619 getErrCtxt :: TcM ErrCtxt
620 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
622 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
623 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
625 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
626 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
628 addErrCtxt :: Message -> TcM a -> TcM a
629 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
631 -- Helper function for the above
632 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
633 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
634 env { tcl_ctxt = upd ctxt })
636 -- Conditionally add an error context
637 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
638 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
639 maybeAddErrCtxt Nothing thing_inside = thing_inside
641 popErrCtxt :: TcM a -> TcM a
642 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
644 getInstLoc :: InstOrigin -> TcM InstLoc
646 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
647 return (InstLoc origin loc (tcl_ctxt env)) }
649 addInstCtxt :: InstLoc -> TcM a -> TcM a
650 -- Add the SrcSpan and context from the first Inst in the list
651 -- (they all have similar locations)
652 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
653 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
656 The addErrTc functions add an error message, but do not cause failure.
657 The 'M' variants pass a TidyEnv that has already been used to
658 tidy up the message; we then use it to tidy the context messages
661 addErrTc :: Message -> TcM ()
662 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
664 addErrsTc :: [Message] -> TcM ()
665 addErrsTc err_msgs = mappM_ addErrTc err_msgs
667 addErrTcM :: (TidyEnv, Message) -> TcM ()
668 addErrTcM (tidy_env, err_msg)
669 = do { ctxt <- getErrCtxt ;
671 add_err_tcm tidy_env err_msg loc ctxt }
674 The failWith functions add an error message and cause failure
677 failWithTc :: Message -> TcM a -- Add an error message and fail
679 = addErrTc err_msg >> failM
681 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
682 failWithTcM local_and_msg
683 = addErrTcM local_and_msg >> failM
685 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
686 checkTc True err = returnM ()
687 checkTc False err = failWithTc err
690 Warnings have no 'M' variant, nor failure
693 addWarnTc :: Message -> TcM ()
695 = do { ctxt <- getErrCtxt ;
696 ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
697 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
699 warnTc :: Bool -> Message -> TcM ()
700 warnTc warn_if_true warn_msg
701 | warn_if_true = addWarnTc warn_msg
702 | otherwise = return ()
708 add_err_tcm tidy_env err_msg loc ctxt
709 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
710 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
714 do_ctxt tidy_env (c:cs)
715 = do { (tidy_env', m) <- c tidy_env ;
716 ms <- do_ctxt tidy_env' cs ;
719 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
720 | otherwise = take 3 ctxt
723 debugTc is useful for monadi debugging code
726 debugTc :: TcM () -> TcM ()
728 debugTc thing = thing
730 debugTc thing = return ()
734 %************************************************************************
736 Type constraints (the so-called LIE)
738 %************************************************************************
741 nextDFunIndex :: TcM Int -- Get the next dfun index
742 nextDFunIndex = do { env <- getGblEnv
743 ; let dfun_n_var = tcg_dfun_n env
744 ; n <- readMutVar dfun_n_var
745 ; writeMutVar dfun_n_var (n+1)
748 getLIEVar :: TcM (TcRef LIE)
749 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
751 setLIEVar :: TcRef LIE -> TcM a -> TcM a
752 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
754 getLIE :: TcM a -> TcM (a, [Inst])
755 -- (getLIE m) runs m, and returns the type constraints it generates
757 = do { lie_var <- newMutVar emptyLIE ;
758 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
760 lie <- readMutVar lie_var ;
761 return (res, lieToList lie) }
763 extendLIE :: Inst -> TcM ()
765 = do { lie_var <- getLIEVar ;
766 lie <- readMutVar lie_var ;
767 writeMutVar lie_var (inst `consLIE` lie) }
769 extendLIEs :: [Inst] -> TcM ()
773 = do { lie_var <- getLIEVar ;
774 lie <- readMutVar lie_var ;
775 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
779 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
780 -- Set the local type envt, but do *not* disturb other fields,
781 -- notably the lie_var
782 setLclTypeEnv lcl_env thing_inside
783 = updLclEnv upd thing_inside
785 upd env = env { tcl_env = tcl_env lcl_env,
786 tcl_tyvars = tcl_tyvars lcl_env }
790 %************************************************************************
792 Template Haskell context
794 %************************************************************************
797 recordThUse :: TcM ()
798 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
800 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
801 keepAliveTc n = do { env <- getGblEnv;
802 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
804 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
805 keepAliveSetTc ns = do { env <- getGblEnv;
806 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
808 getStage :: TcM ThStage
809 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
811 setStage :: ThStage -> TcM a -> TcM a
812 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
816 %************************************************************************
818 Stuff for the renamer's local env
820 %************************************************************************
823 getLocalRdrEnv :: RnM LocalRdrEnv
824 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
826 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
827 setLocalRdrEnv rdr_env thing_inside
828 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
832 %************************************************************************
834 Stuff for interface decls
836 %************************************************************************
839 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
840 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
842 if_tv_env = emptyOccEnv,
843 if_id_env = emptyOccEnv }
845 initIfaceTcRn :: IfG a -> TcRn a
846 initIfaceTcRn thing_inside
847 = do { tcg_env <- getGblEnv
848 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
849 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
850 ; setEnvs (if_env, ()) thing_inside }
852 initIfaceExtCore :: IfL a -> TcRn a
853 initIfaceExtCore thing_inside
854 = do { tcg_env <- getGblEnv
855 ; let { mod = tcg_mod tcg_env
856 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
857 ; if_env = IfGblEnv {
858 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
859 ; if_lenv = mkIfLclEnv mod doc
861 ; setEnvs (if_env, if_lenv) thing_inside }
863 initIfaceCheck :: HscEnv -> IfG a -> IO a
864 -- Used when checking the up-to-date-ness of the old Iface
865 -- Initialise the environment with no useful info at all
866 initIfaceCheck hsc_env do_this
867 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
868 ; initTcRnIf 'i' hsc_env gbl_env () do_this
871 initIfaceTc :: ModIface
872 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
873 -- Used when type-checking checking an up-to-date interface file
874 -- No type envt from the current module, but we do know the module dependencies
875 initIfaceTc iface do_this
876 = do { tc_env_var <- newMutVar emptyTypeEnv
877 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
878 ; if_lenv = mkIfLclEnv mod doc
880 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
883 mod = mi_module iface
884 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
886 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
887 -- Used when sucking in new Rules in SimplCore
888 -- We have available the type envt of the module being compiled, and we must use it
889 initIfaceRules hsc_env guts do_this
891 type_info = (mg_module guts, return (mg_types guts))
892 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
895 -- Run the thing; any exceptions just bubble out from here
896 ; initTcRnIf 'i' hsc_env gbl_env () do_this
899 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
900 initIfaceLcl mod loc_doc thing_inside
901 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
903 getIfModule :: IfL Module
904 getIfModule = do { env <- getLclEnv; return (if_mod env) }
907 failIfM :: Message -> IfL a
908 -- The Iface monad doesn't have a place to accumulate errors, so we
909 -- just fall over fast if one happens; it "shouldnt happen".
910 -- We use IfL here so that we can get context info out of the local env
912 = do { env <- getLclEnv
913 ; let full_msg = if_loc env $$ nest 2 msg
914 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
918 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
919 -- Run thing_inside in an interleaved thread.
920 -- It shares everything with the parent thread, so this is DANGEROUS.
922 -- It returns Nothing if the computation fails
924 -- It's used for lazily type-checking interface
925 -- signatures, which is pretty benign
927 forkM_maybe doc thing_inside
928 = do { unsafeInterleaveM $
929 do { traceIf (text "Starting fork {" <+> doc)
930 ; mb_res <- tryM thing_inside ;
932 Right r -> do { traceIf (text "} ending fork" <+> doc)
936 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
937 -- Otherwise we silently discard errors. Errors can legitimately
938 -- happen when compiling interface signatures (see tcInterfaceSigs)
939 ifOptM Opt_D_dump_if_trace
940 (print_errs (hang (text "forkM failed:" <+> doc)
941 4 (text (show exn))))
943 ; traceIf (text "} ending fork (badly)" <+> doc)
947 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
949 forkM :: SDoc -> IfL a -> IfL a
950 forkM doc thing_inside
951 = do { mb_res <- forkM_maybe doc thing_inside
952 ; return (case mb_res of
953 Nothing -> pprPanic "forkM" doc
957 %************************************************************************
961 %************************************************************************
964 getTypeRefinement :: TcM GadtRefinement
965 getTypeRefinement = do { lcl_env <- getLclEnv; return (tcl_gadt lcl_env) }
967 setTypeRefinement :: GadtRefinement -> TcM a -> TcM a
968 setTypeRefinement gadt = updLclEnv (\env -> env { tcl_gadt = gadt })