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 GhciMode, 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,
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 CmdLineOpts ( DynFlags, DynFlag(..), dopt, opt_PprStyle_Debug, dopt_set )
41 import Bag ( snocBag, unionBags )
42 import Panic ( showException )
44 import Maybe ( isJust )
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 ;
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 = emptyInstEnv,
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_env = unitModuleEnv mod emptyNameSet }
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".
139 initTcPrintErrors -- Used from the interactive loop only
144 initTcPrintErrors env mod todo = do
145 (msgs, res) <- initTc env HsSrcFile mod todo
146 printErrorsAndWarnings msgs
149 -- mkImpTypeEnv makes the imported symbol table
150 mkImpTypeEnv :: ExternalPackageState -> HomePackageTable
151 -> Name -> Maybe TyThing
152 mkImpTypeEnv pcs hpt = lookup
155 lookup name | isInternalName name = Nothing
156 | otherwise = lookupType hpt pte name
160 %************************************************************************
164 %************************************************************************
168 initTcRnIf :: Char -- Tag for unique supply
173 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
174 = do { us <- mkSplitUniqSupply uniq_tag ;
175 ; us_var <- newIORef us ;
177 ; let { env = Env { env_top = hsc_env,
180 env_lcl = lcl_env } }
182 ; runIOEnv env thing_inside
186 %************************************************************************
190 %************************************************************************
193 getTopEnv :: TcRnIf gbl lcl HscEnv
194 getTopEnv = do { env <- getEnv; return (env_top env) }
196 getGblEnv :: TcRnIf gbl lcl gbl
197 getGblEnv = do { env <- getEnv; return (env_gbl env) }
199 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
200 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
201 env { env_gbl = upd gbl })
203 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
204 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
206 getLclEnv :: TcRnIf gbl lcl lcl
207 getLclEnv = do { env <- getEnv; return (env_lcl env) }
209 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
210 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
211 env { env_lcl = upd lcl })
213 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
214 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
216 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
217 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
219 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
220 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
227 getDOpts :: TcRnIf gbl lcl DynFlags
228 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
230 doptM :: DynFlag -> TcRnIf gbl lcl Bool
231 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
233 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
234 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
235 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
237 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
238 ifOptM flag thing_inside = do { b <- doptM flag;
239 if b then thing_inside else return () }
241 getGhciMode :: TcRnIf gbl lcl GhciMode
242 getGhciMode = do { env <- getTopEnv; return (hsc_mode env) }
246 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
247 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
249 getEps :: TcRnIf gbl lcl ExternalPackageState
250 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
252 -- Updating the EPS. This should be an atomic operation.
253 -- Note the delicate 'seq' which forces the EPS before putting it in the
254 -- variable. Otherwise what happens is that we get
255 -- write eps_var (....(unsafeRead eps_var)....)
256 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
257 -- we make the unsafeRead happen before we update the variable.
259 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
261 updateEps upd_fn = do { traceIf (text "updating EPS")
262 ; eps_var <- getEpsVar
263 ; eps <- readMutVar eps_var
264 ; let { (eps', val) = upd_fn eps }
265 ; seq eps' (writeMutVar eps_var eps')
268 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
270 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
271 ; eps_var <- getEpsVar
272 ; eps <- readMutVar eps_var
273 ; let { eps' = upd_fn eps }
274 ; seq eps' (writeMutVar eps_var eps') }
276 getHpt :: TcRnIf gbl lcl HomePackageTable
277 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
279 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
280 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
281 ; return (eps, hsc_HPT env) }
284 %************************************************************************
288 %************************************************************************
291 newUnique :: TcRnIf gbl lcl Unique
292 newUnique = do { us <- newUniqueSupply ;
293 return (uniqFromSupply us) }
295 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
297 = do { env <- getEnv ;
298 let { u_var = env_us env } ;
299 us <- readMutVar u_var ;
300 let { (us1, us2) = splitUniqSupply us } ;
301 writeMutVar u_var us1 ;
306 %************************************************************************
310 %************************************************************************
313 traceTc, traceRn :: SDoc -> TcRn ()
314 traceRn = dumpOptTcRn Opt_D_dump_rn_trace
315 traceTc = dumpOptTcRn Opt_D_dump_tc_trace
316 traceSplice = dumpOptTcRn Opt_D_dump_splices
319 traceIf :: SDoc -> TcRnIf m n ()
320 traceIf = dumpOptIf Opt_D_dump_if_trace
321 traceHiDiffs = dumpOptIf Opt_D_dump_hi_diffs
324 dumpOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
325 dumpOptIf flag doc = ifOptM flag $
326 ioToIOEnv (printForUser stderr alwaysQualify doc)
328 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
329 dumpOptTcRn flag doc = ifOptM flag $ do
332 ; ctxt_msgs <- do_ctxt emptyTidyEnv ctxt
333 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
334 ; dumpTcRn real_doc }
336 dumpTcRn :: SDoc -> TcRn ()
337 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
338 ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
342 %************************************************************************
344 Typechecker global environment
346 %************************************************************************
349 getModule :: TcRn Module
350 getModule = do { env <- getGblEnv; return (tcg_mod env) }
352 tcIsHsBoot :: TcRn Bool
353 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
355 getGlobalRdrEnv :: TcRn GlobalRdrEnv
356 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
358 getImports :: TcRn ImportAvails
359 getImports = do { env <- getGblEnv; return (tcg_imports env) }
361 getFixityEnv :: TcRn FixityEnv
362 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
364 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
365 extendFixityEnv new_bit
366 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
367 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
369 getDefaultTys :: TcRn (Maybe [Type])
370 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
373 %************************************************************************
377 %************************************************************************
380 getSrcSpanM :: TcRn SrcSpan
381 -- Avoid clash with Name.getSrcLoc
382 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
384 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
385 setSrcSpan loc thing_inside
386 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
387 | otherwise = thing_inside -- Don't overwrite useful info with useless
389 addLocM :: (a -> TcM b) -> Located a -> TcM b
390 addLocM fn (L loc a) = setSrcSpan loc $ fn a
392 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
393 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
395 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
396 wrapLocFstM fn (L loc a) =
401 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
402 wrapLocSndM fn (L loc a) =
410 getErrsVar :: TcRn (TcRef Messages)
411 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
413 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
414 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
416 addErr :: Message -> TcRn ()
417 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
419 addLocErr :: Located e -> (e -> Message) -> TcRn ()
420 addLocErr (L loc e) fn = addErrAt loc (fn e)
422 addErrAt :: SrcSpan -> Message -> TcRn ()
423 addErrAt loc msg = addLongErrAt loc msg empty
425 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
426 addLongErrAt loc msg extra
427 = do { errs_var <- getErrsVar ;
428 rdr_env <- getGlobalRdrEnv ;
429 let { err = mkLongErrMsg loc (unQualInScope rdr_env) msg extra } ;
430 (warns, errs) <- readMutVar errs_var ;
431 writeMutVar errs_var (warns, errs `snocBag` err) }
433 addErrs :: [(SrcSpan,Message)] -> TcRn ()
434 addErrs msgs = mappM_ add msgs
436 add (loc,msg) = addErrAt loc msg
438 addReport :: Message -> TcRn ()
439 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
441 addReportAt :: SrcSpan -> Message -> TcRn ()
443 = do { errs_var <- getErrsVar ;
444 rdr_env <- getGlobalRdrEnv ;
445 let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
446 (warns, errs) <- readMutVar errs_var ;
447 writeMutVar errs_var (warns `snocBag` warn, errs) }
449 addWarn :: Message -> TcRn ()
450 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
452 addWarnAt :: SrcSpan -> Message -> TcRn ()
453 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
455 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
456 addLocWarn (L loc e) fn = addReportAt loc (fn e)
458 checkErr :: Bool -> Message -> TcRn ()
459 -- Add the error if the bool is False
460 checkErr ok msg = checkM ok (addErr msg)
462 warnIf :: Bool -> Message -> TcRn ()
463 warnIf True msg = addWarn msg
464 warnIf False msg = return ()
466 addMessages :: Messages -> TcRn ()
467 addMessages (m_warns, m_errs)
468 = do { errs_var <- getErrsVar ;
469 (warns, errs) <- readMutVar errs_var ;
470 writeMutVar errs_var (warns `unionBags` m_warns,
471 errs `unionBags` m_errs) }
473 discardWarnings :: TcRn a -> TcRn a
474 -- Ignore warnings inside the thing inside;
475 -- used to ignore-unused-variable warnings inside derived code
476 -- With -dppr-debug, the effects is switched off, so you can still see
477 -- what warnings derived code would give
478 discardWarnings thing_inside
479 | opt_PprStyle_Debug = thing_inside
481 = do { errs_var <- newMutVar emptyMessages
482 ; result <- setErrsVar errs_var thing_inside
483 ; (_warns, errs) <- readMutVar errs_var
484 ; addMessages (emptyBag, errs)
490 recoverM :: TcRn r -- Recovery action; do this if the main one fails
491 -> TcRn r -- Main action: do this first
493 recoverM recover thing
494 = do { mb_res <- try_m thing ;
497 Right res -> returnM res }
499 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
500 -- (tryTc m) executes m, and returns
501 -- Just r, if m succeeds (returning r) and caused no errors
502 -- Nothing, if m fails, or caused errors
503 -- It also returns all the errors accumulated by m
504 -- (even in the Just case, there might be warnings)
506 -- It always succeeds (never raises an exception)
508 = do { errs_var <- newMutVar emptyMessages ;
510 mb_r <- try_m (setErrsVar errs_var m) ;
512 new_errs <- readMutVar errs_var ;
519 Right r | errorsFound dflags new_errs -> Nothing
520 | otherwise -> Just r)
523 try_m :: TcRn r -> TcRn (Either Exception r)
524 -- Does try_m, with a debug-trace on failure
526 = do { mb_r <- tryM thing ;
528 Left exn -> do { traceTc (exn_msg exn); return mb_r }
529 Right r -> return mb_r }
531 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
533 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
534 -- Just like tryTc, except that it ensures that the LIE
535 -- for the thing is propagated only if there are no errors
536 -- Hence it's restricted to the type-check monad
537 tryTcLIE thing_inside
538 = do { ((errs, mb_r), lie) <- getLIE (tryTc thing_inside) ;
539 ifM (isJust mb_r) (extendLIEs lie) ;
540 return (errs, mb_r) }
542 tryTcLIE_ :: TcM r -> TcM r -> TcM r
543 -- (tryTcLIE_ r m) tries m; if it succeeds it returns it,
544 -- otherwise it returns r. Any error messages added by m are discarded,
545 -- whether or not m succeeds.
546 tryTcLIE_ recover main
547 = do { (_msgs, mb_res) <- tryTcLIE main ;
549 Just res -> return res
552 checkNoErrs :: TcM r -> TcM r
553 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
554 -- If m fails then (checkNoErrsTc m) fails.
555 -- If m succeeds, it checks whether m generated any errors messages
556 -- (it might have recovered internally)
557 -- If so, it fails too.
558 -- Regardless, any errors generated by m are propagated to the enclosing context.
560 = do { (msgs, mb_res) <- tryTcLIE main ;
567 ifErrsM :: TcRn r -> TcRn r -> TcRn r
568 -- ifErrsM bale_out main
569 -- does 'bale_out' if there are errors in errors collection
570 -- otherwise does 'main'
571 ifErrsM bale_out normal
572 = do { errs_var <- getErrsVar ;
573 msgs <- readMutVar errs_var ;
575 if errorsFound dflags msgs then
580 failIfErrsM :: TcRn ()
581 -- Useful to avoid error cascades
582 failIfErrsM = ifErrsM failM (return ())
586 %************************************************************************
588 Context management and error message generation
591 %************************************************************************
594 getErrCtxt :: TcM ErrCtxt
595 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
597 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
598 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
600 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
601 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
603 addErrCtxt :: Message -> TcM a -> TcM a
604 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
606 -- Helper function for the above
607 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
608 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
609 env { tcl_ctxt = upd ctxt })
611 -- Conditionally add an error context
612 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
613 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
614 maybeAddErrCtxt Nothing thing_inside = thing_inside
616 popErrCtxt :: TcM a -> TcM a
617 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
619 getInstLoc :: InstOrigin -> TcM InstLoc
621 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
622 return (InstLoc origin loc (tcl_ctxt env)) }
624 addInstCtxt :: InstLoc -> TcM a -> TcM a
625 -- Add the SrcSpan and context from the first Inst in the list
626 -- (they all have similar locations)
627 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
628 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
631 The addErrTc functions add an error message, but do not cause failure.
632 The 'M' variants pass a TidyEnv that has already been used to
633 tidy up the message; we then use it to tidy the context messages
636 addErrTc :: Message -> TcM ()
637 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
639 addErrsTc :: [Message] -> TcM ()
640 addErrsTc err_msgs = mappM_ addErrTc err_msgs
642 addErrTcM :: (TidyEnv, Message) -> TcM ()
643 addErrTcM (tidy_env, err_msg)
644 = do { ctxt <- getErrCtxt ;
646 add_err_tcm tidy_env err_msg loc ctxt }
649 The failWith functions add an error message and cause failure
652 failWithTc :: Message -> TcM a -- Add an error message and fail
654 = addErrTc err_msg >> failM
656 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
657 failWithTcM local_and_msg
658 = addErrTcM local_and_msg >> failM
660 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
661 checkTc True err = returnM ()
662 checkTc False err = failWithTc err
665 Warnings have no 'M' variant, nor failure
668 addWarnTc :: Message -> TcM ()
670 = do { ctxt <- getErrCtxt ;
671 ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
672 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
674 warnTc :: Bool -> Message -> TcM ()
675 warnTc warn_if_true warn_msg
676 | warn_if_true = addWarnTc warn_msg
677 | otherwise = return ()
683 add_err_tcm tidy_env err_msg loc ctxt
684 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
685 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
689 do_ctxt tidy_env (c:cs)
690 = do { (tidy_env', m) <- c tidy_env ;
691 ms <- do_ctxt tidy_env' cs ;
694 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
695 | otherwise = take 3 ctxt
698 debugTc is useful for monadi debugging code
701 debugTc :: TcM () -> TcM ()
703 debugTc thing = thing
705 debugTc thing = return ()
709 %************************************************************************
711 Type constraints (the so-called LIE)
713 %************************************************************************
716 getLIEVar :: TcM (TcRef LIE)
717 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
719 setLIEVar :: TcRef LIE -> TcM a -> TcM a
720 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
722 getLIE :: TcM a -> TcM (a, [Inst])
723 -- (getLIE m) runs m, and returns the type constraints it generates
725 = do { lie_var <- newMutVar emptyLIE ;
726 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
728 lie <- readMutVar lie_var ;
729 return (res, lieToList lie) }
731 extendLIE :: Inst -> TcM ()
733 = do { lie_var <- getLIEVar ;
734 lie <- readMutVar lie_var ;
735 writeMutVar lie_var (inst `consLIE` lie) }
737 extendLIEs :: [Inst] -> TcM ()
741 = do { lie_var <- getLIEVar ;
742 lie <- readMutVar lie_var ;
743 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
747 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
748 -- Set the local type envt, but do *not* disturb other fields,
749 -- notably the lie_var
750 setLclTypeEnv lcl_env thing_inside
751 = updLclEnv upd thing_inside
753 upd env = env { tcl_env = tcl_env lcl_env,
754 tcl_tyvars = tcl_tyvars lcl_env }
758 %************************************************************************
760 Template Haskell context
762 %************************************************************************
765 recordThUse :: TcM ()
766 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
768 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
769 keepAliveTc n = do { env <- getGblEnv;
770 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
772 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
773 keepAliveSetTc ns = do { env <- getGblEnv;
774 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
776 getStage :: TcM ThStage
777 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
779 setStage :: ThStage -> TcM a -> TcM a
780 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
784 %************************************************************************
788 %************************************************************************
791 popArrowBinders :: TcM a -> TcM a -- Move to the left of a (-<); see comments in TcRnTypes
793 = updLclEnv (\ env -> env { tcl_arrow_ctxt = pop (tcl_arrow_ctxt env) })
795 pop (ArrCtxt {proc_level = curr_lvl, proc_banned = banned})
796 = ASSERT( not (curr_lvl `elem` banned) )
797 ArrCtxt {proc_level = curr_lvl, proc_banned = curr_lvl : banned}
799 getBannedProcLevels :: TcM [ProcLevel]
800 = do { env <- getLclEnv; return (proc_banned (tcl_arrow_ctxt env)) }
802 incProcLevel :: TcM a -> TcM a
804 = updLclEnv (\ env -> env { tcl_arrow_ctxt = inc (tcl_arrow_ctxt env) })
806 inc ctxt = ctxt { proc_level = proc_level ctxt + 1 }
810 %************************************************************************
812 Stuff for the renamer's local env
814 %************************************************************************
817 getLocalRdrEnv :: RnM LocalRdrEnv
818 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
820 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
821 setLocalRdrEnv rdr_env thing_inside
822 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
826 %************************************************************************
828 Stuff for interface decls
830 %************************************************************************
833 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
834 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
836 if_tv_env = emptyOccEnv,
837 if_id_env = emptyOccEnv }
839 initIfaceTcRn :: IfG a -> TcRn a
840 initIfaceTcRn thing_inside
841 = do { tcg_env <- getGblEnv
842 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
843 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
844 ; setEnvs (if_env, ()) thing_inside }
846 initIfaceExtCore :: IfL a -> TcRn a
847 initIfaceExtCore thing_inside
848 = do { tcg_env <- getGblEnv
849 ; let { mod = tcg_mod tcg_env
850 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
851 ; if_env = IfGblEnv {
852 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
853 ; if_lenv = mkIfLclEnv mod doc
855 ; setEnvs (if_env, if_lenv) thing_inside }
857 initIfaceCheck :: HscEnv -> IfG a -> IO a
858 -- Used when checking the up-to-date-ness of the old Iface
859 -- Initialise the environment with no useful info at all
860 initIfaceCheck hsc_env do_this
861 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
862 ; initTcRnIf 'i' hsc_env gbl_env () do_this
865 initIfaceTc :: HscEnv -> ModIface
866 -> (TcRef TypeEnv -> IfL a) -> IO a
867 -- Used when type-checking checking an up-to-date interface file
868 -- No type envt from the current module, but we do know the module dependencies
869 initIfaceTc hsc_env iface do_this
870 = do { tc_env_var <- newIORef emptyTypeEnv
871 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
872 ; if_lenv = mkIfLclEnv mod doc
874 ; initTcRnIf 'i' hsc_env gbl_env if_lenv (do_this tc_env_var)
877 mod = mi_module iface
878 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
880 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
881 -- Used when sucking in new Rules in SimplCore
882 -- We have available the type envt of the module being compiled, and we must use it
883 initIfaceRules hsc_env guts do_this
885 type_info = (mg_module guts, return (mg_types guts))
886 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
889 -- Run the thing; any exceptions just bubble out from here
890 ; initTcRnIf 'i' hsc_env gbl_env () do_this
893 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
894 initIfaceLcl mod loc_doc thing_inside
895 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
897 getIfModule :: IfL Module
898 getIfModule = do { env <- getLclEnv; return (if_mod env) }
901 failIfM :: Message -> IfL a
902 -- The Iface monad doesn't have a place to accumulate errors, so we
903 -- just fall over fast if one happens; it "shouldnt happen".
904 -- We use IfL here so that we can get context info out of the local env
906 = do { env <- getLclEnv
907 ; let full_msg = if_loc env $$ nest 2 msg
908 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
912 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
913 -- Run thing_inside in an interleaved thread.
914 -- It shares everything with the parent thread, so this is DANGEROUS.
916 -- It returns Nothing if the computation fails
918 -- It's used for lazily type-checking interface
919 -- signatures, which is pretty benign
921 forkM_maybe doc thing_inside
922 = do { unsafeInterleaveM $
923 do { traceIf (text "Starting fork {" <+> doc)
924 ; mb_res <- tryM thing_inside ;
926 Right r -> do { traceIf (text "} ending fork" <+> doc)
930 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
931 -- Otherwise we silently discard errors. Errors can legitimately
932 -- happen when compiling interface signatures (see tcInterfaceSigs)
933 ifOptM Opt_D_dump_if_trace
934 (print_errs (hang (text "forkM failed:" <+> doc)
935 4 (text (show exn))))
937 ; traceIf (text "} ending fork (badly)" <+> doc)
941 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
943 forkM :: SDoc -> IfL a -> IfL a
944 forkM doc thing_inside
945 = do { mb_res <- forkM_maybe doc thing_inside
946 ; return (case mb_res of
947 Nothing -> pprPanic "forkM" doc
951 %************************************************************************
955 %************************************************************************
958 getTypeRefinement :: TcM GadtRefinement
959 getTypeRefinement = do { lcl_env <- getLclEnv; return (tcl_gadt lcl_env) }
961 setTypeRefinement :: GadtRefinement -> TcM a -> TcM a
962 setTypeRefinement gadt = updLclEnv (\env -> env { tcl_gadt = gadt })