8 #include "HsVersions.h"
10 import TcRnTypes -- Re-export all
11 import IOEnv -- Re-export all
13 #if defined(GHCI) && defined(BREAKPOINT)
14 import TypeRep ( Type(..), liftedTypeKind )
15 import Var ( mkTyVar, mkGlobalId )
16 import IdInfo ( GlobalIdDetails(..), vanillaIdInfo )
17 import OccName ( mkOccName, tvName )
18 import SrcLoc ( noSrcLoc )
19 import TysWiredIn ( intTy, stringTy, mkListTy, unitTy, boolTy )
20 import PrelNames ( breakpointJumpName, breakpointCondJumpName )
21 import NameEnv ( mkNameEnv )
22 import TcEnv ( tcExtendIdEnv )
25 import HsSyn ( emptyLHsBinds )
26 import HscTypes ( HscEnv(..), ModGuts(..), ModIface(..),
27 TypeEnv, emptyTypeEnv, HscSource(..), isHsBoot,
28 ExternalPackageState(..), HomePackageTable,
29 Deprecs(..), FixityEnv, FixItem,
31 import Module ( Module, moduleName )
32 import RdrName ( GlobalRdrEnv, LocalRdrEnv, emptyLocalRdrEnv )
33 import Name ( Name, mkInternalName, tidyNameOcc, nameOccName, getSrcLoc )
35 import TcType ( TcType, tcIsTyVarTy, tcGetTyVar )
36 import NameEnv ( extendNameEnvList, nameEnvElts )
37 import InstEnv ( emptyInstEnv )
38 import FamInstEnv ( emptyFamInstEnv )
40 import Var ( setTyVarName )
41 import Id ( mkSysLocal )
42 import VarSet ( emptyVarSet )
43 import VarEnv ( TidyEnv, emptyTidyEnv, extendVarEnv )
44 import ErrUtils ( Message, Messages, emptyMessages, errorsFound,
45 mkWarnMsg, printErrorsAndWarnings,
46 mkLocMessage, mkLongErrMsg )
47 import SrcLoc ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
48 import NameEnv ( emptyNameEnv )
49 import NameSet ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
50 import OccName ( emptyOccEnv, tidyOccName )
51 import Bag ( emptyBag )
53 import UniqSupply ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, uniqsFromSupply, splitUniqSupply )
54 import UniqFM ( unitUFM )
55 import Unique ( Unique )
56 import DynFlags ( DynFlags(..), DynFlag(..), dopt, dopt_set,
58 import StaticFlags ( opt_PprStyle_Debug )
59 import FastString ( FastString )
60 import Bag ( snocBag, unionBags )
61 import Panic ( showException )
64 import DATA_IOREF ( newIORef, readIORef )
65 import EXCEPTION ( Exception )
70 %************************************************************************
74 %************************************************************************
77 ioToTcRn :: IO r -> TcRn r
86 -> IO (Messages, Maybe r)
87 -- Nothing => error thrown by the thing inside
88 -- (error messages should have been printed already)
90 initTc hsc_env hsc_src mod do_this
91 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
92 tvs_var <- newIORef emptyVarSet ;
93 type_env_var <- newIORef emptyNameEnv ;
94 dfuns_var <- newIORef emptyNameSet ;
95 keep_var <- newIORef emptyNameSet ;
96 th_var <- newIORef False ;
97 dfun_n_var <- newIORef 1 ;
102 tcg_rdr_env = hsc_global_rdr_env hsc_env,
103 tcg_fix_env = emptyNameEnv,
104 tcg_default = Nothing,
105 tcg_type_env = hsc_global_type_env hsc_env,
106 tcg_type_env_var = type_env_var,
107 tcg_inst_env = emptyInstEnv,
108 tcg_fam_inst_env = emptyFamInstEnv,
109 tcg_inst_uses = dfuns_var,
110 tcg_th_used = th_var,
111 tcg_exports = emptyNameSet,
112 tcg_imports = init_imports,
114 tcg_rn_imports = Nothing,
115 tcg_rn_exports = Nothing,
116 tcg_rn_decls = Nothing,
117 tcg_binds = emptyLHsBinds,
118 tcg_deprecs = NoDeprecs,
122 tcg_dfun_n = dfun_n_var,
127 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
129 tcl_rdr = emptyLocalRdrEnv,
130 tcl_th_ctxt = topStage,
131 tcl_arrow_ctxt = NoArrowCtxt,
132 tcl_env = emptyNameEnv,
133 tcl_tyvars = tvs_var,
134 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
138 -- OK, here's the business end!
139 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
140 addBreakpointBindings $
141 do { r <- tryM do_this
143 Right res -> return (Just res)
144 Left _ -> return Nothing } ;
146 -- Collect any error messages
147 msgs <- readIORef errs_var ;
149 let { dflags = hsc_dflags hsc_env
150 ; final_res | errorsFound dflags msgs = Nothing
151 | otherwise = maybe_res } ;
153 return (msgs, final_res)
156 init_imports = emptyImportAvails {imp_env =
157 unitUFM (moduleName mod) emptyNameSet}
158 -- Initialise tcg_imports with an empty set of bindings for
159 -- this module, so that if we see 'module M' in the export
160 -- list, and there are no bindings in M, we don't bleat
161 -- "unknown module M".
163 initTcPrintErrors -- Used from the interactive loop only
168 initTcPrintErrors env mod todo = do
169 (msgs, res) <- initTc env HsSrcFile mod todo
170 printErrorsAndWarnings (hsc_dflags env) msgs
175 addBreakpointBindings :: TcM a -> TcM a
176 addBreakpointBindings thing_inside
177 #if defined(GHCI) && defined(BREAKPOINT)
178 = do { unique <- newUnique
179 ; let { var = mkInternalName unique (mkOccName tvName "a") noSrcLoc;
180 tyvar = mkTyVar var liftedTypeKind;
181 basicType extra = (FunTy intTy
182 (FunTy (mkListTy unitTy)
186 (FunTy (TyVarTy tyvar)
187 (TyVarTy tyvar)))))));
189 = mkGlobalId VanillaGlobal breakpointJumpName
190 (basicType id) vanillaIdInfo;
192 = mkGlobalId VanillaGlobal breakpointCondJumpName
193 (basicType (FunTy boolTy)) vanillaIdInfo
195 ; tcExtendIdEnv [breakpointJumpId, breakpointCondJumpId] thing_inside}
201 %************************************************************************
205 %************************************************************************
209 initTcRnIf :: Char -- Tag for unique supply
214 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
215 = do { us <- mkSplitUniqSupply uniq_tag ;
216 ; us_var <- newIORef us ;
218 ; let { env = Env { env_top = hsc_env,
221 env_lcl = lcl_env } }
223 ; runIOEnv env thing_inside
227 %************************************************************************
231 %************************************************************************
234 getTopEnv :: TcRnIf gbl lcl HscEnv
235 getTopEnv = do { env <- getEnv; return (env_top env) }
237 getGblEnv :: TcRnIf gbl lcl gbl
238 getGblEnv = do { env <- getEnv; return (env_gbl env) }
240 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
241 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
242 env { env_gbl = upd gbl })
244 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
245 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
247 getLclEnv :: TcRnIf gbl lcl lcl
248 getLclEnv = do { env <- getEnv; return (env_lcl env) }
250 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
251 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
252 env { env_lcl = upd lcl })
254 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
255 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
257 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
258 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
260 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
261 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
268 getDOpts :: TcRnIf gbl lcl DynFlags
269 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
271 doptM :: DynFlag -> TcRnIf gbl lcl Bool
272 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
274 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
275 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
276 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
278 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
279 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
280 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
282 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
283 ifOptM flag thing_inside = do { b <- doptM flag;
284 if b then thing_inside else return () }
286 getGhcMode :: TcRnIf gbl lcl GhcMode
287 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
291 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
292 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
294 getEps :: TcRnIf gbl lcl ExternalPackageState
295 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
297 -- Updating the EPS. This should be an atomic operation.
298 -- Note the delicate 'seq' which forces the EPS before putting it in the
299 -- variable. Otherwise what happens is that we get
300 -- write eps_var (....(unsafeRead eps_var)....)
301 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
302 -- we make the unsafeRead happen before we update the variable.
304 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
306 updateEps upd_fn = do { traceIf (text "updating EPS")
307 ; eps_var <- getEpsVar
308 ; eps <- readMutVar eps_var
309 ; let { (eps', val) = upd_fn eps }
310 ; seq eps' (writeMutVar eps_var eps')
313 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
315 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
316 ; eps_var <- getEpsVar
317 ; eps <- readMutVar eps_var
318 ; let { eps' = upd_fn eps }
319 ; seq eps' (writeMutVar eps_var eps') }
321 getHpt :: TcRnIf gbl lcl HomePackageTable
322 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
324 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
325 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
326 ; return (eps, hsc_HPT env) }
329 %************************************************************************
333 %************************************************************************
336 newUnique :: TcRnIf gbl lcl Unique
338 = do { env <- getEnv ;
339 let { u_var = env_us env } ;
340 us <- readMutVar u_var ;
341 case splitUniqSupply us of { (us1,_) -> do {
342 writeMutVar u_var us1 ;
343 return $! uniqFromSupply us }}}
344 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
345 -- a chain of unevaluated supplies behind.
346 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
347 -- throw away one half of the new split supply. This is safe because this
348 -- is the only place we use that unique. Using the other half of the split
349 -- supply is safer, but slower.
351 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
353 = do { env <- getEnv ;
354 let { u_var = env_us env } ;
355 us <- readMutVar u_var ;
356 case splitUniqSupply us of { (us1,us2) -> do {
357 writeMutVar u_var us1 ;
360 newLocalName :: Name -> TcRnIf gbl lcl Name
361 newLocalName name -- Make a clone
362 = do { uniq <- newUnique
363 ; return (mkInternalName uniq (nameOccName name) (getSrcLoc name)) }
365 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
366 newSysLocalIds fs tys
367 = do { us <- newUniqueSupply
368 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
372 %************************************************************************
376 %************************************************************************
379 traceTc, traceRn :: SDoc -> TcRn ()
380 traceRn = traceOptTcRn Opt_D_dump_rn_trace
381 traceTc = traceOptTcRn Opt_D_dump_tc_trace
382 traceSplice = traceOptTcRn Opt_D_dump_splices
385 traceIf :: SDoc -> TcRnIf m n ()
386 traceIf = traceOptIf Opt_D_dump_if_trace
387 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
390 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
391 traceOptIf flag doc = ifOptM flag $
392 ioToIOEnv (printForUser stderr alwaysQualify doc)
394 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
395 traceOptTcRn flag doc = ifOptM flag $ do
398 ; env0 <- tcInitTidyEnv
399 ; ctxt_msgs <- do_ctxt env0 ctxt
400 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
401 ; dumpTcRn real_doc }
403 dumpTcRn :: SDoc -> TcRn ()
404 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
405 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
407 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
408 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
412 %************************************************************************
414 Typechecker global environment
416 %************************************************************************
419 getModule :: TcRn Module
420 getModule = do { env <- getGblEnv; return (tcg_mod env) }
422 setModule :: Module -> TcRn a -> TcRn a
423 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
425 tcIsHsBoot :: TcRn Bool
426 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
428 getGlobalRdrEnv :: TcRn GlobalRdrEnv
429 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
431 getImports :: TcRn ImportAvails
432 getImports = do { env <- getGblEnv; return (tcg_imports env) }
434 getFixityEnv :: TcRn FixityEnv
435 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
437 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
438 extendFixityEnv new_bit
439 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
440 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
442 getDefaultTys :: TcRn (Maybe [Type])
443 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
446 %************************************************************************
450 %************************************************************************
453 getSrcSpanM :: TcRn SrcSpan
454 -- Avoid clash with Name.getSrcLoc
455 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
457 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
458 setSrcSpan loc thing_inside
459 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
460 | otherwise = thing_inside -- Don't overwrite useful info with useless
462 addLocM :: (a -> TcM b) -> Located a -> TcM b
463 addLocM fn (L loc a) = setSrcSpan loc $ fn a
465 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
466 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
468 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
469 wrapLocFstM fn (L loc a) =
474 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
475 wrapLocSndM fn (L loc a) =
483 getErrsVar :: TcRn (TcRef Messages)
484 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
486 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
487 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
489 addErr :: Message -> TcRn ()
490 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
492 addLocErr :: Located e -> (e -> Message) -> TcRn ()
493 addLocErr (L loc e) fn = addErrAt loc (fn e)
495 addErrAt :: SrcSpan -> Message -> TcRn ()
496 addErrAt loc msg = addLongErrAt loc msg empty
498 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
499 addLongErrAt loc msg extra
500 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
501 errs_var <- getErrsVar ;
502 rdr_env <- getGlobalRdrEnv ;
503 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
504 (warns, errs) <- readMutVar errs_var ;
505 writeMutVar errs_var (warns, errs `snocBag` err) }
507 addErrs :: [(SrcSpan,Message)] -> TcRn ()
508 addErrs msgs = mappM_ add msgs
510 add (loc,msg) = addErrAt loc msg
512 addReport :: Message -> TcRn ()
513 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
515 addReportAt :: SrcSpan -> Message -> TcRn ()
517 = do { errs_var <- getErrsVar ;
518 rdr_env <- getGlobalRdrEnv ;
519 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
520 (warns, errs) <- readMutVar errs_var ;
521 writeMutVar errs_var (warns `snocBag` warn, errs) }
523 addWarn :: Message -> TcRn ()
524 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
526 addWarnAt :: SrcSpan -> Message -> TcRn ()
527 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
529 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
530 addLocWarn (L loc e) fn = addReportAt loc (fn e)
532 checkErr :: Bool -> Message -> TcRn ()
533 -- Add the error if the bool is False
534 checkErr ok msg = checkM ok (addErr msg)
536 warnIf :: Bool -> Message -> TcRn ()
537 warnIf True msg = addWarn msg
538 warnIf False msg = return ()
540 addMessages :: Messages -> TcRn ()
541 addMessages (m_warns, m_errs)
542 = do { errs_var <- getErrsVar ;
543 (warns, errs) <- readMutVar errs_var ;
544 writeMutVar errs_var (warns `unionBags` m_warns,
545 errs `unionBags` m_errs) }
547 discardWarnings :: TcRn a -> TcRn a
548 -- Ignore warnings inside the thing inside;
549 -- used to ignore-unused-variable warnings inside derived code
550 -- With -dppr-debug, the effects is switched off, so you can still see
551 -- what warnings derived code would give
552 discardWarnings thing_inside
553 | opt_PprStyle_Debug = thing_inside
555 = do { errs_var <- newMutVar emptyMessages
556 ; result <- setErrsVar errs_var thing_inside
557 ; (_warns, errs) <- readMutVar errs_var
558 ; addMessages (emptyBag, errs)
564 try_m :: TcRn r -> TcRn (Either Exception r)
565 -- Does try_m, with a debug-trace on failure
567 = do { mb_r <- tryM thing ;
569 Left exn -> do { traceTc (exn_msg exn); return mb_r }
570 Right r -> return mb_r }
572 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
574 -----------------------
575 recoverM :: TcRn r -- Recovery action; do this if the main one fails
576 -> TcRn r -- Main action: do this first
578 -- Errors in 'thing' are retained
579 recoverM recover thing
580 = do { mb_res <- try_m thing ;
583 Right res -> returnM res }
585 -----------------------
586 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
587 -- (tryTc m) executes m, and returns
588 -- Just r, if m succeeds (returning r)
589 -- Nothing, if m fails
590 -- It also returns all the errors and warnings accumulated by m
591 -- It always succeeds (never raises an exception)
593 = do { errs_var <- newMutVar emptyMessages ;
594 res <- try_m (setErrsVar errs_var m) ;
595 msgs <- readMutVar errs_var ;
596 return (msgs, case res of
598 Right val -> Just val)
599 -- The exception is always the IOEnv built-in
600 -- in exception; see IOEnv.failM
603 -----------------------
604 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
605 -- Run the thing, returning
606 -- Just r, if m succceeds with no error messages
607 -- Nothing, if m fails, or if it succeeds but has error messages
608 -- Either way, the messages are returned; even in the Just case
609 -- there might be warnings
611 = do { (msgs, res) <- tryTc thing
613 ; let errs_found = errorsFound dflags msgs
614 ; return (msgs, case res of
616 Just val | errs_found -> Nothing
617 | otherwise -> Just val)
620 -----------------------
621 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
622 -- Just like tryTcErrs, except that it ensures that the LIE
623 -- for the thing is propagated only if there are no errors
624 -- Hence it's restricted to the type-check monad
625 tryTcLIE thing_inside
626 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
628 Nothing -> return (msgs, Nothing)
629 Just val -> do { extendLIEs lie; return (msgs, Just val) }
632 -----------------------
633 tryTcLIE_ :: TcM r -> TcM r -> TcM r
634 -- (tryTcLIE_ r m) tries m;
635 -- if m succeeds with no error messages, it's the answer
636 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
637 tryTcLIE_ recover main
638 = do { (msgs, mb_res) <- tryTcLIE main
640 Just val -> do { addMessages msgs -- There might be warnings
642 Nothing -> recover -- Discard all msgs
645 -----------------------
646 checkNoErrs :: TcM r -> TcM r
647 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
648 -- If m fails then (checkNoErrsTc m) fails.
649 -- If m succeeds, it checks whether m generated any errors messages
650 -- (it might have recovered internally)
651 -- If so, it fails too.
652 -- Regardless, any errors generated by m are propagated to the enclosing context.
654 = do { (msgs, mb_res) <- tryTcLIE main
658 Just val -> return val
661 ifErrsM :: TcRn r -> TcRn r -> TcRn r
662 -- ifErrsM bale_out main
663 -- does 'bale_out' if there are errors in errors collection
664 -- otherwise does 'main'
665 ifErrsM bale_out normal
666 = do { errs_var <- getErrsVar ;
667 msgs <- readMutVar errs_var ;
669 if errorsFound dflags msgs then
674 failIfErrsM :: TcRn ()
675 -- Useful to avoid error cascades
676 failIfErrsM = ifErrsM failM (return ())
680 %************************************************************************
682 Context management and error message generation
685 %************************************************************************
688 getErrCtxt :: TcM ErrCtxt
689 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
691 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
692 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
694 addErrCtxt :: Message -> TcM a -> TcM a
695 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
697 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
698 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
700 -- Helper function for the above
701 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
702 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
703 env { tcl_ctxt = upd ctxt })
705 -- Conditionally add an error context
706 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
707 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
708 maybeAddErrCtxt Nothing thing_inside = thing_inside
710 popErrCtxt :: TcM a -> TcM a
711 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
713 getInstLoc :: InstOrigin -> TcM InstLoc
715 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
716 return (InstLoc origin loc (tcl_ctxt env)) }
718 addInstCtxt :: InstLoc -> TcM a -> TcM a
719 -- Add the SrcSpan and context from the first Inst in the list
720 -- (they all have similar locations)
721 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
722 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
725 The addErrTc functions add an error message, but do not cause failure.
726 The 'M' variants pass a TidyEnv that has already been used to
727 tidy up the message; we then use it to tidy the context messages
730 addErrTc :: Message -> TcM ()
731 addErrTc err_msg = do { env0 <- tcInitTidyEnv
732 ; addErrTcM (env0, err_msg) }
734 addErrsTc :: [Message] -> TcM ()
735 addErrsTc err_msgs = mappM_ addErrTc err_msgs
737 addErrTcM :: (TidyEnv, Message) -> TcM ()
738 addErrTcM (tidy_env, err_msg)
739 = do { ctxt <- getErrCtxt ;
741 add_err_tcm tidy_env err_msg loc ctxt }
744 The failWith functions add an error message and cause failure
747 failWithTc :: Message -> TcM a -- Add an error message and fail
749 = addErrTc err_msg >> failM
751 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
752 failWithTcM local_and_msg
753 = addErrTcM local_and_msg >> failM
755 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
756 checkTc True err = returnM ()
757 checkTc False err = failWithTc err
760 Warnings have no 'M' variant, nor failure
763 addWarnTc :: Message -> TcM ()
765 = do { ctxt <- getErrCtxt ;
766 env0 <- tcInitTidyEnv ;
767 ctxt_msgs <- do_ctxt env0 ctxt ;
768 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
770 warnTc :: Bool -> Message -> TcM ()
771 warnTc warn_if_true warn_msg
772 | warn_if_true = addWarnTc warn_msg
773 | otherwise = return ()
776 -----------------------------------
779 We initialise the "tidy-env", used for tidying types before printing,
780 by building a reverse map from the in-scope type variables to the
781 OccName that the programmer originally used for them
784 tcInitTidyEnv :: TcM TidyEnv
786 = do { lcl_env <- getLclEnv
787 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
788 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
790 ; return (foldl add emptyTidyEnv nm_tv_prs) }
792 add (env,subst) (name, tyvar)
793 = case tidyOccName env (nameOccName name) of
794 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
796 tyvar' = setTyVarName tyvar name'
797 name' = tidyNameOcc name occ'
800 -----------------------------------
801 Other helper functions
804 add_err_tcm tidy_env err_msg loc ctxt
805 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
806 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
810 do_ctxt tidy_env (c:cs)
811 = do { (tidy_env', m) <- c tidy_env ;
812 ms <- do_ctxt tidy_env' cs ;
815 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
816 | otherwise = take 3 ctxt
819 debugTc is useful for monadic debugging code
822 debugTc :: TcM () -> TcM ()
824 debugTc thing = thing
826 debugTc thing = return ()
830 %************************************************************************
832 Type constraints (the so-called LIE)
834 %************************************************************************
837 nextDFunIndex :: TcM Int -- Get the next dfun index
838 nextDFunIndex = do { env <- getGblEnv
839 ; let dfun_n_var = tcg_dfun_n env
840 ; n <- readMutVar dfun_n_var
841 ; writeMutVar dfun_n_var (n+1)
844 getLIEVar :: TcM (TcRef LIE)
845 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
847 setLIEVar :: TcRef LIE -> TcM a -> TcM a
848 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
850 getLIE :: TcM a -> TcM (a, [Inst])
851 -- (getLIE m) runs m, and returns the type constraints it generates
853 = do { lie_var <- newMutVar emptyLIE ;
854 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
856 lie <- readMutVar lie_var ;
857 return (res, lieToList lie) }
859 extendLIE :: Inst -> TcM ()
861 = do { lie_var <- getLIEVar ;
862 lie <- readMutVar lie_var ;
863 writeMutVar lie_var (inst `consLIE` lie) }
865 extendLIEs :: [Inst] -> TcM ()
869 = do { lie_var <- getLIEVar ;
870 lie <- readMutVar lie_var ;
871 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
875 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
876 -- Set the local type envt, but do *not* disturb other fields,
877 -- notably the lie_var
878 setLclTypeEnv lcl_env thing_inside
879 = updLclEnv upd thing_inside
881 upd env = env { tcl_env = tcl_env lcl_env,
882 tcl_tyvars = tcl_tyvars lcl_env }
886 %************************************************************************
888 Template Haskell context
890 %************************************************************************
893 recordThUse :: TcM ()
894 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
896 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
897 keepAliveTc n = do { env <- getGblEnv;
898 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
900 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
901 keepAliveSetTc ns = do { env <- getGblEnv;
902 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
904 getStage :: TcM ThStage
905 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
907 setStage :: ThStage -> TcM a -> TcM a
908 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
912 %************************************************************************
914 Stuff for the renamer's local env
916 %************************************************************************
919 getLocalRdrEnv :: RnM LocalRdrEnv
920 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
922 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
923 setLocalRdrEnv rdr_env thing_inside
924 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
928 %************************************************************************
930 Stuff for interface decls
932 %************************************************************************
935 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
936 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
938 if_tv_env = emptyOccEnv,
939 if_id_env = emptyOccEnv }
941 initIfaceTcRn :: IfG a -> TcRn a
942 initIfaceTcRn thing_inside
943 = do { tcg_env <- getGblEnv
944 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
945 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
946 ; setEnvs (if_env, ()) thing_inside }
948 initIfaceExtCore :: IfL a -> TcRn a
949 initIfaceExtCore thing_inside
950 = do { tcg_env <- getGblEnv
951 ; let { mod = tcg_mod tcg_env
952 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
953 ; if_env = IfGblEnv {
954 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
955 ; if_lenv = mkIfLclEnv mod doc
957 ; setEnvs (if_env, if_lenv) thing_inside }
959 initIfaceCheck :: HscEnv -> IfG a -> IO a
960 -- Used when checking the up-to-date-ness of the old Iface
961 -- Initialise the environment with no useful info at all
962 initIfaceCheck hsc_env do_this
963 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
964 ; initTcRnIf 'i' hsc_env gbl_env () do_this
967 initIfaceTc :: ModIface
968 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
969 -- Used when type-checking checking an up-to-date interface file
970 -- No type envt from the current module, but we do know the module dependencies
971 initIfaceTc iface do_this
972 = do { tc_env_var <- newMutVar emptyTypeEnv
973 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
974 ; if_lenv = mkIfLclEnv mod doc
976 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
979 mod = mi_module iface
980 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
982 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
983 -- Used when sucking in new Rules in SimplCore
984 -- We have available the type envt of the module being compiled, and we must use it
985 initIfaceRules hsc_env guts do_this
987 type_info = (mg_module guts, return (mg_types guts))
988 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
991 -- Run the thing; any exceptions just bubble out from here
992 ; initTcRnIf 'i' hsc_env gbl_env () do_this
995 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
996 initIfaceLcl mod loc_doc thing_inside
997 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
999 getIfModule :: IfL Module
1000 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1002 --------------------
1003 failIfM :: Message -> IfL a
1004 -- The Iface monad doesn't have a place to accumulate errors, so we
1005 -- just fall over fast if one happens; it "shouldnt happen".
1006 -- We use IfL here so that we can get context info out of the local env
1008 = do { env <- getLclEnv
1009 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1010 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
1013 --------------------
1014 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1015 -- Run thing_inside in an interleaved thread.
1016 -- It shares everything with the parent thread, so this is DANGEROUS.
1018 -- It returns Nothing if the computation fails
1020 -- It's used for lazily type-checking interface
1021 -- signatures, which is pretty benign
1023 forkM_maybe doc thing_inside
1024 = do { unsafeInterleaveM $
1025 do { traceIf (text "Starting fork {" <+> doc)
1027 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1030 Right r -> do { traceIf (text "} ending fork" <+> doc)
1034 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1035 -- Otherwise we silently discard errors. Errors can legitimately
1036 -- happen when compiling interface signatures (see tcInterfaceSigs)
1037 ifOptM Opt_D_dump_if_trace
1038 (print_errs (hang (text "forkM failed:" <+> doc)
1039 4 (text (show exn))))
1041 ; traceIf (text "} ending fork (badly)" <+> doc)
1045 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1047 forkM :: SDoc -> IfL a -> IfL a
1048 forkM doc thing_inside
1049 = do { mb_res <- forkM_maybe doc thing_inside
1050 ; return (case mb_res of
1051 Nothing -> pgmError "Cannot continue after interface file error"
1052 -- pprPanic "forkM" doc