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,
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 )
43 import Panic ( showException )
45 import Maybe ( isJust )
47 import DATA_IOREF ( newIORef, readIORef )
48 import EXCEPTION ( Exception )
53 %************************************************************************
57 %************************************************************************
60 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 hsc_src 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 ;
80 dfun_n_var <- newIORef 1 ;
86 tcg_rdr_env = emptyGlobalRdrEnv,
87 tcg_fix_env = emptyNameEnv,
88 tcg_default = Nothing,
89 tcg_type_env = emptyNameEnv,
90 tcg_type_env_var = type_env_var,
91 tcg_inst_env = emptyInstEnv,
92 tcg_inst_uses = dfuns_var,
94 tcg_exports = emptyNameSet,
95 tcg_imports = init_imports,
97 tcg_rn_decls = Nothing,
98 tcg_binds = emptyLHsBinds,
99 tcg_deprecs = NoDeprecs,
103 tcg_dfun_n = dfun_n_var,
108 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
110 tcl_rdr = emptyLocalRdrEnv,
111 tcl_th_ctxt = topStage,
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 writeMutVar errs_var (warns, errs `snocBag` err) }
436 addErrs :: [(SrcSpan,Message)] -> TcRn ()
437 addErrs msgs = mappM_ add msgs
439 add (loc,msg) = addErrAt loc msg
441 addReport :: Message -> TcRn ()
442 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
444 addReportAt :: SrcSpan -> Message -> TcRn ()
446 = do { errs_var <- getErrsVar ;
447 rdr_env <- getGlobalRdrEnv ;
448 let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
449 (warns, errs) <- readMutVar errs_var ;
450 writeMutVar errs_var (warns `snocBag` warn, errs) }
452 addWarn :: Message -> TcRn ()
453 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
455 addWarnAt :: SrcSpan -> Message -> TcRn ()
456 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
458 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
459 addLocWarn (L loc e) fn = addReportAt loc (fn e)
461 checkErr :: Bool -> Message -> TcRn ()
462 -- Add the error if the bool is False
463 checkErr ok msg = checkM ok (addErr msg)
465 warnIf :: Bool -> Message -> TcRn ()
466 warnIf True msg = addWarn msg
467 warnIf False msg = return ()
469 addMessages :: Messages -> TcRn ()
470 addMessages (m_warns, m_errs)
471 = do { errs_var <- getErrsVar ;
472 (warns, errs) <- readMutVar errs_var ;
473 writeMutVar errs_var (warns `unionBags` m_warns,
474 errs `unionBags` m_errs) }
476 discardWarnings :: TcRn a -> TcRn a
477 -- Ignore warnings inside the thing inside;
478 -- used to ignore-unused-variable warnings inside derived code
479 -- With -dppr-debug, the effects is switched off, so you can still see
480 -- what warnings derived code would give
481 discardWarnings thing_inside
482 | opt_PprStyle_Debug = thing_inside
484 = do { errs_var <- newMutVar emptyMessages
485 ; result <- setErrsVar errs_var thing_inside
486 ; (_warns, errs) <- readMutVar errs_var
487 ; addMessages (emptyBag, errs)
493 recoverM :: TcRn r -- Recovery action; do this if the main one fails
494 -> TcRn r -- Main action: do this first
496 recoverM recover thing
497 = do { mb_res <- try_m thing ;
500 Right res -> returnM res }
502 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
503 -- (tryTc m) executes m, and returns
504 -- Just r, if m succeeds (returning r) and caused no errors
505 -- Nothing, if m fails, or caused errors
506 -- It also returns all the errors accumulated by m
507 -- (even in the Just case, there might be warnings)
509 -- It always succeeds (never raises an exception)
511 = do { errs_var <- newMutVar emptyMessages ;
513 mb_r <- try_m (setErrsVar errs_var m) ;
515 new_errs <- readMutVar errs_var ;
522 Right r | errorsFound dflags new_errs -> Nothing
523 | otherwise -> Just r)
526 try_m :: TcRn r -> TcRn (Either Exception r)
527 -- Does try_m, with a debug-trace on failure
529 = do { mb_r <- tryM thing ;
531 Left exn -> do { traceTc (exn_msg exn); return mb_r }
532 Right r -> return mb_r }
534 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
536 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
537 -- Just like tryTc, except that it ensures that the LIE
538 -- for the thing is propagated only if there are no errors
539 -- Hence it's restricted to the type-check monad
540 tryTcLIE thing_inside
541 = do { ((errs, mb_r), lie) <- getLIE (tryTc thing_inside) ;
542 ifM (isJust mb_r) (extendLIEs lie) ;
543 return (errs, mb_r) }
545 tryTcLIE_ :: TcM r -> TcM r -> TcM r
546 -- (tryTcLIE_ r m) tries m; if it succeeds it returns it,
547 -- otherwise it returns r. Any error messages added by m are discarded,
548 -- whether or not m succeeds.
549 tryTcLIE_ recover main
550 = do { (_msgs, mb_res) <- tryTcLIE main ;
552 Just res -> return res
555 checkNoErrs :: TcM r -> TcM r
556 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
557 -- If m fails then (checkNoErrsTc m) fails.
558 -- If m succeeds, it checks whether m generated any errors messages
559 -- (it might have recovered internally)
560 -- If so, it fails too.
561 -- Regardless, any errors generated by m are propagated to the enclosing context.
563 = do { (msgs, mb_res) <- tryTcLIE main ;
570 ifErrsM :: TcRn r -> TcRn r -> TcRn r
571 -- ifErrsM bale_out main
572 -- does 'bale_out' if there are errors in errors collection
573 -- otherwise does 'main'
574 ifErrsM bale_out normal
575 = do { errs_var <- getErrsVar ;
576 msgs <- readMutVar errs_var ;
578 if errorsFound dflags msgs then
583 failIfErrsM :: TcRn ()
584 -- Useful to avoid error cascades
585 failIfErrsM = ifErrsM failM (return ())
589 %************************************************************************
591 Context management and error message generation
594 %************************************************************************
597 getErrCtxt :: TcM ErrCtxt
598 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
600 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
601 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
603 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
604 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
606 addErrCtxt :: Message -> TcM a -> TcM a
607 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
609 -- Helper function for the above
610 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
611 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
612 env { tcl_ctxt = upd ctxt })
614 -- Conditionally add an error context
615 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
616 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
617 maybeAddErrCtxt Nothing thing_inside = thing_inside
619 popErrCtxt :: TcM a -> TcM a
620 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
622 getInstLoc :: InstOrigin -> TcM InstLoc
624 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
625 return (InstLoc origin loc (tcl_ctxt env)) }
627 addInstCtxt :: InstLoc -> TcM a -> TcM a
628 -- Add the SrcSpan and context from the first Inst in the list
629 -- (they all have similar locations)
630 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
631 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
634 The addErrTc functions add an error message, but do not cause failure.
635 The 'M' variants pass a TidyEnv that has already been used to
636 tidy up the message; we then use it to tidy the context messages
639 addErrTc :: Message -> TcM ()
640 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
642 addErrsTc :: [Message] -> TcM ()
643 addErrsTc err_msgs = mappM_ addErrTc err_msgs
645 addErrTcM :: (TidyEnv, Message) -> TcM ()
646 addErrTcM (tidy_env, err_msg)
647 = do { ctxt <- getErrCtxt ;
649 add_err_tcm tidy_env err_msg loc ctxt }
652 The failWith functions add an error message and cause failure
655 failWithTc :: Message -> TcM a -- Add an error message and fail
657 = addErrTc err_msg >> failM
659 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
660 failWithTcM local_and_msg
661 = addErrTcM local_and_msg >> failM
663 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
664 checkTc True err = returnM ()
665 checkTc False err = failWithTc err
668 Warnings have no 'M' variant, nor failure
671 addWarnTc :: Message -> TcM ()
673 = do { ctxt <- getErrCtxt ;
674 ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
675 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
677 warnTc :: Bool -> Message -> TcM ()
678 warnTc warn_if_true warn_msg
679 | warn_if_true = addWarnTc warn_msg
680 | otherwise = return ()
686 add_err_tcm tidy_env err_msg loc ctxt
687 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
688 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
692 do_ctxt tidy_env (c:cs)
693 = do { (tidy_env', m) <- c tidy_env ;
694 ms <- do_ctxt tidy_env' cs ;
697 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
698 | otherwise = take 3 ctxt
701 debugTc is useful for monadi debugging code
704 debugTc :: TcM () -> TcM ()
706 debugTc thing = thing
708 debugTc thing = return ()
712 %************************************************************************
714 Type constraints (the so-called LIE)
716 %************************************************************************
719 nextDFunIndex :: TcM Int -- Get the next dfun index
720 nextDFunIndex = do { env <- getGblEnv
721 ; let dfun_n_var = tcg_dfun_n env
722 ; n <- readMutVar dfun_n_var
723 ; writeMutVar dfun_n_var (n+1)
726 getLIEVar :: TcM (TcRef LIE)
727 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
729 setLIEVar :: TcRef LIE -> TcM a -> TcM a
730 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
732 getLIE :: TcM a -> TcM (a, [Inst])
733 -- (getLIE m) runs m, and returns the type constraints it generates
735 = do { lie_var <- newMutVar emptyLIE ;
736 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
738 lie <- readMutVar lie_var ;
739 return (res, lieToList lie) }
741 extendLIE :: Inst -> TcM ()
743 = do { lie_var <- getLIEVar ;
744 lie <- readMutVar lie_var ;
745 writeMutVar lie_var (inst `consLIE` lie) }
747 extendLIEs :: [Inst] -> TcM ()
751 = do { lie_var <- getLIEVar ;
752 lie <- readMutVar lie_var ;
753 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
757 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
758 -- Set the local type envt, but do *not* disturb other fields,
759 -- notably the lie_var
760 setLclTypeEnv lcl_env thing_inside
761 = updLclEnv upd thing_inside
763 upd env = env { tcl_env = tcl_env lcl_env,
764 tcl_tyvars = tcl_tyvars lcl_env }
768 %************************************************************************
770 Template Haskell context
772 %************************************************************************
775 recordThUse :: TcM ()
776 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
778 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
779 keepAliveTc n = do { env <- getGblEnv;
780 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
782 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
783 keepAliveSetTc ns = do { env <- getGblEnv;
784 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
786 getStage :: TcM ThStage
787 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
789 setStage :: ThStage -> TcM a -> TcM a
790 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
794 %************************************************************************
796 Stuff for the renamer's local env
798 %************************************************************************
801 getLocalRdrEnv :: RnM LocalRdrEnv
802 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
804 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
805 setLocalRdrEnv rdr_env thing_inside
806 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
810 %************************************************************************
812 Stuff for interface decls
814 %************************************************************************
817 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
818 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
820 if_tv_env = emptyOccEnv,
821 if_id_env = emptyOccEnv }
823 initIfaceTcRn :: IfG a -> TcRn a
824 initIfaceTcRn thing_inside
825 = do { tcg_env <- getGblEnv
826 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
827 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
828 ; setEnvs (if_env, ()) thing_inside }
830 initIfaceExtCore :: IfL a -> TcRn a
831 initIfaceExtCore thing_inside
832 = do { tcg_env <- getGblEnv
833 ; let { mod = tcg_mod tcg_env
834 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
835 ; if_env = IfGblEnv {
836 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
837 ; if_lenv = mkIfLclEnv mod doc
839 ; setEnvs (if_env, if_lenv) thing_inside }
841 initIfaceCheck :: HscEnv -> IfG a -> IO a
842 -- Used when checking the up-to-date-ness of the old Iface
843 -- Initialise the environment with no useful info at all
844 initIfaceCheck hsc_env do_this
845 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
846 ; initTcRnIf 'i' hsc_env gbl_env () do_this
849 initIfaceTc :: ModIface
850 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
851 -- Used when type-checking checking an up-to-date interface file
852 -- No type envt from the current module, but we do know the module dependencies
853 initIfaceTc iface do_this
854 = do { tc_env_var <- newMutVar emptyTypeEnv
855 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
856 ; if_lenv = mkIfLclEnv mod doc
858 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
861 mod = mi_module iface
862 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
864 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
865 -- Used when sucking in new Rules in SimplCore
866 -- We have available the type envt of the module being compiled, and we must use it
867 initIfaceRules hsc_env guts do_this
869 type_info = (mg_module guts, return (mg_types guts))
870 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
873 -- Run the thing; any exceptions just bubble out from here
874 ; initTcRnIf 'i' hsc_env gbl_env () do_this
877 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
878 initIfaceLcl mod loc_doc thing_inside
879 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
881 getIfModule :: IfL Module
882 getIfModule = do { env <- getLclEnv; return (if_mod env) }
885 failIfM :: Message -> IfL a
886 -- The Iface monad doesn't have a place to accumulate errors, so we
887 -- just fall over fast if one happens; it "shouldnt happen".
888 -- We use IfL here so that we can get context info out of the local env
890 = do { env <- getLclEnv
891 ; let full_msg = if_loc env $$ nest 2 msg
892 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
896 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
897 -- Run thing_inside in an interleaved thread.
898 -- It shares everything with the parent thread, so this is DANGEROUS.
900 -- It returns Nothing if the computation fails
902 -- It's used for lazily type-checking interface
903 -- signatures, which is pretty benign
905 forkM_maybe doc thing_inside
906 = do { unsafeInterleaveM $
907 do { traceIf (text "Starting fork {" <+> doc)
908 ; mb_res <- tryM thing_inside ;
910 Right r -> do { traceIf (text "} ending fork" <+> doc)
914 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
915 -- Otherwise we silently discard errors. Errors can legitimately
916 -- happen when compiling interface signatures (see tcInterfaceSigs)
917 ifOptM Opt_D_dump_if_trace
918 (print_errs (hang (text "forkM failed:" <+> doc)
919 4 (text (show exn))))
921 ; traceIf (text "} ending fork (badly)" <+> doc)
925 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
927 forkM :: SDoc -> IfL a -> IfL a
928 forkM doc thing_inside
929 = do { mb_res <- forkM_maybe doc thing_inside
930 ; return (case mb_res of
931 Nothing -> pprPanic "forkM" doc
935 %************************************************************************
939 %************************************************************************
942 getTypeRefinement :: TcM GadtRefinement
943 getTypeRefinement = do { lcl_env <- getLclEnv; return (tcl_gadt lcl_env) }
945 setTypeRefinement :: GadtRefinement -> TcM a -> TcM a
946 setTypeRefinement gadt = updLclEnv (\env -> env { tcl_gadt = gadt })