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, getOccName, getSrcLoc )
25 import NameEnv ( extendNameEnvList )
26 import InstEnv ( emptyInstEnv )
28 import VarSet ( emptyVarSet )
29 import VarEnv ( TidyEnv, emptyTidyEnv, emptyVarEnv )
30 import ErrUtils ( Message, Messages, emptyMessages, errorsFound,
31 mkWarnMsg, printErrorsAndWarnings,
32 mkLocMessage, mkLongErrMsg )
33 import Packages ( mkHomeModules )
34 import SrcLoc ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
35 import NameEnv ( emptyNameEnv )
36 import NameSet ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
37 import OccName ( emptyOccEnv )
38 import Bag ( emptyBag )
40 import UniqSupply ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
41 import Unique ( Unique )
42 import DynFlags ( DynFlags(..), DynFlag(..), dopt, dopt_set, GhcMode )
43 import StaticFlags ( opt_PprStyle_Debug )
44 import Bag ( snocBag, unionBags, unitBag )
45 import Panic ( showException )
48 import DATA_IOREF ( newIORef, readIORef )
49 import EXCEPTION ( Exception )
54 %************************************************************************
58 %************************************************************************
61 ioToTcRn :: IO r -> TcRn r
70 -> IO (Messages, Maybe r)
71 -- Nothing => error thrown by the thing inside
72 -- (error messages should have been printed already)
74 initTc hsc_env hsc_src mod do_this
75 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
76 tvs_var <- newIORef emptyVarSet ;
77 type_env_var <- newIORef emptyNameEnv ;
78 dfuns_var <- newIORef emptyNameSet ;
79 keep_var <- newIORef emptyNameSet ;
80 th_var <- newIORef False ;
81 dfun_n_var <- newIORef 1 ;
87 tcg_rdr_env = emptyGlobalRdrEnv,
88 tcg_fix_env = emptyNameEnv,
89 tcg_default = Nothing,
90 tcg_type_env = emptyNameEnv,
91 tcg_type_env_var = type_env_var,
92 tcg_inst_env = emptyInstEnv,
93 tcg_inst_uses = dfuns_var,
95 tcg_exports = emptyNameSet,
96 tcg_imports = init_imports,
97 tcg_home_mods = home_mods,
99 tcg_rn_decls = Nothing,
100 tcg_binds = emptyLHsBinds,
101 tcg_deprecs = NoDeprecs,
105 tcg_dfun_n = dfun_n_var,
110 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
112 tcl_rdr = emptyLocalRdrEnv,
113 tcl_th_ctxt = topStage,
114 tcl_arrow_ctxt = NoArrowCtxt,
115 tcl_env = emptyNameEnv,
116 tcl_tyvars = tvs_var,
117 tcl_lie = panic "initTc:LIE", -- LIE only valid inside a getLIE
118 tcl_gadt = emptyVarEnv
122 -- OK, here's the business end!
123 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
124 do { r <- tryM do_this
126 Right res -> return (Just res)
127 Left _ -> return Nothing } ;
129 -- Collect any error messages
130 msgs <- readIORef errs_var ;
132 let { dflags = hsc_dflags hsc_env
133 ; final_res | errorsFound dflags msgs = Nothing
134 | otherwise = maybe_res } ;
136 return (msgs, final_res)
139 home_mods = mkHomeModules (map ms_mod (hsc_mod_graph hsc_env))
140 -- A guess at the home modules. This will be correct in
141 -- --make and GHCi modes, but in one-shot mode we need to
142 -- fix it up after we know the real dependencies of the current
143 -- module (see tcRnModule).
144 -- Setting it here is necessary for the typechecker entry points
145 -- other than tcRnModule: tcRnGetInfo, for example. These are
146 -- all called via the GHC module, so hsc_mod_graph will contain
147 -- something sensible.
149 init_imports = emptyImportAvails {imp_env = unitModuleEnv mod emptyNameSet}
150 -- Initialise tcg_imports with an empty set of bindings for
151 -- this module, so that if we see 'module M' in the export
152 -- list, and there are no bindings in M, we don't bleat
153 -- "unknown module M".
155 initTcPrintErrors -- Used from the interactive loop only
160 initTcPrintErrors env mod todo = do
161 (msgs, res) <- initTc env HsSrcFile mod todo
162 printErrorsAndWarnings (hsc_dflags env) msgs
165 -- mkImpTypeEnv makes the imported symbol table
166 mkImpTypeEnv :: ExternalPackageState -> HomePackageTable
167 -> Name -> Maybe TyThing
168 mkImpTypeEnv pcs hpt = lookup
171 lookup name | isInternalName name = Nothing
172 | otherwise = lookupType hpt pte name
176 %************************************************************************
180 %************************************************************************
184 initTcRnIf :: Char -- Tag for unique supply
189 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
190 = do { us <- mkSplitUniqSupply uniq_tag ;
191 ; us_var <- newIORef us ;
193 ; let { env = Env { env_top = hsc_env,
196 env_lcl = lcl_env } }
198 ; runIOEnv env thing_inside
202 %************************************************************************
206 %************************************************************************
209 getTopEnv :: TcRnIf gbl lcl HscEnv
210 getTopEnv = do { env <- getEnv; return (env_top env) }
212 getGblEnv :: TcRnIf gbl lcl gbl
213 getGblEnv = do { env <- getEnv; return (env_gbl env) }
215 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
216 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
217 env { env_gbl = upd gbl })
219 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
220 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
222 getLclEnv :: TcRnIf gbl lcl lcl
223 getLclEnv = do { env <- getEnv; return (env_lcl env) }
225 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
226 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
227 env { env_lcl = upd lcl })
229 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
230 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
232 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
233 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
235 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
236 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
243 getDOpts :: TcRnIf gbl lcl DynFlags
244 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
246 doptM :: DynFlag -> TcRnIf gbl lcl Bool
247 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
249 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
250 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
251 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
253 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
254 ifOptM flag thing_inside = do { b <- doptM flag;
255 if b then thing_inside else return () }
257 getGhciMode :: TcRnIf gbl lcl GhcMode
258 getGhciMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
262 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
263 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
265 getEps :: TcRnIf gbl lcl ExternalPackageState
266 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
268 -- Updating the EPS. This should be an atomic operation.
269 -- Note the delicate 'seq' which forces the EPS before putting it in the
270 -- variable. Otherwise what happens is that we get
271 -- write eps_var (....(unsafeRead eps_var)....)
272 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
273 -- we make the unsafeRead happen before we update the variable.
275 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
277 updateEps upd_fn = do { traceIf (text "updating EPS")
278 ; eps_var <- getEpsVar
279 ; eps <- readMutVar eps_var
280 ; let { (eps', val) = upd_fn eps }
281 ; seq eps' (writeMutVar eps_var eps')
284 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
286 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
287 ; eps_var <- getEpsVar
288 ; eps <- readMutVar eps_var
289 ; let { eps' = upd_fn eps }
290 ; seq eps' (writeMutVar eps_var eps') }
292 getHpt :: TcRnIf gbl lcl HomePackageTable
293 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
295 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
296 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
297 ; return (eps, hsc_HPT env) }
300 %************************************************************************
304 %************************************************************************
307 newUnique :: TcRnIf gbl lcl Unique
308 newUnique = do { us <- newUniqueSupply ;
309 return (uniqFromSupply us) }
311 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
313 = do { env <- getEnv ;
314 let { u_var = env_us env } ;
315 us <- readMutVar u_var ;
316 let { (us1, us2) = splitUniqSupply us } ;
317 writeMutVar u_var us1 ;
320 newLocalName :: Name -> TcRnIf gbl lcl Name
321 newLocalName name -- Make a clone
322 = newUnique `thenM` \ uniq ->
323 returnM (mkInternalName uniq (getOccName name) (getSrcLoc name))
327 %************************************************************************
331 %************************************************************************
334 traceTc, traceRn :: SDoc -> TcRn ()
335 traceRn = traceOptTcRn Opt_D_dump_rn_trace
336 traceTc = traceOptTcRn Opt_D_dump_tc_trace
337 traceSplice = traceOptTcRn Opt_D_dump_splices
340 traceIf :: SDoc -> TcRnIf m n ()
341 traceIf = traceOptIf Opt_D_dump_if_trace
342 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
345 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
346 traceOptIf flag doc = ifOptM flag $
347 ioToIOEnv (printForUser stderr alwaysQualify doc)
349 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
350 traceOptTcRn flag doc = ifOptM flag $ do
353 ; ctxt_msgs <- do_ctxt emptyTidyEnv ctxt
354 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
355 ; dumpTcRn real_doc }
357 dumpTcRn :: SDoc -> TcRn ()
358 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
359 ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
361 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
362 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
366 %************************************************************************
368 Typechecker global environment
370 %************************************************************************
373 getModule :: TcRn Module
374 getModule = do { env <- getGblEnv; return (tcg_mod env) }
376 tcIsHsBoot :: TcRn Bool
377 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
379 getGlobalRdrEnv :: TcRn GlobalRdrEnv
380 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
382 getImports :: TcRn ImportAvails
383 getImports = do { env <- getGblEnv; return (tcg_imports env) }
385 getFixityEnv :: TcRn FixityEnv
386 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
388 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
389 extendFixityEnv new_bit
390 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
391 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
393 getDefaultTys :: TcRn (Maybe [Type])
394 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
397 %************************************************************************
401 %************************************************************************
404 getSrcSpanM :: TcRn SrcSpan
405 -- Avoid clash with Name.getSrcLoc
406 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
408 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
409 setSrcSpan loc thing_inside
410 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
411 | otherwise = thing_inside -- Don't overwrite useful info with useless
413 addLocM :: (a -> TcM b) -> Located a -> TcM b
414 addLocM fn (L loc a) = setSrcSpan loc $ fn a
416 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
417 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
419 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
420 wrapLocFstM fn (L loc a) =
425 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
426 wrapLocSndM fn (L loc a) =
434 getErrsVar :: TcRn (TcRef Messages)
435 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
437 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
438 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
440 addErr :: Message -> TcRn ()
441 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
443 addLocErr :: Located e -> (e -> Message) -> TcRn ()
444 addLocErr (L loc e) fn = addErrAt loc (fn e)
446 addErrAt :: SrcSpan -> Message -> TcRn ()
447 addErrAt loc msg = addLongErrAt loc msg empty
449 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
450 addLongErrAt loc msg extra
451 = do { errs_var <- getErrsVar ;
452 rdr_env <- getGlobalRdrEnv ;
453 let { err = mkLongErrMsg loc (unQualInScope rdr_env) msg extra } ;
454 (warns, errs) <- readMutVar errs_var ;
456 let style = mkErrStyle (unQualInScope rdr_env)
457 doc = mkLocMessage loc (msg $$ extra)
458 in traceTc (ptext SLIT("Adding error:") <+> doc) ;
459 writeMutVar errs_var (warns, errs `snocBag` err) }
461 addErrs :: [(SrcSpan,Message)] -> TcRn ()
462 addErrs msgs = mappM_ add msgs
464 add (loc,msg) = addErrAt loc msg
466 addReport :: Message -> TcRn ()
467 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
469 addReportAt :: SrcSpan -> Message -> TcRn ()
471 = do { errs_var <- getErrsVar ;
472 rdr_env <- getGlobalRdrEnv ;
473 let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
474 (warns, errs) <- readMutVar errs_var ;
475 writeMutVar errs_var (warns `snocBag` warn, errs) }
477 addWarn :: Message -> TcRn ()
478 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
480 addWarnAt :: SrcSpan -> Message -> TcRn ()
481 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
483 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
484 addLocWarn (L loc e) fn = addReportAt loc (fn e)
486 checkErr :: Bool -> Message -> TcRn ()
487 -- Add the error if the bool is False
488 checkErr ok msg = checkM ok (addErr msg)
490 warnIf :: Bool -> Message -> TcRn ()
491 warnIf True msg = addWarn msg
492 warnIf False msg = return ()
494 addMessages :: Messages -> TcRn ()
495 addMessages (m_warns, m_errs)
496 = do { errs_var <- getErrsVar ;
497 (warns, errs) <- readMutVar errs_var ;
498 writeMutVar errs_var (warns `unionBags` m_warns,
499 errs `unionBags` m_errs) }
501 discardWarnings :: TcRn a -> TcRn a
502 -- Ignore warnings inside the thing inside;
503 -- used to ignore-unused-variable warnings inside derived code
504 -- With -dppr-debug, the effects is switched off, so you can still see
505 -- what warnings derived code would give
506 discardWarnings thing_inside
507 | opt_PprStyle_Debug = thing_inside
509 = do { errs_var <- newMutVar emptyMessages
510 ; result <- setErrsVar errs_var thing_inside
511 ; (_warns, errs) <- readMutVar errs_var
512 ; addMessages (emptyBag, errs)
518 try_m :: TcRn r -> TcRn (Either Exception r)
519 -- Does try_m, with a debug-trace on failure
521 = do { mb_r <- tryM thing ;
523 Left exn -> do { traceTc (exn_msg exn); return mb_r }
524 Right r -> return mb_r }
526 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
528 -----------------------
529 recoverM :: TcRn r -- Recovery action; do this if the main one fails
530 -> TcRn r -- Main action: do this first
532 -- Errors in 'thing' are retained
533 recoverM recover thing
534 = do { mb_res <- try_m thing ;
537 Right res -> returnM res }
539 -----------------------
540 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
541 -- (tryTc m) executes m, and returns
542 -- Just r, if m succeeds (returning r)
543 -- Nothing, if m fails
544 -- It also returns all the errors and warnings accumulated by m
545 -- It always succeeds (never raises an exception)
547 = do { errs_var <- newMutVar emptyMessages ;
548 res <- try_m (setErrsVar errs_var m) ;
549 msgs <- readMutVar errs_var ;
550 return (msgs, case res of
552 Right val -> Just val)
553 -- The exception is always the IOEnv built-in
554 -- in exception; see IOEnv.failM
557 -----------------------
558 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
559 -- Run the thing, returning
560 -- Just r, if m succceeds with no error messages
561 -- Nothing, if m fails, or if it succeeds but has error messages
562 -- Either way, the messages are returned; even in the Just case
563 -- there might be warnings
565 = do { (msgs, res) <- tryTc thing
567 ; let errs_found = errorsFound dflags msgs
568 ; return (msgs, case res of
570 Just val | errs_found -> Nothing
571 | otherwise -> Just val)
574 -----------------------
575 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
576 -- Just like tryTcErrs, except that it ensures that the LIE
577 -- for the thing is propagated only if there are no errors
578 -- Hence it's restricted to the type-check monad
579 tryTcLIE thing_inside
580 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
582 Nothing -> return (msgs, Nothing)
583 Just val -> do { extendLIEs lie; return (msgs, Just val) }
586 -----------------------
587 tryTcLIE_ :: TcM r -> TcM r -> TcM r
588 -- (tryTcLIE_ r m) tries m;
589 -- if m succeeds with no error messages, it's the answer
590 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
591 tryTcLIE_ recover main
592 = do { (msgs, mb_res) <- tryTcLIE main
594 Just val -> do { addMessages msgs -- There might be warnings
596 Nothing -> recover -- Discard all msgs
599 -----------------------
600 checkNoErrs :: TcM r -> TcM r
601 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
602 -- If m fails then (checkNoErrsTc m) fails.
603 -- If m succeeds, it checks whether m generated any errors messages
604 -- (it might have recovered internally)
605 -- If so, it fails too.
606 -- Regardless, any errors generated by m are propagated to the enclosing context.
608 = do { (msgs, mb_res) <- tryTcLIE main
612 Just val -> return val
615 ifErrsM :: TcRn r -> TcRn r -> TcRn r
616 -- ifErrsM bale_out main
617 -- does 'bale_out' if there are errors in errors collection
618 -- otherwise does 'main'
619 ifErrsM bale_out normal
620 = do { errs_var <- getErrsVar ;
621 msgs <- readMutVar errs_var ;
623 if errorsFound dflags msgs then
628 failIfErrsM :: TcRn ()
629 -- Useful to avoid error cascades
630 failIfErrsM = ifErrsM failM (return ())
634 %************************************************************************
636 Context management and error message generation
639 %************************************************************************
642 getErrCtxt :: TcM ErrCtxt
643 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
645 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
646 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
648 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
649 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
651 addErrCtxt :: Message -> TcM a -> TcM a
652 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
654 -- Helper function for the above
655 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
656 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
657 env { tcl_ctxt = upd ctxt })
659 -- Conditionally add an error context
660 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
661 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
662 maybeAddErrCtxt Nothing thing_inside = thing_inside
664 popErrCtxt :: TcM a -> TcM a
665 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
667 getInstLoc :: InstOrigin -> TcM InstLoc
669 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
670 return (InstLoc origin loc (tcl_ctxt env)) }
672 addInstCtxt :: InstLoc -> TcM a -> TcM a
673 -- Add the SrcSpan and context from the first Inst in the list
674 -- (they all have similar locations)
675 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
676 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
679 The addErrTc functions add an error message, but do not cause failure.
680 The 'M' variants pass a TidyEnv that has already been used to
681 tidy up the message; we then use it to tidy the context messages
684 addErrTc :: Message -> TcM ()
685 addErrTc err_msg = addErrTcM (emptyTidyEnv, err_msg)
687 addErrsTc :: [Message] -> TcM ()
688 addErrsTc err_msgs = mappM_ addErrTc err_msgs
690 addErrTcM :: (TidyEnv, Message) -> TcM ()
691 addErrTcM (tidy_env, err_msg)
692 = do { ctxt <- getErrCtxt ;
694 add_err_tcm tidy_env err_msg loc ctxt }
697 The failWith functions add an error message and cause failure
700 failWithTc :: Message -> TcM a -- Add an error message and fail
702 = addErrTc err_msg >> failM
704 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
705 failWithTcM local_and_msg
706 = addErrTcM local_and_msg >> failM
708 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
709 checkTc True err = returnM ()
710 checkTc False err = failWithTc err
713 Warnings have no 'M' variant, nor failure
716 addWarnTc :: Message -> TcM ()
718 = do { ctxt <- getErrCtxt ;
719 ctxt_msgs <- do_ctxt emptyTidyEnv ctxt ;
720 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
722 warnTc :: Bool -> Message -> TcM ()
723 warnTc warn_if_true warn_msg
724 | warn_if_true = addWarnTc warn_msg
725 | otherwise = return ()
731 add_err_tcm tidy_env err_msg loc ctxt
732 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
733 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
737 do_ctxt tidy_env (c:cs)
738 = do { (tidy_env', m) <- c tidy_env ;
739 ms <- do_ctxt tidy_env' cs ;
742 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
743 | otherwise = take 3 ctxt
746 debugTc is useful for monadi debugging code
749 debugTc :: TcM () -> TcM ()
751 debugTc thing = thing
753 debugTc thing = return ()
757 %************************************************************************
759 Type constraints (the so-called LIE)
761 %************************************************************************
764 nextDFunIndex :: TcM Int -- Get the next dfun index
765 nextDFunIndex = do { env <- getGblEnv
766 ; let dfun_n_var = tcg_dfun_n env
767 ; n <- readMutVar dfun_n_var
768 ; writeMutVar dfun_n_var (n+1)
771 getLIEVar :: TcM (TcRef LIE)
772 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
774 setLIEVar :: TcRef LIE -> TcM a -> TcM a
775 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
777 getLIE :: TcM a -> TcM (a, [Inst])
778 -- (getLIE m) runs m, and returns the type constraints it generates
780 = do { lie_var <- newMutVar emptyLIE ;
781 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
783 lie <- readMutVar lie_var ;
784 return (res, lieToList lie) }
786 extendLIE :: Inst -> TcM ()
788 = do { lie_var <- getLIEVar ;
789 lie <- readMutVar lie_var ;
790 writeMutVar lie_var (inst `consLIE` lie) }
792 extendLIEs :: [Inst] -> TcM ()
796 = do { lie_var <- getLIEVar ;
797 lie <- readMutVar lie_var ;
798 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
802 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
803 -- Set the local type envt, but do *not* disturb other fields,
804 -- notably the lie_var
805 setLclTypeEnv lcl_env thing_inside
806 = updLclEnv upd thing_inside
808 upd env = env { tcl_env = tcl_env lcl_env,
809 tcl_tyvars = tcl_tyvars lcl_env }
813 %************************************************************************
815 Template Haskell context
817 %************************************************************************
820 recordThUse :: TcM ()
821 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
823 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
824 keepAliveTc n = do { env <- getGblEnv;
825 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
827 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
828 keepAliveSetTc ns = do { env <- getGblEnv;
829 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
831 getStage :: TcM ThStage
832 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
834 setStage :: ThStage -> TcM a -> TcM a
835 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
839 %************************************************************************
841 Stuff for the renamer's local env
843 %************************************************************************
846 getLocalRdrEnv :: RnM LocalRdrEnv
847 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
849 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
850 setLocalRdrEnv rdr_env thing_inside
851 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
855 %************************************************************************
857 Stuff for interface decls
859 %************************************************************************
862 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
863 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
865 if_tv_env = emptyOccEnv,
866 if_id_env = emptyOccEnv }
868 initIfaceTcRn :: IfG a -> TcRn a
869 initIfaceTcRn thing_inside
870 = do { tcg_env <- getGblEnv
871 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
872 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
873 ; setEnvs (if_env, ()) thing_inside }
875 initIfaceExtCore :: IfL a -> TcRn a
876 initIfaceExtCore thing_inside
877 = do { tcg_env <- getGblEnv
878 ; let { mod = tcg_mod tcg_env
879 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
880 ; if_env = IfGblEnv {
881 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
882 ; if_lenv = mkIfLclEnv mod doc
884 ; setEnvs (if_env, if_lenv) thing_inside }
886 initIfaceCheck :: HscEnv -> IfG a -> IO a
887 -- Used when checking the up-to-date-ness of the old Iface
888 -- Initialise the environment with no useful info at all
889 initIfaceCheck hsc_env do_this
890 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
891 ; initTcRnIf 'i' hsc_env gbl_env () do_this
894 initIfaceTc :: ModIface
895 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
896 -- Used when type-checking checking an up-to-date interface file
897 -- No type envt from the current module, but we do know the module dependencies
898 initIfaceTc iface do_this
899 = do { tc_env_var <- newMutVar emptyTypeEnv
900 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
901 ; if_lenv = mkIfLclEnv mod doc
903 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
906 mod = mi_module iface
907 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
909 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
910 -- Used when sucking in new Rules in SimplCore
911 -- We have available the type envt of the module being compiled, and we must use it
912 initIfaceRules hsc_env guts do_this
914 type_info = (mg_module guts, return (mg_types guts))
915 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
918 -- Run the thing; any exceptions just bubble out from here
919 ; initTcRnIf 'i' hsc_env gbl_env () do_this
922 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
923 initIfaceLcl mod loc_doc thing_inside
924 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
926 getIfModule :: IfL Module
927 getIfModule = do { env <- getLclEnv; return (if_mod env) }
930 failIfM :: Message -> IfL a
931 -- The Iface monad doesn't have a place to accumulate errors, so we
932 -- just fall over fast if one happens; it "shouldnt happen".
933 -- We use IfL here so that we can get context info out of the local env
935 = do { env <- getLclEnv
936 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
937 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
941 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
942 -- Run thing_inside in an interleaved thread.
943 -- It shares everything with the parent thread, so this is DANGEROUS.
945 -- It returns Nothing if the computation fails
947 -- It's used for lazily type-checking interface
948 -- signatures, which is pretty benign
950 forkM_maybe doc thing_inside
951 = do { unsafeInterleaveM $
952 do { traceIf (text "Starting fork {" <+> doc)
953 ; mb_res <- tryM thing_inside ;
955 Right r -> do { traceIf (text "} ending fork" <+> doc)
959 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
960 -- Otherwise we silently discard errors. Errors can legitimately
961 -- happen when compiling interface signatures (see tcInterfaceSigs)
962 ifOptM Opt_D_dump_if_trace
963 (print_errs (hang (text "forkM failed:" <+> doc)
964 4 (text (show exn))))
966 ; traceIf (text "} ending fork (badly)" <+> doc)
970 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
972 forkM :: SDoc -> IfL a -> IfL a
973 forkM doc thing_inside
974 = do { mb_res <- forkM_maybe doc thing_inside
975 ; return (case mb_res of
976 Nothing -> pgmError "Cannot continue after interface file error"
977 -- pprPanic "forkM" doc
981 %************************************************************************
985 %************************************************************************
988 getTypeRefinement :: TcM GadtRefinement
989 getTypeRefinement = do { lcl_env <- getLclEnv; return (tcl_gadt lcl_env) }
991 setTypeRefinement :: GadtRefinement -> TcM a -> TcM a
992 setTypeRefinement gadt = updLclEnv (\env -> env { tcl_gadt = gadt })