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,
16 ExternalPackageState(..), HomePackageTable,
17 ModDetails(..), HomeModInfo(..),
18 Deprecs(..), FixityEnv, FixItem,
19 GhciMode, lookupType, unQualInScope )
20 import Module ( Module, ModuleName, unitModuleEnv, foldModuleEnv )
21 import RdrName ( GlobalRdrEnv, emptyGlobalRdrEnv,
22 LocalRdrEnv, emptyLocalRdrEnv )
23 import Name ( Name, isInternalName )
25 import NameEnv ( extendNameEnvList )
26 import InstEnv ( InstEnv, emptyInstEnv, extendInstEnv )
28 import VarSet ( emptyVarSet )
29 import VarEnv ( TidyEnv, emptyTidyEnv, emptyVarEnv )
30 import ErrUtils ( Message, Messages, emptyMessages, errorsFound,
31 mkWarnMsg, printErrorsAndWarnings,
32 mkLocMessage, mkLongErrMsg )
33 import SrcLoc ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
34 import NameEnv ( emptyNameEnv )
35 import NameSet ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
36 import OccName ( emptyOccEnv )
37 import Module ( moduleName )
38 import Bag ( emptyBag )
40 import UniqSupply ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
41 import Unique ( Unique )
42 import CmdLineOpts ( DynFlags, DynFlag(..), dopt, opt_PprStyle_Debug, dopt_set )
43 import Bag ( snocBag, unionBags )
44 import Panic ( showException )
46 import Maybe ( isJust )
48 import DATA_IOREF ( newIORef, readIORef )
49 import EXCEPTION ( Exception )
54 %************************************************************************
58 %************************************************************************
61 ioToTcRn :: IO r -> TcRn r
69 -> IO (Messages, Maybe r)
70 -- Nothing => error thrown by the thing inside
71 -- (error messages should have been printed already)
73 initTc hsc_env mod do_this
74 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
75 tvs_var <- newIORef emptyVarSet ;
76 type_env_var <- newIORef emptyNameEnv ;
77 dfuns_var <- newIORef emptyNameSet ;
78 keep_var <- newIORef emptyNameSet ;
79 th_var <- newIORef False ;
84 tcg_rdr_env = emptyGlobalRdrEnv,
85 tcg_fix_env = emptyNameEnv,
86 tcg_default = Nothing,
87 tcg_type_env = emptyNameEnv,
88 tcg_type_env_var = type_env_var,
89 tcg_inst_env = mkImpInstEnv hsc_env,
90 tcg_inst_uses = dfuns_var,
92 tcg_exports = emptyNameSet,
93 tcg_imports = init_imports,
95 tcg_binds = emptyLHsBinds,
96 tcg_deprecs = NoDeprecs,
104 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
106 tcl_rdr = emptyLocalRdrEnv,
107 tcl_th_ctxt = topStage,
108 tcl_arrow_ctxt = topArrowCtxt,
109 tcl_env = emptyNameEnv,
110 tcl_tyvars = tvs_var,
111 tcl_lie = panic "initTc:LIE", -- LIE only valid inside a getLIE
112 tcl_gadt = emptyVarEnv
116 -- OK, here's the business end!
117 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
118 do { r <- tryM do_this
120 Right res -> return (Just res)
121 Left _ -> return Nothing } ;
123 -- Collect any error messages
124 msgs <- readIORef errs_var ;
126 let { dflags = hsc_dflags hsc_env
127 ; final_res | errorsFound dflags msgs = Nothing
128 | otherwise = maybe_res } ;
130 return (msgs, final_res)
133 init_imports = emptyImportAvails { imp_qual = unitModuleEnv mod emptyAvailEnv }
134 -- Initialise tcg_imports with an empty set of bindings for
135 -- this module, so that if we see 'module M' in the export
136 -- list, and there are no bindings in M, we don't bleat
137 -- "unknown module M".
144 initTcPrintErrors env mod todo = do
145 (msgs, res) <- initTc env mod todo
146 printErrorsAndWarnings msgs
149 mkImpInstEnv :: HscEnv -> InstEnv
150 -- At the moment we (wrongly) build an instance environment from all the
151 -- home-package modules we have already compiled.
152 -- We should really only get instances from modules below us in the
153 -- module import tree.
154 mkImpInstEnv (HscEnv {hsc_dflags = dflags, hsc_HPT = hpt})
155 = foldModuleEnv (add . md_insts . hm_details) emptyInstEnv hpt
157 add dfuns inst_env = foldl extendInstEnv inst_env dfuns
159 -- mkImpTypeEnv makes the imported symbol table
160 mkImpTypeEnv :: ExternalPackageState -> HomePackageTable
161 -> Name -> Maybe TyThing
162 mkImpTypeEnv pcs hpt = lookup
165 lookup name | isInternalName name = Nothing
166 | otherwise = lookupType hpt pte name
170 %************************************************************************
174 %************************************************************************
178 initTcRnIf :: Char -- Tag for unique supply
183 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
184 = do { us <- mkSplitUniqSupply uniq_tag ;
185 ; us_var <- newIORef us ;
187 ; let { env = Env { env_top = hsc_env,
190 env_lcl = lcl_env } }
192 ; runIOEnv env thing_inside
196 %************************************************************************
200 %************************************************************************
203 getTopEnv :: TcRnIf gbl lcl HscEnv
204 getTopEnv = do { env <- getEnv; return (env_top env) }
206 getGblEnv :: TcRnIf gbl lcl gbl
207 getGblEnv = do { env <- getEnv; return (env_gbl env) }
209 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
210 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
211 env { env_gbl = upd gbl })
213 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
214 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
216 getLclEnv :: TcRnIf gbl lcl lcl
217 getLclEnv = do { env <- getEnv; return (env_lcl env) }
219 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
220 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
221 env { env_lcl = upd lcl })
223 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
224 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
226 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
227 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
229 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
230 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
237 getDOpts :: TcRnIf gbl lcl DynFlags
238 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
240 doptM :: DynFlag -> TcRnIf gbl lcl Bool
241 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
243 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
244 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
245 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
247 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
248 ifOptM flag thing_inside = do { b <- doptM flag;
249 if b then thing_inside else return () }
251 getGhciMode :: TcRnIf gbl lcl GhciMode
252 getGhciMode = do { env <- getTopEnv; return (hsc_mode env) }
256 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
257 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
259 getEps :: TcRnIf gbl lcl ExternalPackageState
260 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
262 -- Updating the EPS. This should be an atomic operation.
263 -- Note the delicate 'seq' which forces the EPS before putting it in the
264 -- variable. Otherwise what happens is that we get
265 -- write eps_var (....(unsafeRead eps_var)....)
266 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
267 -- we make the unsafeRead happen before we update the variable.
269 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
271 updateEps upd_fn = do { traceIf (text "updating EPS")
272 ; eps_var <- getEpsVar
273 ; eps <- readMutVar eps_var
274 ; let { (eps', val) = upd_fn eps }
275 ; seq eps' (writeMutVar eps_var eps')
278 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
280 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
281 ; eps_var <- getEpsVar
282 ; eps <- readMutVar eps_var
283 ; let { eps' = upd_fn eps }
284 ; seq eps' (writeMutVar eps_var eps') }
286 getHpt :: TcRnIf gbl lcl HomePackageTable
287 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
289 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
290 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
291 ; return (eps, hsc_HPT env) }
294 %************************************************************************
298 %************************************************************************
301 newUnique :: TcRnIf gbl lcl Unique
302 newUnique = do { us <- newUniqueSupply ;
303 return (uniqFromSupply us) }
305 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
307 = do { env <- getEnv ;
308 let { u_var = env_us env } ;
309 us <- readMutVar u_var ;
310 let { (us1, us2) = splitUniqSupply us } ;
311 writeMutVar u_var us1 ;
316 %************************************************************************
320 %************************************************************************
323 traceTc, traceRn :: SDoc -> TcRn ()
324 traceRn = dumpOptTcRn Opt_D_dump_rn_trace
325 traceTc = dumpOptTcRn Opt_D_dump_tc_trace
326 traceSplice = dumpOptTcRn Opt_D_dump_splices
329 traceIf :: SDoc -> TcRnIf m n ()
330 traceIf = dumpOptIf Opt_D_dump_if_trace
331 traceHiDiffs = dumpOptIf Opt_D_dump_hi_diffs
334 dumpOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
335 dumpOptIf flag doc = ifOptM flag $
336 ioToIOEnv (printForUser stderr alwaysQualify doc)
338 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
339 dumpOptTcRn flag doc = ifOptM flag $ do
342 ; ctxt_msgs <- do_ctxt emptyTidyEnv ctxt
343 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
344 ; dumpTcRn real_doc }
346 dumpTcRn :: SDoc -> TcRn ()
347 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
348 ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
352 %************************************************************************
354 Typechecker global environment
356 %************************************************************************
359 getModule :: TcRn Module
360 getModule = do { env <- getGblEnv; return (tcg_mod env) }
362 getGlobalRdrEnv :: TcRn GlobalRdrEnv
363 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
365 getImports :: TcRn ImportAvails
366 getImports = do { env <- getGblEnv; return (tcg_imports env) }
368 getFixityEnv :: TcRn FixityEnv
369 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
371 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
372 extendFixityEnv new_bit
373 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
374 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
376 getDefaultTys :: TcRn (Maybe [Type])
377 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
380 %************************************************************************
384 %************************************************************************
387 getSrcSpanM :: TcRn SrcSpan
388 -- Avoid clash with Name.getSrcLoc
389 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
391 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
392 setSrcSpan loc thing_inside
393 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
394 | otherwise = thing_inside -- Don't overwrite useful info with useless
396 addLocM :: (a -> TcM b) -> Located a -> TcM b
397 addLocM fn (L loc a) = setSrcSpan loc $ fn a
399 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
400 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
402 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
403 wrapLocFstM fn (L loc a) =
408 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
409 wrapLocSndM fn (L loc a) =
417 getErrsVar :: TcRn (TcRef Messages)
418 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
420 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
421 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
423 addErr :: Message -> TcRn ()
424 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
426 addLocErr :: Located e -> (e -> Message) -> TcRn ()
427 addLocErr (L loc e) fn = addErrAt loc (fn e)
429 addErrAt :: SrcSpan -> Message -> TcRn ()
430 addErrAt loc msg = addLongErrAt loc msg empty
432 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
433 addLongErrAt loc msg extra
434 = do { errs_var <- getErrsVar ;
435 rdr_env <- getGlobalRdrEnv ;
436 let { err = mkLongErrMsg loc (unQualInScope rdr_env) msg extra } ;
437 (warns, errs) <- readMutVar errs_var ;
438 writeMutVar errs_var (warns, errs `snocBag` err) }
440 addErrs :: [(SrcSpan,Message)] -> TcRn ()
441 addErrs msgs = mappM_ add msgs
443 add (loc,msg) = addErrAt loc msg
445 addReport :: Message -> TcRn ()
446 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
448 addReportAt :: SrcSpan -> Message -> TcRn ()
450 = do { errs_var <- getErrsVar ;
451 rdr_env <- getGlobalRdrEnv ;
452 let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
453 (warns, errs) <- readMutVar errs_var ;
454 writeMutVar errs_var (warns `snocBag` warn, errs) }
456 addWarn :: Message -> TcRn ()
457 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
459 addWarnAt :: SrcSpan -> Message -> TcRn ()
460 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
462 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
463 addLocWarn (L loc e) fn = addReportAt loc (fn e)
465 checkErr :: Bool -> Message -> TcRn ()
466 -- Add the error if the bool is False
467 checkErr ok msg = checkM ok (addErr msg)
469 warnIf :: Bool -> Message -> TcRn ()
470 warnIf True msg = addWarn msg
471 warnIf False msg = return ()
473 addMessages :: Messages -> TcRn ()
474 addMessages (m_warns, m_errs)
475 = do { errs_var <- getErrsVar ;
476 (warns, errs) <- readMutVar errs_var ;
477 writeMutVar errs_var (warns `unionBags` m_warns,
478 errs `unionBags` m_errs) }
480 discardWarnings :: TcRn a -> TcRn a
481 -- Ignore warnings inside the thing inside;
482 -- used to ignore-unused-variable warnings inside derived code
483 -- With -dppr-debug, the effects is switched off, so you can still see
484 -- what warnings derived code would give
485 discardWarnings thing_inside
486 | opt_PprStyle_Debug = thing_inside
488 = do { errs_var <- newMutVar emptyMessages
489 ; result <- setErrsVar errs_var thing_inside
490 ; (_warns, errs) <- readMutVar errs_var
491 ; addMessages (emptyBag, errs)
497 recoverM :: TcRn r -- Recovery action; do this if the main one fails
498 -> TcRn r -- Main action: do this first
500 recoverM recover thing
501 = do { mb_res <- try_m thing ;
504 Right res -> returnM res }
506 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
507 -- (tryTc m) executes m, and returns
508 -- Just r, if m succeeds (returning r) and caused no errors
509 -- Nothing, if m fails, or caused errors
510 -- It also returns all the errors accumulated by m
511 -- (even in the Just case, there might be warnings)
513 -- It always succeeds (never raises an exception)
515 = do { errs_var <- newMutVar emptyMessages ;
517 mb_r <- try_m (setErrsVar errs_var m) ;
519 new_errs <- readMutVar errs_var ;
526 Right r | errorsFound dflags new_errs -> Nothing
527 | otherwise -> Just r)
530 try_m :: TcRn r -> TcRn (Either Exception r)
531 -- Does try_m, with a debug-trace on failure
533 = do { mb_r <- tryM thing ;
535 Left exn -> do { traceTc (exn_msg exn); return mb_r }
536 Right r -> return mb_r }
538 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
540 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
541 -- Just like tryTc, except that it ensures that the LIE
542 -- for the thing is propagated only if there are no errors
543 -- Hence it's restricted to the type-check monad
544 tryTcLIE thing_inside
545 = do { ((errs, mb_r), lie) <- getLIE (tryTc thing_inside) ;
546 ifM (isJust mb_r) (extendLIEs lie) ;
547 return (errs, mb_r) }
549 tryTcLIE_ :: TcM r -> TcM r -> TcM r
550 -- (tryTcLIE_ r m) tries m; if it succeeds it returns it,
551 -- otherwise it returns r. Any error messages added by m are discarded,
552 -- whether or not m succeeds.
553 tryTcLIE_ recover main
554 = do { (_msgs, mb_res) <- tryTcLIE main ;
556 Just res -> return res
559 checkNoErrs :: TcM r -> TcM r
560 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
561 -- If m fails then (checkNoErrsTc m) fails.
562 -- If m succeeds, it checks whether m generated any errors messages
563 -- (it might have recovered internally)
564 -- If so, it fails too.
565 -- Regardless, any errors generated by m are propagated to the enclosing context.
567 = do { (msgs, mb_res) <- tryTcLIE main ;
574 ifErrsM :: TcRn r -> TcRn r -> TcRn r
575 -- ifErrsM bale_out main
576 -- does 'bale_out' if there are errors in errors collection
577 -- otherwise does 'main'
578 ifErrsM bale_out normal
579 = do { errs_var <- getErrsVar ;
580 msgs <- readMutVar errs_var ;
582 if errorsFound dflags msgs then
587 failIfErrsM :: TcRn ()
588 -- Useful to avoid error cascades
589 failIfErrsM = ifErrsM failM (return ())
593 %************************************************************************
595 Context management and error message generation
598 %************************************************************************
601 getErrCtxt :: TcM ErrCtxt
602 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
604 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
605 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
607 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
608 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
610 addErrCtxt :: Message -> TcM a -> TcM a
611 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
613 -- Helper function for the above
614 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
615 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
616 env { tcl_ctxt = upd ctxt })
618 -- Conditionally add an error context
619 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
620 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
621 maybeAddErrCtxt Nothing thing_inside = thing_inside
623 popErrCtxt :: TcM a -> TcM a
624 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
626 getInstLoc :: InstOrigin -> TcM InstLoc
628 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
629 return (InstLoc origin loc (tcl_ctxt env)) }
631 addInstCtxt :: InstLoc -> TcM a -> TcM a
632 -- Add the SrcSpan and context from the first Inst in the list
633 -- (they all have similar locations)
634 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
635 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
638 The addErrTc functions add an error message, but do not cause failure.
639 The 'M' variants pass a TidyEnv that has already been used to
640 tidy up the message; we then use it to tidy the context messages
643 addErrTc :: Message -> TcM ()
644 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
646 addErrsTc :: [Message] -> TcM ()
647 addErrsTc err_msgs = mappM_ addErrTc err_msgs
649 addErrTcM :: (TidyEnv, Message) -> TcM ()
650 addErrTcM (tidy_env, err_msg)
651 = do { ctxt <- getErrCtxt ;
653 add_err_tcm tidy_env err_msg loc ctxt }
656 The failWith functions add an error message and cause failure
659 failWithTc :: Message -> TcM a -- Add an error message and fail
661 = addErrTc err_msg >> failM
663 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
664 failWithTcM local_and_msg
665 = addErrTcM local_and_msg >> failM
667 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
668 checkTc True err = returnM ()
669 checkTc False err = failWithTc err
672 Warnings have no 'M' variant, nor failure
675 addWarnTc :: Message -> TcM ()
677 = do { ctxt <- getErrCtxt ;
678 ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
679 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
681 warnTc :: Bool -> Message -> TcM ()
682 warnTc warn_if_true warn_msg
683 | warn_if_true = addWarnTc warn_msg
684 | otherwise = return ()
690 add_err_tcm tidy_env err_msg loc ctxt
691 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
692 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
696 do_ctxt tidy_env (c:cs)
697 = do { (tidy_env', m) <- c tidy_env ;
698 ms <- do_ctxt tidy_env' cs ;
701 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
702 | otherwise = take 3 ctxt
705 debugTc is useful for monadi debugging code
708 debugTc :: TcM () -> TcM ()
710 debugTc thing = thing
712 debugTc thing = return ()
716 %************************************************************************
718 Type constraints (the so-called LIE)
720 %************************************************************************
723 getLIEVar :: TcM (TcRef LIE)
724 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
726 setLIEVar :: TcRef LIE -> TcM a -> TcM a
727 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
729 getLIE :: TcM a -> TcM (a, [Inst])
730 -- (getLIE m) runs m, and returns the type constraints it generates
732 = do { lie_var <- newMutVar emptyLIE ;
733 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
735 lie <- readMutVar lie_var ;
736 return (res, lieToList lie) }
738 extendLIE :: Inst -> TcM ()
740 = do { lie_var <- getLIEVar ;
741 lie <- readMutVar lie_var ;
742 writeMutVar lie_var (inst `consLIE` lie) }
744 extendLIEs :: [Inst] -> TcM ()
748 = do { lie_var <- getLIEVar ;
749 lie <- readMutVar lie_var ;
750 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
754 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
755 -- Set the local type envt, but do *not* disturb other fields,
756 -- notably the lie_var
757 setLclTypeEnv lcl_env thing_inside
758 = updLclEnv upd thing_inside
760 upd env = env { tcl_env = tcl_env lcl_env,
761 tcl_tyvars = tcl_tyvars lcl_env }
765 %************************************************************************
767 Template Haskell context
769 %************************************************************************
772 recordThUse :: TcM ()
773 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
775 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
776 keepAliveTc n = do { env <- getGblEnv;
777 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
779 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
780 keepAliveSetTc ns = do { env <- getGblEnv;
781 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
783 getStage :: TcM ThStage
784 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
786 setStage :: ThStage -> TcM a -> TcM a
787 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
791 %************************************************************************
795 %************************************************************************
798 popArrowBinders :: TcM a -> TcM a -- Move to the left of a (-<); see comments in TcRnTypes
800 = updLclEnv (\ env -> env { tcl_arrow_ctxt = pop (tcl_arrow_ctxt env) })
802 pop (ArrCtxt {proc_level = curr_lvl, proc_banned = banned})
803 = ASSERT( not (curr_lvl `elem` banned) )
804 ArrCtxt {proc_level = curr_lvl, proc_banned = curr_lvl : banned}
806 getBannedProcLevels :: TcM [ProcLevel]
807 = do { env <- getLclEnv; return (proc_banned (tcl_arrow_ctxt env)) }
809 incProcLevel :: TcM a -> TcM a
811 = updLclEnv (\ env -> env { tcl_arrow_ctxt = inc (tcl_arrow_ctxt env) })
813 inc ctxt = ctxt { proc_level = proc_level ctxt + 1 }
817 %************************************************************************
819 Stuff for the renamer's local env
821 %************************************************************************
824 getLocalRdrEnv :: RnM LocalRdrEnv
825 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
827 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
828 setLocalRdrEnv rdr_env thing_inside
829 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
833 %************************************************************************
835 Stuff for interface decls
837 %************************************************************************
840 initIfaceTcRn :: IfG a -> TcRn a
841 initIfaceTcRn thing_inside
842 = do { tcg_env <- getGblEnv
843 ; let { if_env = IfGblEnv {
844 if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
845 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
846 ; setEnvs (if_env, ()) thing_inside }
848 initIfaceExtCore :: IfL a -> TcRn a
849 initIfaceExtCore thing_inside
850 = do { tcg_env <- getGblEnv
851 ; let { mod = tcg_mod tcg_env
852 ; if_env = IfGblEnv {
853 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
854 ; if_lenv = IfLclEnv { if_mod = moduleName mod,
855 if_tv_env = emptyOccEnv,
856 if_id_env = emptyOccEnv }
858 ; setEnvs (if_env, if_lenv) thing_inside }
860 initIfaceCheck :: HscEnv -> IfG a -> IO a
861 -- Used when checking the up-to-date-ness of the old Iface
862 -- Initialise the environment with no useful info at all
863 initIfaceCheck hsc_env do_this
864 = do { let { gbl_env = IfGblEnv { if_rec_types = Nothing } ;
866 ; initTcRnIf 'i' hsc_env gbl_env () do_this
869 initIfaceTc :: HscEnv -> ModIface
870 -> (TcRef TypeEnv -> IfL a) -> IO a
871 -- Used when type-checking checking an up-to-date interface file
872 -- No type envt from the current module, but we do know the module dependencies
873 initIfaceTc hsc_env iface do_this
874 = do { tc_env_var <- newIORef emptyTypeEnv
875 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
876 ; if_lenv = IfLclEnv { if_mod = moduleName mod,
877 if_tv_env = emptyOccEnv,
878 if_id_env = emptyOccEnv }
880 ; initTcRnIf 'i' hsc_env gbl_env if_lenv (do_this tc_env_var)
883 mod = mi_module iface
885 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
886 -- Used when sucking in new Rules in SimplCore
887 -- We have available the type envt of the module being compiled, and we must use it
888 initIfaceRules hsc_env guts do_this
890 type_info = (mg_module guts, return (mg_types guts))
891 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
894 -- Run the thing; any exceptions just bubble out from here
895 ; initTcRnIf 'i' hsc_env gbl_env () do_this
898 initIfaceLcl :: ModuleName -> IfL a -> IfM lcl a
899 initIfaceLcl mod thing_inside
900 = setLclEnv (IfLclEnv { if_mod = mod,
901 if_tv_env = emptyOccEnv,
902 if_id_env = emptyOccEnv })
907 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
908 -- Run thing_inside in an interleaved thread.
909 -- It shares everything with the parent thread, so this is DANGEROUS.
911 -- It returns Nothing if the computation fails
913 -- It's used for lazily type-checking interface
914 -- signatures, which is pretty benign
916 forkM_maybe doc thing_inside
917 = do { unsafeInterleaveM $
918 do { traceIf (text "Starting fork {" <+> doc)
919 ; mb_res <- tryM thing_inside ;
921 Right r -> do { traceIf (text "} ending fork" <+> doc)
925 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
926 -- Otherwise we silently discard errors. Errors can legitimately
927 -- happen when compiling interface signatures (see tcInterfaceSigs)
928 ifOptM Opt_D_dump_if_trace
929 (print_errs (hang (text "forkM failed:" <+> doc)
930 4 (text (show exn))))
932 ; traceIf (text "} ending fork (badly)" <+> doc)
936 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
938 forkM :: SDoc -> IfL a -> IfL a
939 forkM doc thing_inside
940 = do { mb_res <- forkM_maybe doc thing_inside
941 ; return (case mb_res of
942 Nothing -> pprPanic "forkM" doc
946 %************************************************************************
950 %************************************************************************
953 getTypeRefinement :: TcM GadtRefinement
954 getTypeRefinement = do { lcl_env <- getLclEnv; return (tcl_gadt lcl_env) }
956 setTypeRefinement :: GadtRefinement -> TcM a -> TcM a
957 setTypeRefinement gadt = updLclEnv (\env -> env { tcl_gadt = gadt })