8 #include "HsVersions.h"
10 import TcRnTypes -- Re-export all
11 import IOEnv -- Re-export all
13 import HsSyn ( emptyLHsBinds )
14 import HscTypes ( HscEnv(..), ModGuts(..), ModIface(..),
15 TyThing, TypeEnv, emptyTypeEnv, HscSource(..),
16 isHsBoot, ModSummary(..),
17 ExternalPackageState(..), HomePackageTable,
18 Deprecs(..), FixityEnv, FixItem,
19 lookupType, unQualInScope )
20 import Module ( Module, unitModuleEnv )
21 import RdrName ( GlobalRdrEnv, emptyGlobalRdrEnv,
22 LocalRdrEnv, emptyLocalRdrEnv )
23 import Name ( Name, isInternalName, mkInternalName, tidyNameOcc, nameOccName, getSrcLoc )
25 import TcType ( tcIsTyVarTy, tcGetTyVar )
26 import NameEnv ( extendNameEnvList, nameEnvElts )
27 import InstEnv ( emptyInstEnv )
29 import Var ( setTyVarName )
30 import VarSet ( emptyVarSet )
31 import VarEnv ( TidyEnv, emptyTidyEnv, extendVarEnv )
32 import ErrUtils ( Message, Messages, emptyMessages, errorsFound,
33 mkWarnMsg, printErrorsAndWarnings,
34 mkLocMessage, mkLongErrMsg )
35 import Packages ( mkHomeModules )
36 import SrcLoc ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
37 import NameEnv ( emptyNameEnv )
38 import NameSet ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
39 import OccName ( emptyOccEnv, tidyOccName )
40 import Bag ( emptyBag )
42 import UniqSupply ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
43 import Unique ( Unique )
44 import DynFlags ( DynFlags(..), DynFlag(..), dopt, dopt_set, GhcMode )
45 import StaticFlags ( opt_PprStyle_Debug )
46 import Bag ( snocBag, unionBags )
47 import Panic ( showException )
50 import DATA_IOREF ( newIORef, readIORef )
51 import EXCEPTION ( Exception )
56 %************************************************************************
60 %************************************************************************
63 ioToTcRn :: IO r -> TcRn r
72 -> IO (Messages, Maybe r)
73 -- Nothing => error thrown by the thing inside
74 -- (error messages should have been printed already)
76 initTc hsc_env hsc_src mod do_this
77 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
78 tvs_var <- newIORef emptyVarSet ;
79 type_env_var <- newIORef emptyNameEnv ;
80 dfuns_var <- newIORef emptyNameSet ;
81 keep_var <- newIORef emptyNameSet ;
82 th_var <- newIORef False ;
83 dfun_n_var <- newIORef 1 ;
89 tcg_rdr_env = emptyGlobalRdrEnv,
90 tcg_fix_env = emptyNameEnv,
91 tcg_default = Nothing,
92 tcg_type_env = emptyNameEnv,
93 tcg_type_env_var = type_env_var,
94 tcg_inst_env = emptyInstEnv,
95 tcg_inst_uses = dfuns_var,
97 tcg_exports = emptyNameSet,
98 tcg_imports = init_imports,
99 tcg_home_mods = home_mods,
101 tcg_rn_imports = Nothing,
102 tcg_rn_exports = Nothing,
103 tcg_rn_decls = Nothing,
104 tcg_binds = emptyLHsBinds,
105 tcg_deprecs = NoDeprecs,
109 tcg_dfun_n = dfun_n_var,
114 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
116 tcl_rdr = emptyLocalRdrEnv,
117 tcl_th_ctxt = topStage,
118 tcl_arrow_ctxt = NoArrowCtxt,
119 tcl_env = emptyNameEnv,
120 tcl_tyvars = tvs_var,
121 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
125 -- OK, here's the business end!
126 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
127 do { r <- tryM do_this
129 Right res -> return (Just res)
130 Left _ -> return Nothing } ;
132 -- Collect any error messages
133 msgs <- readIORef errs_var ;
135 let { dflags = hsc_dflags hsc_env
136 ; final_res | errorsFound dflags msgs = Nothing
137 | otherwise = maybe_res } ;
139 return (msgs, final_res)
142 home_mods = mkHomeModules (map ms_mod (hsc_mod_graph hsc_env))
143 -- A guess at the home modules. This will be correct in
144 -- --make and GHCi modes, but in one-shot mode we need to
145 -- fix it up after we know the real dependencies of the current
146 -- module (see tcRnModule).
147 -- Setting it here is necessary for the typechecker entry points
148 -- other than tcRnModule: tcRnGetInfo, for example. These are
149 -- all called via the GHC module, so hsc_mod_graph will contain
150 -- something sensible.
152 init_imports = emptyImportAvails {imp_env = unitModuleEnv mod emptyNameSet}
153 -- Initialise tcg_imports with an empty set of bindings for
154 -- this module, so that if we see 'module M' in the export
155 -- list, and there are no bindings in M, we don't bleat
156 -- "unknown module M".
158 initTcPrintErrors -- Used from the interactive loop only
163 initTcPrintErrors env mod todo = do
164 (msgs, res) <- initTc env HsSrcFile mod todo
165 printErrorsAndWarnings (hsc_dflags env) msgs
168 -- mkImpTypeEnv makes the imported symbol table
169 mkImpTypeEnv :: ExternalPackageState -> HomePackageTable
170 -> Name -> Maybe TyThing
171 mkImpTypeEnv pcs hpt = lookup
174 lookup name | isInternalName name = Nothing
175 | otherwise = lookupType hpt pte name
179 %************************************************************************
183 %************************************************************************
187 initTcRnIf :: Char -- Tag for unique supply
192 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
193 = do { us <- mkSplitUniqSupply uniq_tag ;
194 ; us_var <- newIORef us ;
196 ; let { env = Env { env_top = hsc_env,
199 env_lcl = lcl_env } }
201 ; runIOEnv env thing_inside
205 %************************************************************************
209 %************************************************************************
212 getTopEnv :: TcRnIf gbl lcl HscEnv
213 getTopEnv = do { env <- getEnv; return (env_top env) }
215 getGblEnv :: TcRnIf gbl lcl gbl
216 getGblEnv = do { env <- getEnv; return (env_gbl env) }
218 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
219 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
220 env { env_gbl = upd gbl })
222 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
223 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
225 getLclEnv :: TcRnIf gbl lcl lcl
226 getLclEnv = do { env <- getEnv; return (env_lcl env) }
228 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
229 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
230 env { env_lcl = upd lcl })
232 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
233 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
235 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
236 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
238 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
239 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
246 getDOpts :: TcRnIf gbl lcl DynFlags
247 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
249 doptM :: DynFlag -> TcRnIf gbl lcl Bool
250 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
252 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
253 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
254 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
256 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
257 ifOptM flag thing_inside = do { b <- doptM flag;
258 if b then thing_inside else return () }
260 getGhciMode :: TcRnIf gbl lcl GhcMode
261 getGhciMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
265 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
266 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
268 getEps :: TcRnIf gbl lcl ExternalPackageState
269 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
271 -- Updating the EPS. This should be an atomic operation.
272 -- Note the delicate 'seq' which forces the EPS before putting it in the
273 -- variable. Otherwise what happens is that we get
274 -- write eps_var (....(unsafeRead eps_var)....)
275 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
276 -- we make the unsafeRead happen before we update the variable.
278 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
280 updateEps upd_fn = do { traceIf (text "updating EPS")
281 ; eps_var <- getEpsVar
282 ; eps <- readMutVar eps_var
283 ; let { (eps', val) = upd_fn eps }
284 ; seq eps' (writeMutVar eps_var eps')
287 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
289 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
290 ; eps_var <- getEpsVar
291 ; eps <- readMutVar eps_var
292 ; let { eps' = upd_fn eps }
293 ; seq eps' (writeMutVar eps_var eps') }
295 getHpt :: TcRnIf gbl lcl HomePackageTable
296 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
298 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
299 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
300 ; return (eps, hsc_HPT env) }
303 %************************************************************************
307 %************************************************************************
310 newUnique :: TcRnIf gbl lcl Unique
311 newUnique = do { us <- newUniqueSupply ;
312 return (uniqFromSupply us) }
314 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
316 = do { env <- getEnv ;
317 let { u_var = env_us env } ;
318 us <- readMutVar u_var ;
319 let { (us1, us2) = splitUniqSupply us } ;
320 writeMutVar u_var us1 ;
323 newLocalName :: Name -> TcRnIf gbl lcl Name
324 newLocalName name -- Make a clone
325 = newUnique `thenM` \ uniq ->
326 returnM (mkInternalName uniq (nameOccName name) (getSrcLoc name))
330 %************************************************************************
334 %************************************************************************
337 traceTc, traceRn :: SDoc -> TcRn ()
338 traceRn = traceOptTcRn Opt_D_dump_rn_trace
339 traceTc = traceOptTcRn Opt_D_dump_tc_trace
340 traceSplice = traceOptTcRn Opt_D_dump_splices
343 traceIf :: SDoc -> TcRnIf m n ()
344 traceIf = traceOptIf Opt_D_dump_if_trace
345 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
348 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
349 traceOptIf flag doc = ifOptM flag $
350 ioToIOEnv (printForUser stderr alwaysQualify doc)
352 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
353 traceOptTcRn flag doc = ifOptM flag $ do
356 ; env0 <- tcInitTidyEnv
357 ; ctxt_msgs <- do_ctxt env0 ctxt
358 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
359 ; dumpTcRn real_doc }
361 dumpTcRn :: SDoc -> TcRn ()
362 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
363 ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
365 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
366 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
370 %************************************************************************
372 Typechecker global environment
374 %************************************************************************
377 getModule :: TcRn Module
378 getModule = do { env <- getGblEnv; return (tcg_mod env) }
380 setModule :: Module -> TcRn a -> TcRn a
381 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
383 tcIsHsBoot :: TcRn Bool
384 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
386 getGlobalRdrEnv :: TcRn GlobalRdrEnv
387 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
389 getImports :: TcRn ImportAvails
390 getImports = do { env <- getGblEnv; return (tcg_imports env) }
392 getFixityEnv :: TcRn FixityEnv
393 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
395 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
396 extendFixityEnv new_bit
397 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
398 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
400 getDefaultTys :: TcRn (Maybe [Type])
401 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
404 %************************************************************************
408 %************************************************************************
411 getSrcSpanM :: TcRn SrcSpan
412 -- Avoid clash with Name.getSrcLoc
413 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
415 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
416 setSrcSpan loc thing_inside
417 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
418 | otherwise = thing_inside -- Don't overwrite useful info with useless
420 addLocM :: (a -> TcM b) -> Located a -> TcM b
421 addLocM fn (L loc a) = setSrcSpan loc $ fn a
423 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
424 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
426 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
427 wrapLocFstM fn (L loc a) =
432 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
433 wrapLocSndM fn (L loc a) =
441 getErrsVar :: TcRn (TcRef Messages)
442 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
444 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
445 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
447 addErr :: Message -> TcRn ()
448 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
450 addLocErr :: Located e -> (e -> Message) -> TcRn ()
451 addLocErr (L loc e) fn = addErrAt loc (fn e)
453 addErrAt :: SrcSpan -> Message -> TcRn ()
454 addErrAt loc msg = addLongErrAt loc msg empty
456 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
457 addLongErrAt loc msg extra
458 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
459 errs_var <- getErrsVar ;
460 rdr_env <- getGlobalRdrEnv ;
461 let { err = mkLongErrMsg loc (unQualInScope rdr_env) msg extra } ;
462 (warns, errs) <- readMutVar errs_var ;
463 writeMutVar errs_var (warns, errs `snocBag` err) }
465 addErrs :: [(SrcSpan,Message)] -> TcRn ()
466 addErrs msgs = mappM_ add msgs
468 add (loc,msg) = addErrAt loc msg
470 addReport :: Message -> TcRn ()
471 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
473 addReportAt :: SrcSpan -> Message -> TcRn ()
475 = do { errs_var <- getErrsVar ;
476 rdr_env <- getGlobalRdrEnv ;
477 let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
478 (warns, errs) <- readMutVar errs_var ;
479 writeMutVar errs_var (warns `snocBag` warn, errs) }
481 addWarn :: Message -> TcRn ()
482 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
484 addWarnAt :: SrcSpan -> Message -> TcRn ()
485 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
487 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
488 addLocWarn (L loc e) fn = addReportAt loc (fn e)
490 checkErr :: Bool -> Message -> TcRn ()
491 -- Add the error if the bool is False
492 checkErr ok msg = checkM ok (addErr msg)
494 warnIf :: Bool -> Message -> TcRn ()
495 warnIf True msg = addWarn msg
496 warnIf False msg = return ()
498 addMessages :: Messages -> TcRn ()
499 addMessages (m_warns, m_errs)
500 = do { errs_var <- getErrsVar ;
501 (warns, errs) <- readMutVar errs_var ;
502 writeMutVar errs_var (warns `unionBags` m_warns,
503 errs `unionBags` m_errs) }
505 discardWarnings :: TcRn a -> TcRn a
506 -- Ignore warnings inside the thing inside;
507 -- used to ignore-unused-variable warnings inside derived code
508 -- With -dppr-debug, the effects is switched off, so you can still see
509 -- what warnings derived code would give
510 discardWarnings thing_inside
511 | opt_PprStyle_Debug = thing_inside
513 = do { errs_var <- newMutVar emptyMessages
514 ; result <- setErrsVar errs_var thing_inside
515 ; (_warns, errs) <- readMutVar errs_var
516 ; addMessages (emptyBag, errs)
522 try_m :: TcRn r -> TcRn (Either Exception r)
523 -- Does try_m, with a debug-trace on failure
525 = do { mb_r <- tryM thing ;
527 Left exn -> do { traceTc (exn_msg exn); return mb_r }
528 Right r -> return mb_r }
530 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
532 -----------------------
533 recoverM :: TcRn r -- Recovery action; do this if the main one fails
534 -> TcRn r -- Main action: do this first
536 -- Errors in 'thing' are retained
537 recoverM recover thing
538 = do { mb_res <- try_m thing ;
541 Right res -> returnM res }
543 -----------------------
544 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
545 -- (tryTc m) executes m, and returns
546 -- Just r, if m succeeds (returning r)
547 -- Nothing, if m fails
548 -- It also returns all the errors and warnings accumulated by m
549 -- It always succeeds (never raises an exception)
551 = do { errs_var <- newMutVar emptyMessages ;
552 res <- try_m (setErrsVar errs_var m) ;
553 msgs <- readMutVar errs_var ;
554 return (msgs, case res of
556 Right val -> Just val)
557 -- The exception is always the IOEnv built-in
558 -- in exception; see IOEnv.failM
561 -----------------------
562 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
563 -- Run the thing, returning
564 -- Just r, if m succceeds with no error messages
565 -- Nothing, if m fails, or if it succeeds but has error messages
566 -- Either way, the messages are returned; even in the Just case
567 -- there might be warnings
569 = do { (msgs, res) <- tryTc thing
571 ; let errs_found = errorsFound dflags msgs
572 ; return (msgs, case res of
574 Just val | errs_found -> Nothing
575 | otherwise -> Just val)
578 -----------------------
579 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
580 -- Just like tryTcErrs, except that it ensures that the LIE
581 -- for the thing is propagated only if there are no errors
582 -- Hence it's restricted to the type-check monad
583 tryTcLIE thing_inside
584 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
586 Nothing -> return (msgs, Nothing)
587 Just val -> do { extendLIEs lie; return (msgs, Just val) }
590 -----------------------
591 tryTcLIE_ :: TcM r -> TcM r -> TcM r
592 -- (tryTcLIE_ r m) tries m;
593 -- if m succeeds with no error messages, it's the answer
594 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
595 tryTcLIE_ recover main
596 = do { (msgs, mb_res) <- tryTcLIE main
598 Just val -> do { addMessages msgs -- There might be warnings
600 Nothing -> recover -- Discard all msgs
603 -----------------------
604 checkNoErrs :: TcM r -> TcM r
605 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
606 -- If m fails then (checkNoErrsTc m) fails.
607 -- If m succeeds, it checks whether m generated any errors messages
608 -- (it might have recovered internally)
609 -- If so, it fails too.
610 -- Regardless, any errors generated by m are propagated to the enclosing context.
612 = do { (msgs, mb_res) <- tryTcLIE main
616 Just val -> return val
619 ifErrsM :: TcRn r -> TcRn r -> TcRn r
620 -- ifErrsM bale_out main
621 -- does 'bale_out' if there are errors in errors collection
622 -- otherwise does 'main'
623 ifErrsM bale_out normal
624 = do { errs_var <- getErrsVar ;
625 msgs <- readMutVar errs_var ;
627 if errorsFound dflags msgs then
632 failIfErrsM :: TcRn ()
633 -- Useful to avoid error cascades
634 failIfErrsM = ifErrsM failM (return ())
638 %************************************************************************
640 Context management and error message generation
643 %************************************************************************
646 getErrCtxt :: TcM ErrCtxt
647 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
649 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
650 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
652 addErrCtxt :: Message -> TcM a -> TcM a
653 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
655 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
656 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
658 -- Helper function for the above
659 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
660 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
661 env { tcl_ctxt = upd ctxt })
663 -- Conditionally add an error context
664 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
665 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
666 maybeAddErrCtxt Nothing thing_inside = thing_inside
668 popErrCtxt :: TcM a -> TcM a
669 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
671 getInstLoc :: InstOrigin -> TcM InstLoc
673 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
674 return (InstLoc origin loc (tcl_ctxt env)) }
676 addInstCtxt :: InstLoc -> TcM a -> TcM a
677 -- Add the SrcSpan and context from the first Inst in the list
678 -- (they all have similar locations)
679 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
680 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
683 The addErrTc functions add an error message, but do not cause failure.
684 The 'M' variants pass a TidyEnv that has already been used to
685 tidy up the message; we then use it to tidy the context messages
688 addErrTc :: Message -> TcM ()
689 addErrTc err_msg = do { env0 <- tcInitTidyEnv
690 ; addErrTcM (env0, err_msg) }
692 addErrsTc :: [Message] -> TcM ()
693 addErrsTc err_msgs = mappM_ addErrTc err_msgs
695 addErrTcM :: (TidyEnv, Message) -> TcM ()
696 addErrTcM (tidy_env, err_msg)
697 = do { ctxt <- getErrCtxt ;
699 add_err_tcm tidy_env err_msg loc ctxt }
702 The failWith functions add an error message and cause failure
705 failWithTc :: Message -> TcM a -- Add an error message and fail
707 = addErrTc err_msg >> failM
709 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
710 failWithTcM local_and_msg
711 = addErrTcM local_and_msg >> failM
713 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
714 checkTc True err = returnM ()
715 checkTc False err = failWithTc err
718 Warnings have no 'M' variant, nor failure
721 addWarnTc :: Message -> TcM ()
723 = do { ctxt <- getErrCtxt ;
724 env0 <- tcInitTidyEnv ;
725 ctxt_msgs <- do_ctxt env0 ctxt ;
726 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
728 warnTc :: Bool -> Message -> TcM ()
729 warnTc warn_if_true warn_msg
730 | warn_if_true = addWarnTc warn_msg
731 | otherwise = return ()
734 -----------------------------------
737 We initialise the "tidy-env", used for tidying types before printing,
738 by building a reverse map from the in-scope type variables to the
739 OccName that the programmer originally used for them
742 tcInitTidyEnv :: TcM TidyEnv
744 = do { lcl_env <- getLclEnv
745 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
746 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
748 ; return (foldl add emptyTidyEnv nm_tv_prs) }
750 add (env,subst) (name, tyvar)
751 = case tidyOccName env (nameOccName name) of
752 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
754 tyvar' = setTyVarName tyvar name'
755 name' = tidyNameOcc name occ'
758 -----------------------------------
759 Other helper functions
762 add_err_tcm tidy_env err_msg loc ctxt
763 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
764 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
768 do_ctxt tidy_env (c:cs)
769 = do { (tidy_env', m) <- c tidy_env ;
770 ms <- do_ctxt tidy_env' cs ;
773 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
774 | otherwise = take 3 ctxt
777 debugTc is useful for monadic debugging code
780 debugTc :: TcM () -> TcM ()
782 debugTc thing = thing
784 debugTc thing = return ()
788 %************************************************************************
790 Type constraints (the so-called LIE)
792 %************************************************************************
795 nextDFunIndex :: TcM Int -- Get the next dfun index
796 nextDFunIndex = do { env <- getGblEnv
797 ; let dfun_n_var = tcg_dfun_n env
798 ; n <- readMutVar dfun_n_var
799 ; writeMutVar dfun_n_var (n+1)
802 getLIEVar :: TcM (TcRef LIE)
803 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
805 setLIEVar :: TcRef LIE -> TcM a -> TcM a
806 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
808 getLIE :: TcM a -> TcM (a, [Inst])
809 -- (getLIE m) runs m, and returns the type constraints it generates
811 = do { lie_var <- newMutVar emptyLIE ;
812 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
814 lie <- readMutVar lie_var ;
815 return (res, lieToList lie) }
817 extendLIE :: Inst -> TcM ()
819 = do { lie_var <- getLIEVar ;
820 lie <- readMutVar lie_var ;
821 writeMutVar lie_var (inst `consLIE` lie) }
823 extendLIEs :: [Inst] -> TcM ()
827 = do { lie_var <- getLIEVar ;
828 lie <- readMutVar lie_var ;
829 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
833 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
834 -- Set the local type envt, but do *not* disturb other fields,
835 -- notably the lie_var
836 setLclTypeEnv lcl_env thing_inside
837 = updLclEnv upd thing_inside
839 upd env = env { tcl_env = tcl_env lcl_env,
840 tcl_tyvars = tcl_tyvars lcl_env }
844 %************************************************************************
846 Template Haskell context
848 %************************************************************************
851 recordThUse :: TcM ()
852 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
854 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
855 keepAliveTc n = do { env <- getGblEnv;
856 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
858 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
859 keepAliveSetTc ns = do { env <- getGblEnv;
860 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
862 getStage :: TcM ThStage
863 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
865 setStage :: ThStage -> TcM a -> TcM a
866 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
870 %************************************************************************
872 Stuff for the renamer's local env
874 %************************************************************************
877 getLocalRdrEnv :: RnM LocalRdrEnv
878 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
880 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
881 setLocalRdrEnv rdr_env thing_inside
882 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
886 %************************************************************************
888 Stuff for interface decls
890 %************************************************************************
893 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
894 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
896 if_tv_env = emptyOccEnv,
897 if_id_env = emptyOccEnv }
899 initIfaceTcRn :: IfG a -> TcRn a
900 initIfaceTcRn thing_inside
901 = do { tcg_env <- getGblEnv
902 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
903 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
904 ; setEnvs (if_env, ()) thing_inside }
906 initIfaceExtCore :: IfL a -> TcRn a
907 initIfaceExtCore thing_inside
908 = do { tcg_env <- getGblEnv
909 ; let { mod = tcg_mod tcg_env
910 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
911 ; if_env = IfGblEnv {
912 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
913 ; if_lenv = mkIfLclEnv mod doc
915 ; setEnvs (if_env, if_lenv) thing_inside }
917 initIfaceCheck :: HscEnv -> IfG a -> IO a
918 -- Used when checking the up-to-date-ness of the old Iface
919 -- Initialise the environment with no useful info at all
920 initIfaceCheck hsc_env do_this
921 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
922 ; initTcRnIf 'i' hsc_env gbl_env () do_this
925 initIfaceTc :: ModIface
926 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
927 -- Used when type-checking checking an up-to-date interface file
928 -- No type envt from the current module, but we do know the module dependencies
929 initIfaceTc iface do_this
930 = do { tc_env_var <- newMutVar emptyTypeEnv
931 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
932 ; if_lenv = mkIfLclEnv mod doc
934 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
937 mod = mi_module iface
938 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
940 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
941 -- Used when sucking in new Rules in SimplCore
942 -- We have available the type envt of the module being compiled, and we must use it
943 initIfaceRules hsc_env guts do_this
945 type_info = (mg_module guts, return (mg_types guts))
946 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
949 -- Run the thing; any exceptions just bubble out from here
950 ; initTcRnIf 'i' hsc_env gbl_env () do_this
953 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
954 initIfaceLcl mod loc_doc thing_inside
955 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
957 getIfModule :: IfL Module
958 getIfModule = do { env <- getLclEnv; return (if_mod env) }
961 failIfM :: Message -> IfL a
962 -- The Iface monad doesn't have a place to accumulate errors, so we
963 -- just fall over fast if one happens; it "shouldnt happen".
964 -- We use IfL here so that we can get context info out of the local env
966 = do { env <- getLclEnv
967 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
968 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
972 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
973 -- Run thing_inside in an interleaved thread.
974 -- It shares everything with the parent thread, so this is DANGEROUS.
976 -- It returns Nothing if the computation fails
978 -- It's used for lazily type-checking interface
979 -- signatures, which is pretty benign
981 forkM_maybe doc thing_inside
982 = do { unsafeInterleaveM $
983 do { traceIf (text "Starting fork {" <+> doc)
984 ; mb_res <- tryM thing_inside ;
986 Right r -> do { traceIf (text "} ending fork" <+> doc)
990 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
991 -- Otherwise we silently discard errors. Errors can legitimately
992 -- happen when compiling interface signatures (see tcInterfaceSigs)
993 ifOptM Opt_D_dump_if_trace
994 (print_errs (hang (text "forkM failed:" <+> doc)
995 4 (text (show exn))))
997 ; traceIf (text "} ending fork (badly)" <+> doc)
1001 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1003 forkM :: SDoc -> IfL a -> IfL a
1004 forkM doc thing_inside
1005 = do { mb_res <- forkM_maybe doc thing_inside
1006 ; return (case mb_res of
1007 Nothing -> pgmError "Cannot continue after interface file error"
1008 -- pprPanic "forkM" doc