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, HaddockModInfo(..) )
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,
125 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing
129 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
131 tcl_rdr = emptyLocalRdrEnv,
132 tcl_th_ctxt = topStage,
133 tcl_arrow_ctxt = NoArrowCtxt,
134 tcl_env = emptyNameEnv,
135 tcl_tyvars = tvs_var,
136 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
140 -- OK, here's the business end!
141 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
142 addBreakpointBindings $
143 do { r <- tryM do_this
145 Right res -> return (Just res)
146 Left _ -> return Nothing } ;
148 -- Collect any error messages
149 msgs <- readIORef errs_var ;
151 let { dflags = hsc_dflags hsc_env
152 ; final_res | errorsFound dflags msgs = Nothing
153 | otherwise = maybe_res } ;
155 return (msgs, final_res)
158 init_imports = emptyImportAvails {imp_env =
159 unitUFM (moduleName mod) emptyNameSet}
160 -- Initialise tcg_imports with an empty set of bindings for
161 -- this module, so that if we see 'module M' in the export
162 -- list, and there are no bindings in M, we don't bleat
163 -- "unknown module M".
165 initTcPrintErrors -- Used from the interactive loop only
170 initTcPrintErrors env mod todo = do
171 (msgs, res) <- initTc env HsSrcFile mod todo
172 printErrorsAndWarnings (hsc_dflags env) msgs
177 addBreakpointBindings :: TcM a -> TcM a
178 addBreakpointBindings thing_inside
179 #if defined(GHCI) && defined(BREAKPOINT)
180 = do { unique <- newUnique
181 ; let { var = mkInternalName unique (mkOccName tvName "a") noSrcLoc;
182 tyvar = mkTyVar var liftedTypeKind;
183 basicType extra = (FunTy intTy
184 (FunTy (mkListTy unitTy)
188 (FunTy (TyVarTy tyvar)
189 (TyVarTy tyvar)))))));
191 = mkGlobalId VanillaGlobal breakpointJumpName
192 (basicType id) vanillaIdInfo;
194 = mkGlobalId VanillaGlobal breakpointCondJumpName
195 (basicType (FunTy boolTy)) vanillaIdInfo
197 ; tcExtendIdEnv [breakpointJumpId, breakpointCondJumpId] thing_inside}
203 %************************************************************************
207 %************************************************************************
211 initTcRnIf :: Char -- Tag for unique supply
216 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
217 = do { us <- mkSplitUniqSupply uniq_tag ;
218 ; us_var <- newIORef us ;
220 ; let { env = Env { env_top = hsc_env,
223 env_lcl = lcl_env } }
225 ; runIOEnv env thing_inside
229 %************************************************************************
233 %************************************************************************
236 getTopEnv :: TcRnIf gbl lcl HscEnv
237 getTopEnv = do { env <- getEnv; return (env_top env) }
239 getGblEnv :: TcRnIf gbl lcl gbl
240 getGblEnv = do { env <- getEnv; return (env_gbl env) }
242 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
243 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
244 env { env_gbl = upd gbl })
246 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
247 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
249 getLclEnv :: TcRnIf gbl lcl lcl
250 getLclEnv = do { env <- getEnv; return (env_lcl env) }
252 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
253 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
254 env { env_lcl = upd lcl })
256 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
257 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
259 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
260 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
262 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
263 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
270 getDOpts :: TcRnIf gbl lcl DynFlags
271 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
273 doptM :: DynFlag -> TcRnIf gbl lcl Bool
274 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
276 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
277 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
278 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
280 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
281 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
282 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
284 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
285 ifOptM flag thing_inside = do { b <- doptM flag;
286 if b then thing_inside else return () }
288 getGhcMode :: TcRnIf gbl lcl GhcMode
289 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
293 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
294 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
296 getEps :: TcRnIf gbl lcl ExternalPackageState
297 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
299 -- Updating the EPS. This should be an atomic operation.
300 -- Note the delicate 'seq' which forces the EPS before putting it in the
301 -- variable. Otherwise what happens is that we get
302 -- write eps_var (....(unsafeRead eps_var)....)
303 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
304 -- we make the unsafeRead happen before we update the variable.
306 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
308 updateEps upd_fn = do { traceIf (text "updating EPS")
309 ; eps_var <- getEpsVar
310 ; eps <- readMutVar eps_var
311 ; let { (eps', val) = upd_fn eps }
312 ; seq eps' (writeMutVar eps_var eps')
315 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
317 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
318 ; eps_var <- getEpsVar
319 ; eps <- readMutVar eps_var
320 ; let { eps' = upd_fn eps }
321 ; seq eps' (writeMutVar eps_var eps') }
323 getHpt :: TcRnIf gbl lcl HomePackageTable
324 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
326 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
327 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
328 ; return (eps, hsc_HPT env) }
331 %************************************************************************
335 %************************************************************************
338 newUnique :: TcRnIf gbl lcl Unique
340 = do { env <- getEnv ;
341 let { u_var = env_us env } ;
342 us <- readMutVar u_var ;
343 case splitUniqSupply us of { (us1,_) -> do {
344 writeMutVar u_var us1 ;
345 return $! uniqFromSupply us }}}
346 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
347 -- a chain of unevaluated supplies behind.
348 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
349 -- throw away one half of the new split supply. This is safe because this
350 -- is the only place we use that unique. Using the other half of the split
351 -- supply is safer, but slower.
353 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
355 = do { env <- getEnv ;
356 let { u_var = env_us env } ;
357 us <- readMutVar u_var ;
358 case splitUniqSupply us of { (us1,us2) -> do {
359 writeMutVar u_var us1 ;
362 newLocalName :: Name -> TcRnIf gbl lcl Name
363 newLocalName name -- Make a clone
364 = do { uniq <- newUnique
365 ; return (mkInternalName uniq (nameOccName name) (getSrcLoc name)) }
367 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
368 newSysLocalIds fs tys
369 = do { us <- newUniqueSupply
370 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
374 %************************************************************************
378 %************************************************************************
381 traceTc, traceRn :: SDoc -> TcRn ()
382 traceRn = traceOptTcRn Opt_D_dump_rn_trace
383 traceTc = traceOptTcRn Opt_D_dump_tc_trace
384 traceSplice = traceOptTcRn Opt_D_dump_splices
387 traceIf :: SDoc -> TcRnIf m n ()
388 traceIf = traceOptIf Opt_D_dump_if_trace
389 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
392 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
393 traceOptIf flag doc = ifOptM flag $
394 ioToIOEnv (printForUser stderr alwaysQualify doc)
396 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
397 traceOptTcRn flag doc = ifOptM flag $ do
400 ; env0 <- tcInitTidyEnv
401 ; ctxt_msgs <- do_ctxt env0 ctxt
402 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
403 ; dumpTcRn real_doc }
405 dumpTcRn :: SDoc -> TcRn ()
406 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
407 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
409 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
410 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
414 %************************************************************************
416 Typechecker global environment
418 %************************************************************************
421 getModule :: TcRn Module
422 getModule = do { env <- getGblEnv; return (tcg_mod env) }
424 setModule :: Module -> TcRn a -> TcRn a
425 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
427 tcIsHsBoot :: TcRn Bool
428 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
430 getGlobalRdrEnv :: TcRn GlobalRdrEnv
431 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
433 getImports :: TcRn ImportAvails
434 getImports = do { env <- getGblEnv; return (tcg_imports env) }
436 getFixityEnv :: TcRn FixityEnv
437 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
439 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
440 extendFixityEnv new_bit
441 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
442 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
444 getDefaultTys :: TcRn (Maybe [Type])
445 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
448 %************************************************************************
452 %************************************************************************
455 getSrcSpanM :: TcRn SrcSpan
456 -- Avoid clash with Name.getSrcLoc
457 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
459 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
460 setSrcSpan loc thing_inside
461 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
462 | otherwise = thing_inside -- Don't overwrite useful info with useless
464 addLocM :: (a -> TcM b) -> Located a -> TcM b
465 addLocM fn (L loc a) = setSrcSpan loc $ fn a
467 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
468 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
470 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
471 wrapLocFstM fn (L loc a) =
476 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
477 wrapLocSndM fn (L loc a) =
485 getErrsVar :: TcRn (TcRef Messages)
486 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
488 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
489 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
491 addErr :: Message -> TcRn ()
492 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
494 addLocErr :: Located e -> (e -> Message) -> TcRn ()
495 addLocErr (L loc e) fn = addErrAt loc (fn e)
497 addErrAt :: SrcSpan -> Message -> TcRn ()
498 addErrAt loc msg = addLongErrAt loc msg empty
500 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
501 addLongErrAt loc msg extra
502 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
503 errs_var <- getErrsVar ;
504 rdr_env <- getGlobalRdrEnv ;
505 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
506 (warns, errs) <- readMutVar errs_var ;
507 writeMutVar errs_var (warns, errs `snocBag` err) }
509 addErrs :: [(SrcSpan,Message)] -> TcRn ()
510 addErrs msgs = mappM_ add msgs
512 add (loc,msg) = addErrAt loc msg
514 addReport :: Message -> TcRn ()
515 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
517 addReportAt :: SrcSpan -> Message -> TcRn ()
519 = do { errs_var <- getErrsVar ;
520 rdr_env <- getGlobalRdrEnv ;
521 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
522 (warns, errs) <- readMutVar errs_var ;
523 writeMutVar errs_var (warns `snocBag` warn, errs) }
525 addWarn :: Message -> TcRn ()
526 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
528 addWarnAt :: SrcSpan -> Message -> TcRn ()
529 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
531 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
532 addLocWarn (L loc e) fn = addReportAt loc (fn e)
534 checkErr :: Bool -> Message -> TcRn ()
535 -- Add the error if the bool is False
536 checkErr ok msg = checkM ok (addErr msg)
538 warnIf :: Bool -> Message -> TcRn ()
539 warnIf True msg = addWarn msg
540 warnIf False msg = return ()
542 addMessages :: Messages -> TcRn ()
543 addMessages (m_warns, m_errs)
544 = do { errs_var <- getErrsVar ;
545 (warns, errs) <- readMutVar errs_var ;
546 writeMutVar errs_var (warns `unionBags` m_warns,
547 errs `unionBags` m_errs) }
549 discardWarnings :: TcRn a -> TcRn a
550 -- Ignore warnings inside the thing inside;
551 -- used to ignore-unused-variable warnings inside derived code
552 -- With -dppr-debug, the effects is switched off, so you can still see
553 -- what warnings derived code would give
554 discardWarnings thing_inside
555 | opt_PprStyle_Debug = thing_inside
557 = do { errs_var <- newMutVar emptyMessages
558 ; result <- setErrsVar errs_var thing_inside
559 ; (_warns, errs) <- readMutVar errs_var
560 ; addMessages (emptyBag, errs)
566 try_m :: TcRn r -> TcRn (Either Exception r)
567 -- Does try_m, with a debug-trace on failure
569 = do { mb_r <- tryM thing ;
571 Left exn -> do { traceTc (exn_msg exn); return mb_r }
572 Right r -> return mb_r }
574 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
576 -----------------------
577 recoverM :: TcRn r -- Recovery action; do this if the main one fails
578 -> TcRn r -- Main action: do this first
580 -- Errors in 'thing' are retained
581 recoverM recover thing
582 = do { mb_res <- try_m thing ;
585 Right res -> returnM res }
587 -----------------------
588 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
589 -- (tryTc m) executes m, and returns
590 -- Just r, if m succeeds (returning r)
591 -- Nothing, if m fails
592 -- It also returns all the errors and warnings accumulated by m
593 -- It always succeeds (never raises an exception)
595 = do { errs_var <- newMutVar emptyMessages ;
596 res <- try_m (setErrsVar errs_var m) ;
597 msgs <- readMutVar errs_var ;
598 return (msgs, case res of
600 Right val -> Just val)
601 -- The exception is always the IOEnv built-in
602 -- in exception; see IOEnv.failM
605 -----------------------
606 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
607 -- Run the thing, returning
608 -- Just r, if m succceeds with no error messages
609 -- Nothing, if m fails, or if it succeeds but has error messages
610 -- Either way, the messages are returned; even in the Just case
611 -- there might be warnings
613 = do { (msgs, res) <- tryTc thing
615 ; let errs_found = errorsFound dflags msgs
616 ; return (msgs, case res of
618 Just val | errs_found -> Nothing
619 | otherwise -> Just val)
622 -----------------------
623 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
624 -- Just like tryTcErrs, except that it ensures that the LIE
625 -- for the thing is propagated only if there are no errors
626 -- Hence it's restricted to the type-check monad
627 tryTcLIE thing_inside
628 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
630 Nothing -> return (msgs, Nothing)
631 Just val -> do { extendLIEs lie; return (msgs, Just val) }
634 -----------------------
635 tryTcLIE_ :: TcM r -> TcM r -> TcM r
636 -- (tryTcLIE_ r m) tries m;
637 -- if m succeeds with no error messages, it's the answer
638 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
639 tryTcLIE_ recover main
640 = do { (msgs, mb_res) <- tryTcLIE main
642 Just val -> do { addMessages msgs -- There might be warnings
644 Nothing -> recover -- Discard all msgs
647 -----------------------
648 checkNoErrs :: TcM r -> TcM r
649 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
650 -- If m fails then (checkNoErrsTc m) fails.
651 -- If m succeeds, it checks whether m generated any errors messages
652 -- (it might have recovered internally)
653 -- If so, it fails too.
654 -- Regardless, any errors generated by m are propagated to the enclosing context.
656 = do { (msgs, mb_res) <- tryTcLIE main
660 Just val -> return val
663 ifErrsM :: TcRn r -> TcRn r -> TcRn r
664 -- ifErrsM bale_out main
665 -- does 'bale_out' if there are errors in errors collection
666 -- otherwise does 'main'
667 ifErrsM bale_out normal
668 = do { errs_var <- getErrsVar ;
669 msgs <- readMutVar errs_var ;
671 if errorsFound dflags msgs then
676 failIfErrsM :: TcRn ()
677 -- Useful to avoid error cascades
678 failIfErrsM = ifErrsM failM (return ())
682 %************************************************************************
684 Context management and error message generation
687 %************************************************************************
690 getErrCtxt :: TcM ErrCtxt
691 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
693 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
694 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
696 addErrCtxt :: Message -> TcM a -> TcM a
697 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
699 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
700 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
702 -- Helper function for the above
703 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
704 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
705 env { tcl_ctxt = upd ctxt })
707 -- Conditionally add an error context
708 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
709 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
710 maybeAddErrCtxt Nothing thing_inside = thing_inside
712 popErrCtxt :: TcM a -> TcM a
713 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
715 getInstLoc :: InstOrigin -> TcM InstLoc
717 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
718 return (InstLoc origin loc (tcl_ctxt env)) }
720 addInstCtxt :: InstLoc -> TcM a -> TcM a
721 -- Add the SrcSpan and context from the first Inst in the list
722 -- (they all have similar locations)
723 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
724 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
727 The addErrTc functions add an error message, but do not cause failure.
728 The 'M' variants pass a TidyEnv that has already been used to
729 tidy up the message; we then use it to tidy the context messages
732 addErrTc :: Message -> TcM ()
733 addErrTc err_msg = do { env0 <- tcInitTidyEnv
734 ; addErrTcM (env0, err_msg) }
736 addErrsTc :: [Message] -> TcM ()
737 addErrsTc err_msgs = mappM_ addErrTc err_msgs
739 addErrTcM :: (TidyEnv, Message) -> TcM ()
740 addErrTcM (tidy_env, err_msg)
741 = do { ctxt <- getErrCtxt ;
743 add_err_tcm tidy_env err_msg loc ctxt }
746 The failWith functions add an error message and cause failure
749 failWithTc :: Message -> TcM a -- Add an error message and fail
751 = addErrTc err_msg >> failM
753 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
754 failWithTcM local_and_msg
755 = addErrTcM local_and_msg >> failM
757 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
758 checkTc True err = returnM ()
759 checkTc False err = failWithTc err
762 Warnings have no 'M' variant, nor failure
765 addWarnTc :: Message -> TcM ()
767 = do { ctxt <- getErrCtxt ;
768 env0 <- tcInitTidyEnv ;
769 ctxt_msgs <- do_ctxt env0 ctxt ;
770 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
772 warnTc :: Bool -> Message -> TcM ()
773 warnTc warn_if_true warn_msg
774 | warn_if_true = addWarnTc warn_msg
775 | otherwise = return ()
778 -----------------------------------
781 We initialise the "tidy-env", used for tidying types before printing,
782 by building a reverse map from the in-scope type variables to the
783 OccName that the programmer originally used for them
786 tcInitTidyEnv :: TcM TidyEnv
788 = do { lcl_env <- getLclEnv
789 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
790 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
792 ; return (foldl add emptyTidyEnv nm_tv_prs) }
794 add (env,subst) (name, tyvar)
795 = case tidyOccName env (nameOccName name) of
796 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
798 tyvar' = setTyVarName tyvar name'
799 name' = tidyNameOcc name occ'
802 -----------------------------------
803 Other helper functions
806 add_err_tcm tidy_env err_msg loc ctxt
807 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
808 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
812 do_ctxt tidy_env (c:cs)
813 = do { (tidy_env', m) <- c tidy_env ;
814 ms <- do_ctxt tidy_env' cs ;
817 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
818 | otherwise = take 3 ctxt
821 debugTc is useful for monadic debugging code
824 debugTc :: TcM () -> TcM ()
826 debugTc thing = thing
828 debugTc thing = return ()
832 %************************************************************************
834 Type constraints (the so-called LIE)
836 %************************************************************************
839 nextDFunIndex :: TcM Int -- Get the next dfun index
840 nextDFunIndex = do { env <- getGblEnv
841 ; let dfun_n_var = tcg_dfun_n env
842 ; n <- readMutVar dfun_n_var
843 ; writeMutVar dfun_n_var (n+1)
846 getLIEVar :: TcM (TcRef LIE)
847 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
849 setLIEVar :: TcRef LIE -> TcM a -> TcM a
850 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
852 getLIE :: TcM a -> TcM (a, [Inst])
853 -- (getLIE m) runs m, and returns the type constraints it generates
855 = do { lie_var <- newMutVar emptyLIE ;
856 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
858 lie <- readMutVar lie_var ;
859 return (res, lieToList lie) }
861 extendLIE :: Inst -> TcM ()
863 = do { lie_var <- getLIEVar ;
864 lie <- readMutVar lie_var ;
865 writeMutVar lie_var (inst `consLIE` lie) }
867 extendLIEs :: [Inst] -> TcM ()
871 = do { lie_var <- getLIEVar ;
872 lie <- readMutVar lie_var ;
873 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
877 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
878 -- Set the local type envt, but do *not* disturb other fields,
879 -- notably the lie_var
880 setLclTypeEnv lcl_env thing_inside
881 = updLclEnv upd thing_inside
883 upd env = env { tcl_env = tcl_env lcl_env,
884 tcl_tyvars = tcl_tyvars lcl_env }
888 %************************************************************************
890 Template Haskell context
892 %************************************************************************
895 recordThUse :: TcM ()
896 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
898 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
899 keepAliveTc n = do { env <- getGblEnv;
900 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
902 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
903 keepAliveSetTc ns = do { env <- getGblEnv;
904 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
906 getStage :: TcM ThStage
907 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
909 setStage :: ThStage -> TcM a -> TcM a
910 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
914 %************************************************************************
916 Stuff for the renamer's local env
918 %************************************************************************
921 getLocalRdrEnv :: RnM LocalRdrEnv
922 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
924 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
925 setLocalRdrEnv rdr_env thing_inside
926 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
930 %************************************************************************
932 Stuff for interface decls
934 %************************************************************************
937 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
938 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
940 if_tv_env = emptyOccEnv,
941 if_id_env = emptyOccEnv }
943 initIfaceTcRn :: IfG a -> TcRn a
944 initIfaceTcRn thing_inside
945 = do { tcg_env <- getGblEnv
946 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
947 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
948 ; setEnvs (if_env, ()) thing_inside }
950 initIfaceExtCore :: IfL a -> TcRn a
951 initIfaceExtCore thing_inside
952 = do { tcg_env <- getGblEnv
953 ; let { mod = tcg_mod tcg_env
954 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
955 ; if_env = IfGblEnv {
956 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
957 ; if_lenv = mkIfLclEnv mod doc
959 ; setEnvs (if_env, if_lenv) thing_inside }
961 initIfaceCheck :: HscEnv -> IfG a -> IO a
962 -- Used when checking the up-to-date-ness of the old Iface
963 -- Initialise the environment with no useful info at all
964 initIfaceCheck hsc_env do_this
965 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
966 ; initTcRnIf 'i' hsc_env gbl_env () do_this
969 initIfaceTc :: ModIface
970 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
971 -- Used when type-checking checking an up-to-date interface file
972 -- No type envt from the current module, but we do know the module dependencies
973 initIfaceTc iface do_this
974 = do { tc_env_var <- newMutVar emptyTypeEnv
975 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
976 ; if_lenv = mkIfLclEnv mod doc
978 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
981 mod = mi_module iface
982 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
984 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
985 -- Used when sucking in new Rules in SimplCore
986 -- We have available the type envt of the module being compiled, and we must use it
987 initIfaceRules hsc_env guts do_this
989 type_info = (mg_module guts, return (mg_types guts))
990 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
993 -- Run the thing; any exceptions just bubble out from here
994 ; initTcRnIf 'i' hsc_env gbl_env () do_this
997 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
998 initIfaceLcl mod loc_doc thing_inside
999 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1001 getIfModule :: IfL Module
1002 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1004 --------------------
1005 failIfM :: Message -> IfL a
1006 -- The Iface monad doesn't have a place to accumulate errors, so we
1007 -- just fall over fast if one happens; it "shouldnt happen".
1008 -- We use IfL here so that we can get context info out of the local env
1010 = do { env <- getLclEnv
1011 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1012 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
1015 --------------------
1016 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1017 -- Run thing_inside in an interleaved thread.
1018 -- It shares everything with the parent thread, so this is DANGEROUS.
1020 -- It returns Nothing if the computation fails
1022 -- It's used for lazily type-checking interface
1023 -- signatures, which is pretty benign
1025 forkM_maybe doc thing_inside
1026 = do { unsafeInterleaveM $
1027 do { traceIf (text "Starting fork {" <+> doc)
1029 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1032 Right r -> do { traceIf (text "} ending fork" <+> doc)
1036 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1037 -- Otherwise we silently discard errors. Errors can legitimately
1038 -- happen when compiling interface signatures (see tcInterfaceSigs)
1039 ifOptM Opt_D_dump_if_trace
1040 (print_errs (hang (text "forkM failed:" <+> doc)
1041 4 (text (show exn))))
1043 ; traceIf (text "} ending fork (badly)" <+> doc)
1047 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1049 forkM :: SDoc -> IfL a -> IfL a
1050 forkM doc thing_inside
1051 = do { mb_res <- forkM_maybe doc thing_inside
1052 ; return (case mb_res of
1053 Nothing -> pgmError "Cannot continue after interface file error"
1054 -- pprPanic "forkM" doc