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,
123 tcg_dfun_n = dfun_n_var,
126 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing
130 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
132 tcl_rdr = emptyLocalRdrEnv,
133 tcl_th_ctxt = topStage,
134 tcl_arrow_ctxt = NoArrowCtxt,
135 tcl_env = emptyNameEnv,
136 tcl_tyvars = tvs_var,
137 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
141 -- OK, here's the business end!
142 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
143 addBreakpointBindings $
144 do { r <- tryM do_this
146 Right res -> return (Just res)
147 Left _ -> return Nothing } ;
149 -- Collect any error messages
150 msgs <- readIORef errs_var ;
152 let { dflags = hsc_dflags hsc_env
153 ; final_res | errorsFound dflags msgs = Nothing
154 | otherwise = maybe_res } ;
156 return (msgs, final_res)
159 init_imports = emptyImportAvails {imp_env =
160 unitUFM (moduleName mod) emptyNameSet}
161 -- Initialise tcg_imports with an empty set of bindings for
162 -- this module, so that if we see 'module M' in the export
163 -- list, and there are no bindings in M, we don't bleat
164 -- "unknown module M".
166 initTcPrintErrors -- Used from the interactive loop only
171 initTcPrintErrors env mod todo = do
172 (msgs, res) <- initTc env HsSrcFile mod todo
173 printErrorsAndWarnings (hsc_dflags env) msgs
178 addBreakpointBindings :: TcM a -> TcM a
179 addBreakpointBindings thing_inside
180 #if defined(GHCI) && defined(BREAKPOINT)
181 = do { unique <- newUnique
182 ; let { var = mkInternalName unique (mkOccName tvName "a") noSrcLoc;
183 tyvar = mkTyVar var liftedTypeKind;
184 basicType extra = (FunTy intTy
185 (FunTy (mkListTy unitTy)
189 (FunTy (TyVarTy tyvar)
190 (TyVarTy tyvar)))))));
192 = mkGlobalId VanillaGlobal breakpointJumpName
193 (basicType id) vanillaIdInfo;
195 = mkGlobalId VanillaGlobal breakpointCondJumpName
196 (basicType (FunTy boolTy)) vanillaIdInfo
198 ; tcExtendIdEnv [breakpointJumpId, breakpointCondJumpId] thing_inside}
204 %************************************************************************
208 %************************************************************************
212 initTcRnIf :: Char -- Tag for unique supply
217 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
218 = do { us <- mkSplitUniqSupply uniq_tag ;
219 ; us_var <- newIORef us ;
221 ; let { env = Env { env_top = hsc_env,
224 env_lcl = lcl_env } }
226 ; runIOEnv env thing_inside
230 %************************************************************************
234 %************************************************************************
237 getTopEnv :: TcRnIf gbl lcl HscEnv
238 getTopEnv = do { env <- getEnv; return (env_top env) }
240 getGblEnv :: TcRnIf gbl lcl gbl
241 getGblEnv = do { env <- getEnv; return (env_gbl env) }
243 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
244 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
245 env { env_gbl = upd gbl })
247 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
248 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
250 getLclEnv :: TcRnIf gbl lcl lcl
251 getLclEnv = do { env <- getEnv; return (env_lcl env) }
253 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
254 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
255 env { env_lcl = upd lcl })
257 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
258 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
260 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
261 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
263 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
264 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
271 getDOpts :: TcRnIf gbl lcl DynFlags
272 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
274 doptM :: DynFlag -> TcRnIf gbl lcl Bool
275 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
277 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
278 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
279 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
281 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
282 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
283 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
285 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
286 ifOptM flag thing_inside = do { b <- doptM flag;
287 if b then thing_inside else return () }
289 getGhcMode :: TcRnIf gbl lcl GhcMode
290 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
294 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
295 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
297 getEps :: TcRnIf gbl lcl ExternalPackageState
298 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
300 -- Updating the EPS. This should be an atomic operation.
301 -- Note the delicate 'seq' which forces the EPS before putting it in the
302 -- variable. Otherwise what happens is that we get
303 -- write eps_var (....(unsafeRead eps_var)....)
304 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
305 -- we make the unsafeRead happen before we update the variable.
307 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
309 updateEps upd_fn = do { traceIf (text "updating EPS")
310 ; eps_var <- getEpsVar
311 ; eps <- readMutVar eps_var
312 ; let { (eps', val) = upd_fn eps }
313 ; seq eps' (writeMutVar eps_var eps')
316 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
318 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
319 ; eps_var <- getEpsVar
320 ; eps <- readMutVar eps_var
321 ; let { eps' = upd_fn eps }
322 ; seq eps' (writeMutVar eps_var eps') }
324 getHpt :: TcRnIf gbl lcl HomePackageTable
325 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
327 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
328 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
329 ; return (eps, hsc_HPT env) }
332 %************************************************************************
336 %************************************************************************
339 newUnique :: TcRnIf gbl lcl Unique
341 = do { env <- getEnv ;
342 let { u_var = env_us env } ;
343 us <- readMutVar u_var ;
344 case splitUniqSupply us of { (us1,_) -> do {
345 writeMutVar u_var us1 ;
346 return $! uniqFromSupply us }}}
347 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
348 -- a chain of unevaluated supplies behind.
349 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
350 -- throw away one half of the new split supply. This is safe because this
351 -- is the only place we use that unique. Using the other half of the split
352 -- supply is safer, but slower.
354 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
356 = do { env <- getEnv ;
357 let { u_var = env_us env } ;
358 us <- readMutVar u_var ;
359 case splitUniqSupply us of { (us1,us2) -> do {
360 writeMutVar u_var us1 ;
363 newLocalName :: Name -> TcRnIf gbl lcl Name
364 newLocalName name -- Make a clone
365 = do { uniq <- newUnique
366 ; return (mkInternalName uniq (nameOccName name) (getSrcLoc name)) }
368 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
369 newSysLocalIds fs tys
370 = do { us <- newUniqueSupply
371 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
375 %************************************************************************
379 %************************************************************************
382 traceTc, traceRn :: SDoc -> TcRn ()
383 traceRn = traceOptTcRn Opt_D_dump_rn_trace
384 traceTc = traceOptTcRn Opt_D_dump_tc_trace
385 traceSplice = traceOptTcRn Opt_D_dump_splices
388 traceIf :: SDoc -> TcRnIf m n ()
389 traceIf = traceOptIf Opt_D_dump_if_trace
390 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
393 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
394 traceOptIf flag doc = ifOptM flag $
395 ioToIOEnv (printForUser stderr alwaysQualify doc)
397 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
398 traceOptTcRn flag doc = ifOptM flag $ do
401 ; env0 <- tcInitTidyEnv
402 ; ctxt_msgs <- do_ctxt env0 ctxt
403 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
404 ; dumpTcRn real_doc }
406 dumpTcRn :: SDoc -> TcRn ()
407 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
408 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
410 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
411 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
415 %************************************************************************
417 Typechecker global environment
419 %************************************************************************
422 getModule :: TcRn Module
423 getModule = do { env <- getGblEnv; return (tcg_mod env) }
425 setModule :: Module -> TcRn a -> TcRn a
426 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
428 tcIsHsBoot :: TcRn Bool
429 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
431 getGlobalRdrEnv :: TcRn GlobalRdrEnv
432 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
434 getImports :: TcRn ImportAvails
435 getImports = do { env <- getGblEnv; return (tcg_imports env) }
437 getFixityEnv :: TcRn FixityEnv
438 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
440 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
441 extendFixityEnv new_bit
442 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
443 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
445 getDefaultTys :: TcRn (Maybe [Type])
446 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
449 %************************************************************************
453 %************************************************************************
456 getSrcSpanM :: TcRn SrcSpan
457 -- Avoid clash with Name.getSrcLoc
458 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
460 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
461 setSrcSpan loc thing_inside
462 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
463 | otherwise = thing_inside -- Don't overwrite useful info with useless
465 addLocM :: (a -> TcM b) -> Located a -> TcM b
466 addLocM fn (L loc a) = setSrcSpan loc $ fn a
468 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
469 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
471 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
472 wrapLocFstM fn (L loc a) =
477 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
478 wrapLocSndM fn (L loc a) =
486 getErrsVar :: TcRn (TcRef Messages)
487 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
489 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
490 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
492 addErr :: Message -> TcRn ()
493 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
495 addLocErr :: Located e -> (e -> Message) -> TcRn ()
496 addLocErr (L loc e) fn = addErrAt loc (fn e)
498 addErrAt :: SrcSpan -> Message -> TcRn ()
499 addErrAt loc msg = addLongErrAt loc msg empty
501 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
502 addLongErrAt loc msg extra
503 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
504 errs_var <- getErrsVar ;
505 rdr_env <- getGlobalRdrEnv ;
506 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
507 (warns, errs) <- readMutVar errs_var ;
508 writeMutVar errs_var (warns, errs `snocBag` err) }
510 addErrs :: [(SrcSpan,Message)] -> TcRn ()
511 addErrs msgs = mappM_ add msgs
513 add (loc,msg) = addErrAt loc msg
515 addReport :: Message -> TcRn ()
516 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
518 addReportAt :: SrcSpan -> Message -> TcRn ()
520 = do { errs_var <- getErrsVar ;
521 rdr_env <- getGlobalRdrEnv ;
522 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
523 (warns, errs) <- readMutVar errs_var ;
524 writeMutVar errs_var (warns `snocBag` warn, errs) }
526 addWarn :: Message -> TcRn ()
527 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
529 addWarnAt :: SrcSpan -> Message -> TcRn ()
530 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
532 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
533 addLocWarn (L loc e) fn = addReportAt loc (fn e)
535 checkErr :: Bool -> Message -> TcRn ()
536 -- Add the error if the bool is False
537 checkErr ok msg = checkM ok (addErr msg)
539 warnIf :: Bool -> Message -> TcRn ()
540 warnIf True msg = addWarn msg
541 warnIf False msg = return ()
543 addMessages :: Messages -> TcRn ()
544 addMessages (m_warns, m_errs)
545 = do { errs_var <- getErrsVar ;
546 (warns, errs) <- readMutVar errs_var ;
547 writeMutVar errs_var (warns `unionBags` m_warns,
548 errs `unionBags` m_errs) }
550 discardWarnings :: TcRn a -> TcRn a
551 -- Ignore warnings inside the thing inside;
552 -- used to ignore-unused-variable warnings inside derived code
553 -- With -dppr-debug, the effects is switched off, so you can still see
554 -- what warnings derived code would give
555 discardWarnings thing_inside
556 | opt_PprStyle_Debug = thing_inside
558 = do { errs_var <- newMutVar emptyMessages
559 ; result <- setErrsVar errs_var thing_inside
560 ; (_warns, errs) <- readMutVar errs_var
561 ; addMessages (emptyBag, errs)
567 try_m :: TcRn r -> TcRn (Either Exception r)
568 -- Does try_m, with a debug-trace on failure
570 = do { mb_r <- tryM thing ;
572 Left exn -> do { traceTc (exn_msg exn); return mb_r }
573 Right r -> return mb_r }
575 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
577 -----------------------
578 recoverM :: TcRn r -- Recovery action; do this if the main one fails
579 -> TcRn r -- Main action: do this first
581 -- Errors in 'thing' are retained
582 recoverM recover thing
583 = do { mb_res <- try_m thing ;
586 Right res -> returnM res }
588 -----------------------
589 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
590 -- (tryTc m) executes m, and returns
591 -- Just r, if m succeeds (returning r)
592 -- Nothing, if m fails
593 -- It also returns all the errors and warnings accumulated by m
594 -- It always succeeds (never raises an exception)
596 = do { errs_var <- newMutVar emptyMessages ;
597 res <- try_m (setErrsVar errs_var m) ;
598 msgs <- readMutVar errs_var ;
599 return (msgs, case res of
601 Right val -> Just val)
602 -- The exception is always the IOEnv built-in
603 -- in exception; see IOEnv.failM
606 -----------------------
607 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
608 -- Run the thing, returning
609 -- Just r, if m succceeds with no error messages
610 -- Nothing, if m fails, or if it succeeds but has error messages
611 -- Either way, the messages are returned; even in the Just case
612 -- there might be warnings
614 = do { (msgs, res) <- tryTc thing
616 ; let errs_found = errorsFound dflags msgs
617 ; return (msgs, case res of
619 Just val | errs_found -> Nothing
620 | otherwise -> Just val)
623 -----------------------
624 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
625 -- Just like tryTcErrs, except that it ensures that the LIE
626 -- for the thing is propagated only if there are no errors
627 -- Hence it's restricted to the type-check monad
628 tryTcLIE thing_inside
629 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
631 Nothing -> return (msgs, Nothing)
632 Just val -> do { extendLIEs lie; return (msgs, Just val) }
635 -----------------------
636 tryTcLIE_ :: TcM r -> TcM r -> TcM r
637 -- (tryTcLIE_ r m) tries m;
638 -- if m succeeds with no error messages, it's the answer
639 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
640 tryTcLIE_ recover main
641 = do { (msgs, mb_res) <- tryTcLIE main
643 Just val -> do { addMessages msgs -- There might be warnings
645 Nothing -> recover -- Discard all msgs
648 -----------------------
649 checkNoErrs :: TcM r -> TcM r
650 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
651 -- If m fails then (checkNoErrsTc m) fails.
652 -- If m succeeds, it checks whether m generated any errors messages
653 -- (it might have recovered internally)
654 -- If so, it fails too.
655 -- Regardless, any errors generated by m are propagated to the enclosing context.
657 = do { (msgs, mb_res) <- tryTcLIE main
661 Just val -> return val
664 ifErrsM :: TcRn r -> TcRn r -> TcRn r
665 -- ifErrsM bale_out main
666 -- does 'bale_out' if there are errors in errors collection
667 -- otherwise does 'main'
668 ifErrsM bale_out normal
669 = do { errs_var <- getErrsVar ;
670 msgs <- readMutVar errs_var ;
672 if errorsFound dflags msgs then
677 failIfErrsM :: TcRn ()
678 -- Useful to avoid error cascades
679 failIfErrsM = ifErrsM failM (return ())
683 %************************************************************************
685 Context management and error message generation
688 %************************************************************************
691 getErrCtxt :: TcM ErrCtxt
692 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
694 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
695 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
697 addErrCtxt :: Message -> TcM a -> TcM a
698 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
700 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
701 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
703 -- Helper function for the above
704 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
705 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
706 env { tcl_ctxt = upd ctxt })
708 -- Conditionally add an error context
709 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
710 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
711 maybeAddErrCtxt Nothing thing_inside = thing_inside
713 popErrCtxt :: TcM a -> TcM a
714 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
716 getInstLoc :: InstOrigin -> TcM InstLoc
718 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
719 return (InstLoc origin loc (tcl_ctxt env)) }
721 addInstCtxt :: InstLoc -> TcM a -> TcM a
722 -- Add the SrcSpan and context from the first Inst in the list
723 -- (they all have similar locations)
724 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
725 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
728 The addErrTc functions add an error message, but do not cause failure.
729 The 'M' variants pass a TidyEnv that has already been used to
730 tidy up the message; we then use it to tidy the context messages
733 addErrTc :: Message -> TcM ()
734 addErrTc err_msg = do { env0 <- tcInitTidyEnv
735 ; addErrTcM (env0, err_msg) }
737 addErrsTc :: [Message] -> TcM ()
738 addErrsTc err_msgs = mappM_ addErrTc err_msgs
740 addErrTcM :: (TidyEnv, Message) -> TcM ()
741 addErrTcM (tidy_env, err_msg)
742 = do { ctxt <- getErrCtxt ;
744 add_err_tcm tidy_env err_msg loc ctxt }
747 The failWith functions add an error message and cause failure
750 failWithTc :: Message -> TcM a -- Add an error message and fail
752 = addErrTc err_msg >> failM
754 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
755 failWithTcM local_and_msg
756 = addErrTcM local_and_msg >> failM
758 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
759 checkTc True err = returnM ()
760 checkTc False err = failWithTc err
763 Warnings have no 'M' variant, nor failure
766 addWarnTc :: Message -> TcM ()
768 = do { ctxt <- getErrCtxt ;
769 env0 <- tcInitTidyEnv ;
770 ctxt_msgs <- do_ctxt env0 ctxt ;
771 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
773 warnTc :: Bool -> Message -> TcM ()
774 warnTc warn_if_true warn_msg
775 | warn_if_true = addWarnTc warn_msg
776 | otherwise = return ()
779 -----------------------------------
782 We initialise the "tidy-env", used for tidying types before printing,
783 by building a reverse map from the in-scope type variables to the
784 OccName that the programmer originally used for them
787 tcInitTidyEnv :: TcM TidyEnv
789 = do { lcl_env <- getLclEnv
790 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
791 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
793 ; return (foldl add emptyTidyEnv nm_tv_prs) }
795 add (env,subst) (name, tyvar)
796 = case tidyOccName env (nameOccName name) of
797 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
799 tyvar' = setTyVarName tyvar name'
800 name' = tidyNameOcc name occ'
803 -----------------------------------
804 Other helper functions
807 add_err_tcm tidy_env err_msg loc ctxt
808 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
809 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
813 do_ctxt tidy_env (c:cs)
814 = do { (tidy_env', m) <- c tidy_env ;
815 ms <- do_ctxt tidy_env' cs ;
818 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
819 | otherwise = take 3 ctxt
822 debugTc is useful for monadic debugging code
825 debugTc :: TcM () -> TcM ()
827 debugTc thing = thing
829 debugTc thing = return ()
833 %************************************************************************
835 Type constraints (the so-called LIE)
837 %************************************************************************
840 nextDFunIndex :: TcM Int -- Get the next dfun index
841 nextDFunIndex = do { env <- getGblEnv
842 ; let dfun_n_var = tcg_dfun_n env
843 ; n <- readMutVar dfun_n_var
844 ; writeMutVar dfun_n_var (n+1)
847 getLIEVar :: TcM (TcRef LIE)
848 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
850 setLIEVar :: TcRef LIE -> TcM a -> TcM a
851 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
853 getLIE :: TcM a -> TcM (a, [Inst])
854 -- (getLIE m) runs m, and returns the type constraints it generates
856 = do { lie_var <- newMutVar emptyLIE ;
857 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
859 lie <- readMutVar lie_var ;
860 return (res, lieToList lie) }
862 extendLIE :: Inst -> TcM ()
864 = do { lie_var <- getLIEVar ;
865 lie <- readMutVar lie_var ;
866 writeMutVar lie_var (inst `consLIE` lie) }
868 extendLIEs :: [Inst] -> TcM ()
872 = do { lie_var <- getLIEVar ;
873 lie <- readMutVar lie_var ;
874 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
878 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
879 -- Set the local type envt, but do *not* disturb other fields,
880 -- notably the lie_var
881 setLclTypeEnv lcl_env thing_inside
882 = updLclEnv upd thing_inside
884 upd env = env { tcl_env = tcl_env lcl_env,
885 tcl_tyvars = tcl_tyvars lcl_env }
889 %************************************************************************
891 Template Haskell context
893 %************************************************************************
896 recordThUse :: TcM ()
897 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
899 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
900 keepAliveTc n = do { env <- getGblEnv;
901 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
903 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
904 keepAliveSetTc ns = do { env <- getGblEnv;
905 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
907 getStage :: TcM ThStage
908 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
910 setStage :: ThStage -> TcM a -> TcM a
911 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
915 %************************************************************************
917 Stuff for the renamer's local env
919 %************************************************************************
922 getLocalRdrEnv :: RnM LocalRdrEnv
923 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
925 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
926 setLocalRdrEnv rdr_env thing_inside
927 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
931 %************************************************************************
933 Stuff for interface decls
935 %************************************************************************
938 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
939 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
941 if_tv_env = emptyOccEnv,
942 if_id_env = emptyOccEnv }
944 initIfaceTcRn :: IfG a -> TcRn a
945 initIfaceTcRn thing_inside
946 = do { tcg_env <- getGblEnv
947 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
948 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
949 ; setEnvs (if_env, ()) thing_inside }
951 initIfaceExtCore :: IfL a -> TcRn a
952 initIfaceExtCore thing_inside
953 = do { tcg_env <- getGblEnv
954 ; let { mod = tcg_mod tcg_env
955 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
956 ; if_env = IfGblEnv {
957 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
958 ; if_lenv = mkIfLclEnv mod doc
960 ; setEnvs (if_env, if_lenv) thing_inside }
962 initIfaceCheck :: HscEnv -> IfG a -> IO a
963 -- Used when checking the up-to-date-ness of the old Iface
964 -- Initialise the environment with no useful info at all
965 initIfaceCheck hsc_env do_this
966 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
967 ; initTcRnIf 'i' hsc_env gbl_env () do_this
970 initIfaceTc :: ModIface
971 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
972 -- Used when type-checking checking an up-to-date interface file
973 -- No type envt from the current module, but we do know the module dependencies
974 initIfaceTc iface do_this
975 = do { tc_env_var <- newMutVar emptyTypeEnv
976 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
977 ; if_lenv = mkIfLclEnv mod doc
979 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
982 mod = mi_module iface
983 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
985 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
986 -- Used when sucking in new Rules in SimplCore
987 -- We have available the type envt of the module being compiled, and we must use it
988 initIfaceRules hsc_env guts do_this
990 type_info = (mg_module guts, return (mg_types guts))
991 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
994 -- Run the thing; any exceptions just bubble out from here
995 ; initTcRnIf 'i' hsc_env gbl_env () do_this
998 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
999 initIfaceLcl mod loc_doc thing_inside
1000 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1002 getIfModule :: IfL Module
1003 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1005 --------------------
1006 failIfM :: Message -> IfL a
1007 -- The Iface monad doesn't have a place to accumulate errors, so we
1008 -- just fall over fast if one happens; it "shouldnt happen".
1009 -- We use IfL here so that we can get context info out of the local env
1011 = do { env <- getLclEnv
1012 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1013 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
1016 --------------------
1017 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1018 -- Run thing_inside in an interleaved thread.
1019 -- It shares everything with the parent thread, so this is DANGEROUS.
1021 -- It returns Nothing if the computation fails
1023 -- It's used for lazily type-checking interface
1024 -- signatures, which is pretty benign
1026 forkM_maybe doc thing_inside
1027 = do { unsafeInterleaveM $
1028 do { traceIf (text "Starting fork {" <+> doc)
1030 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1033 Right r -> do { traceIf (text "} ending fork" <+> doc)
1037 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1038 -- Otherwise we silently discard errors. Errors can legitimately
1039 -- happen when compiling interface signatures (see tcInterfaceSigs)
1040 ifOptM Opt_D_dump_if_trace
1041 (print_errs (hang (text "forkM failed:" <+> doc)
1042 4 (text (show exn))))
1044 ; traceIf (text "} ending fork (badly)" <+> doc)
1048 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1050 forkM :: SDoc -> IfL a -> IfL a
1051 forkM doc thing_inside
1052 = do { mb_res <- forkM_maybe doc thing_inside
1053 ; return (case mb_res of
1054 Nothing -> pgmError "Cannot continue after interface file error"
1055 -- pprPanic "forkM" doc