8 #include "HsVersions.h"
10 import TcRnTypes -- Re-export all
11 import IOEnv -- Re-export all
13 #if defined(GHCI) && defined(BREAKPOINT)
14 import TypeRep ( Type(..), liftedTypeKind )
15 import Var ( mkTyVar, mkGlobalId )
16 import IdInfo ( GlobalIdDetails(..), vanillaIdInfo )
17 import OccName ( mkOccName, tvName )
18 import SrcLoc ( noSrcLoc )
19 import TysWiredIn ( intTy, stringTy, mkListTy, unitTy, boolTy )
20 import PrelNames ( breakpointJumpName, breakpointCondJumpName )
21 import NameEnv ( mkNameEnv )
22 import TcEnv ( tcExtendIdEnv )
25 import HsSyn ( emptyLHsBinds )
26 import HscTypes ( HscEnv(..), ModGuts(..), ModIface(..),
27 TypeEnv, emptyTypeEnv, HscSource(..), isHsBoot,
28 ExternalPackageState(..), HomePackageTable,
29 Deprecs(..), FixityEnv, FixItem,
31 import Module ( Module, moduleName )
32 import RdrName ( GlobalRdrEnv, LocalRdrEnv, emptyLocalRdrEnv )
33 import Name ( Name, mkInternalName, tidyNameOcc, nameOccName, getSrcLoc )
35 import TcType ( tcIsTyVarTy, tcGetTyVar )
36 import NameEnv ( extendNameEnvList, nameEnvElts )
37 import InstEnv ( emptyInstEnv )
39 import Var ( setTyVarName )
40 import VarSet ( emptyVarSet )
41 import VarEnv ( TidyEnv, emptyTidyEnv, extendVarEnv )
42 import ErrUtils ( Message, Messages, emptyMessages, errorsFound,
43 mkWarnMsg, printErrorsAndWarnings,
44 mkLocMessage, mkLongErrMsg )
45 import SrcLoc ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
46 import NameEnv ( emptyNameEnv )
47 import NameSet ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
48 import OccName ( emptyOccEnv, tidyOccName )
49 import Bag ( emptyBag )
51 import UniqSupply ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
52 import UniqFM ( unitUFM )
53 import Unique ( Unique )
54 import DynFlags ( DynFlags(..), DynFlag(..), dopt, dopt_set,
56 import StaticFlags ( opt_PprStyle_Debug )
57 import Bag ( snocBag, unionBags )
58 import Panic ( showException )
61 import DATA_IOREF ( newIORef, readIORef )
62 import EXCEPTION ( Exception )
67 %************************************************************************
71 %************************************************************************
74 ioToTcRn :: IO r -> TcRn r
83 -> IO (Messages, Maybe r)
84 -- Nothing => error thrown by the thing inside
85 -- (error messages should have been printed already)
87 initTc hsc_env hsc_src mod do_this
88 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
89 tvs_var <- newIORef emptyVarSet ;
90 type_env_var <- newIORef emptyNameEnv ;
91 dfuns_var <- newIORef emptyNameSet ;
92 keep_var <- newIORef emptyNameSet ;
93 th_var <- newIORef False ;
94 dfun_n_var <- newIORef 1 ;
99 tcg_rdr_env = hsc_global_rdr_env hsc_env,
100 tcg_fix_env = emptyNameEnv,
101 tcg_default = Nothing,
102 tcg_type_env = hsc_global_type_env hsc_env,
103 tcg_type_env_var = type_env_var,
104 tcg_inst_env = emptyInstEnv,
105 tcg_inst_uses = dfuns_var,
106 tcg_th_used = th_var,
107 tcg_exports = emptyNameSet,
108 tcg_imports = init_imports,
110 tcg_rn_imports = Nothing,
111 tcg_rn_exports = Nothing,
112 tcg_rn_decls = Nothing,
113 tcg_binds = emptyLHsBinds,
114 tcg_deprecs = NoDeprecs,
118 tcg_dfun_n = dfun_n_var,
123 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
125 tcl_rdr = emptyLocalRdrEnv,
126 tcl_th_ctxt = topStage,
127 tcl_arrow_ctxt = NoArrowCtxt,
128 tcl_env = emptyNameEnv,
129 tcl_tyvars = tvs_var,
130 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
134 -- OK, here's the business end!
135 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
136 addBreakpointBindings $
137 do { r <- tryM do_this
139 Right res -> return (Just res)
140 Left _ -> return Nothing } ;
142 -- Collect any error messages
143 msgs <- readIORef errs_var ;
145 let { dflags = hsc_dflags hsc_env
146 ; final_res | errorsFound dflags msgs = Nothing
147 | otherwise = maybe_res } ;
149 return (msgs, final_res)
152 init_imports = emptyImportAvails {imp_env =
153 unitUFM (moduleName mod) emptyNameSet}
154 -- Initialise tcg_imports with an empty set of bindings for
155 -- this module, so that if we see 'module M' in the export
156 -- list, and there are no bindings in M, we don't bleat
157 -- "unknown module M".
159 initTcPrintErrors -- Used from the interactive loop only
164 initTcPrintErrors env mod todo = do
165 (msgs, res) <- initTc env HsSrcFile mod todo
166 printErrorsAndWarnings (hsc_dflags env) msgs
171 addBreakpointBindings :: TcM a -> TcM a
172 addBreakpointBindings thing_inside
173 #if defined(GHCI) && defined(BREAKPOINT)
174 = do { unique <- newUnique
175 ; let { var = mkInternalName unique (mkOccName tvName "a") noSrcLoc;
176 tyvar = mkTyVar var liftedTypeKind;
177 basicType extra = (FunTy intTy
178 (FunTy (mkListTy unitTy)
182 (FunTy (TyVarTy tyvar)
183 (TyVarTy tyvar)))))));
185 = mkGlobalId VanillaGlobal breakpointJumpName
186 (basicType id) vanillaIdInfo;
188 = mkGlobalId VanillaGlobal breakpointCondJumpName
189 (basicType (FunTy boolTy)) vanillaIdInfo
191 ; tcExtendIdEnv [breakpointJumpId, breakpointCondJumpId] thing_inside}
197 %************************************************************************
201 %************************************************************************
205 initTcRnIf :: Char -- Tag for unique supply
210 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
211 = do { us <- mkSplitUniqSupply uniq_tag ;
212 ; us_var <- newIORef us ;
214 ; let { env = Env { env_top = hsc_env,
217 env_lcl = lcl_env } }
219 ; runIOEnv env thing_inside
223 %************************************************************************
227 %************************************************************************
230 getTopEnv :: TcRnIf gbl lcl HscEnv
231 getTopEnv = do { env <- getEnv; return (env_top env) }
233 getGblEnv :: TcRnIf gbl lcl gbl
234 getGblEnv = do { env <- getEnv; return (env_gbl env) }
236 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
237 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
238 env { env_gbl = upd gbl })
240 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
241 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
243 getLclEnv :: TcRnIf gbl lcl lcl
244 getLclEnv = do { env <- getEnv; return (env_lcl env) }
246 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
247 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
248 env { env_lcl = upd lcl })
250 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
251 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
253 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
254 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
256 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
257 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
264 getDOpts :: TcRnIf gbl lcl DynFlags
265 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
267 doptM :: DynFlag -> TcRnIf gbl lcl Bool
268 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
270 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
271 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
272 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
274 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
275 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
276 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
278 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
279 ifOptM flag thing_inside = do { b <- doptM flag;
280 if b then thing_inside else return () }
282 getGhcMode :: TcRnIf gbl lcl GhcMode
283 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
287 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
288 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
290 getEps :: TcRnIf gbl lcl ExternalPackageState
291 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
293 -- Updating the EPS. This should be an atomic operation.
294 -- Note the delicate 'seq' which forces the EPS before putting it in the
295 -- variable. Otherwise what happens is that we get
296 -- write eps_var (....(unsafeRead eps_var)....)
297 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
298 -- we make the unsafeRead happen before we update the variable.
300 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
302 updateEps upd_fn = do { traceIf (text "updating EPS")
303 ; eps_var <- getEpsVar
304 ; eps <- readMutVar eps_var
305 ; let { (eps', val) = upd_fn eps }
306 ; seq eps' (writeMutVar eps_var eps')
309 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
311 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
312 ; eps_var <- getEpsVar
313 ; eps <- readMutVar eps_var
314 ; let { eps' = upd_fn eps }
315 ; seq eps' (writeMutVar eps_var eps') }
317 getHpt :: TcRnIf gbl lcl HomePackageTable
318 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
320 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
321 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
322 ; return (eps, hsc_HPT env) }
325 %************************************************************************
329 %************************************************************************
332 newUnique :: TcRnIf gbl lcl Unique
334 = do { env <- getEnv ;
335 let { u_var = env_us env } ;
336 us <- readMutVar u_var ;
337 case splitUniqSupply us of { (us1,_) -> do {
338 writeMutVar u_var us1 ;
339 return $! uniqFromSupply us }}}
340 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
341 -- a chain of unevaluated supplies behind.
342 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
343 -- throw away one half of the new split supply. This is safe because this
344 -- is the only place we use that unique. Using the other half of the split
345 -- supply is safer, but slower.
347 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
349 = do { env <- getEnv ;
350 let { u_var = env_us env } ;
351 us <- readMutVar u_var ;
352 case splitUniqSupply us of { (us1,us2) -> do {
353 writeMutVar u_var us1 ;
356 newLocalName :: Name -> TcRnIf gbl lcl Name
357 newLocalName name -- Make a clone
358 = newUnique `thenM` \ uniq ->
359 returnM (mkInternalName uniq (nameOccName name) (getSrcLoc name))
363 %************************************************************************
367 %************************************************************************
370 traceTc, traceRn :: SDoc -> TcRn ()
371 traceRn = traceOptTcRn Opt_D_dump_rn_trace
372 traceTc = traceOptTcRn Opt_D_dump_tc_trace
373 traceSplice = traceOptTcRn Opt_D_dump_splices
376 traceIf :: SDoc -> TcRnIf m n ()
377 traceIf = traceOptIf Opt_D_dump_if_trace
378 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
381 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
382 traceOptIf flag doc = ifOptM flag $
383 ioToIOEnv (printForUser stderr alwaysQualify doc)
385 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
386 traceOptTcRn flag doc = ifOptM flag $ do
389 ; env0 <- tcInitTidyEnv
390 ; ctxt_msgs <- do_ctxt env0 ctxt
391 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
392 ; dumpTcRn real_doc }
394 dumpTcRn :: SDoc -> TcRn ()
395 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
396 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
398 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
399 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
403 %************************************************************************
405 Typechecker global environment
407 %************************************************************************
410 getModule :: TcRn Module
411 getModule = do { env <- getGblEnv; return (tcg_mod env) }
413 setModule :: Module -> TcRn a -> TcRn a
414 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
416 tcIsHsBoot :: TcRn Bool
417 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
419 getGlobalRdrEnv :: TcRn GlobalRdrEnv
420 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
422 getImports :: TcRn ImportAvails
423 getImports = do { env <- getGblEnv; return (tcg_imports env) }
425 getFixityEnv :: TcRn FixityEnv
426 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
428 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
429 extendFixityEnv new_bit
430 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
431 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
433 getDefaultTys :: TcRn (Maybe [Type])
434 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
437 %************************************************************************
441 %************************************************************************
444 getSrcSpanM :: TcRn SrcSpan
445 -- Avoid clash with Name.getSrcLoc
446 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
448 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
449 setSrcSpan loc thing_inside
450 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
451 | otherwise = thing_inside -- Don't overwrite useful info with useless
453 addLocM :: (a -> TcM b) -> Located a -> TcM b
454 addLocM fn (L loc a) = setSrcSpan loc $ fn a
456 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
457 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
459 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
460 wrapLocFstM fn (L loc a) =
465 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
466 wrapLocSndM fn (L loc a) =
474 getErrsVar :: TcRn (TcRef Messages)
475 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
477 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
478 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
480 addErr :: Message -> TcRn ()
481 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
483 addLocErr :: Located e -> (e -> Message) -> TcRn ()
484 addLocErr (L loc e) fn = addErrAt loc (fn e)
486 addErrAt :: SrcSpan -> Message -> TcRn ()
487 addErrAt loc msg = addLongErrAt loc msg empty
489 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
490 addLongErrAt loc msg extra
491 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
492 errs_var <- getErrsVar ;
493 rdr_env <- getGlobalRdrEnv ;
494 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
495 (warns, errs) <- readMutVar errs_var ;
496 writeMutVar errs_var (warns, errs `snocBag` err) }
498 addErrs :: [(SrcSpan,Message)] -> TcRn ()
499 addErrs msgs = mappM_ add msgs
501 add (loc,msg) = addErrAt loc msg
503 addReport :: Message -> TcRn ()
504 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
506 addReportAt :: SrcSpan -> Message -> TcRn ()
508 = do { errs_var <- getErrsVar ;
509 rdr_env <- getGlobalRdrEnv ;
510 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
511 (warns, errs) <- readMutVar errs_var ;
512 writeMutVar errs_var (warns `snocBag` warn, errs) }
514 addWarn :: Message -> TcRn ()
515 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
517 addWarnAt :: SrcSpan -> Message -> TcRn ()
518 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
520 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
521 addLocWarn (L loc e) fn = addReportAt loc (fn e)
523 checkErr :: Bool -> Message -> TcRn ()
524 -- Add the error if the bool is False
525 checkErr ok msg = checkM ok (addErr msg)
527 warnIf :: Bool -> Message -> TcRn ()
528 warnIf True msg = addWarn msg
529 warnIf False msg = return ()
531 addMessages :: Messages -> TcRn ()
532 addMessages (m_warns, m_errs)
533 = do { errs_var <- getErrsVar ;
534 (warns, errs) <- readMutVar errs_var ;
535 writeMutVar errs_var (warns `unionBags` m_warns,
536 errs `unionBags` m_errs) }
538 discardWarnings :: TcRn a -> TcRn a
539 -- Ignore warnings inside the thing inside;
540 -- used to ignore-unused-variable warnings inside derived code
541 -- With -dppr-debug, the effects is switched off, so you can still see
542 -- what warnings derived code would give
543 discardWarnings thing_inside
544 | opt_PprStyle_Debug = thing_inside
546 = do { errs_var <- newMutVar emptyMessages
547 ; result <- setErrsVar errs_var thing_inside
548 ; (_warns, errs) <- readMutVar errs_var
549 ; addMessages (emptyBag, errs)
555 try_m :: TcRn r -> TcRn (Either Exception r)
556 -- Does try_m, with a debug-trace on failure
558 = do { mb_r <- tryM thing ;
560 Left exn -> do { traceTc (exn_msg exn); return mb_r }
561 Right r -> return mb_r }
563 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
565 -----------------------
566 recoverM :: TcRn r -- Recovery action; do this if the main one fails
567 -> TcRn r -- Main action: do this first
569 -- Errors in 'thing' are retained
570 recoverM recover thing
571 = do { mb_res <- try_m thing ;
574 Right res -> returnM res }
576 -----------------------
577 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
578 -- (tryTc m) executes m, and returns
579 -- Just r, if m succeeds (returning r)
580 -- Nothing, if m fails
581 -- It also returns all the errors and warnings accumulated by m
582 -- It always succeeds (never raises an exception)
584 = do { errs_var <- newMutVar emptyMessages ;
585 res <- try_m (setErrsVar errs_var m) ;
586 msgs <- readMutVar errs_var ;
587 return (msgs, case res of
589 Right val -> Just val)
590 -- The exception is always the IOEnv built-in
591 -- in exception; see IOEnv.failM
594 -----------------------
595 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
596 -- Run the thing, returning
597 -- Just r, if m succceeds with no error messages
598 -- Nothing, if m fails, or if it succeeds but has error messages
599 -- Either way, the messages are returned; even in the Just case
600 -- there might be warnings
602 = do { (msgs, res) <- tryTc thing
604 ; let errs_found = errorsFound dflags msgs
605 ; return (msgs, case res of
607 Just val | errs_found -> Nothing
608 | otherwise -> Just val)
611 -----------------------
612 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
613 -- Just like tryTcErrs, except that it ensures that the LIE
614 -- for the thing is propagated only if there are no errors
615 -- Hence it's restricted to the type-check monad
616 tryTcLIE thing_inside
617 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
619 Nothing -> return (msgs, Nothing)
620 Just val -> do { extendLIEs lie; return (msgs, Just val) }
623 -----------------------
624 tryTcLIE_ :: TcM r -> TcM r -> TcM r
625 -- (tryTcLIE_ r m) tries m;
626 -- if m succeeds with no error messages, it's the answer
627 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
628 tryTcLIE_ recover main
629 = do { (msgs, mb_res) <- tryTcLIE main
631 Just val -> do { addMessages msgs -- There might be warnings
633 Nothing -> recover -- Discard all msgs
636 -----------------------
637 checkNoErrs :: TcM r -> TcM r
638 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
639 -- If m fails then (checkNoErrsTc m) fails.
640 -- If m succeeds, it checks whether m generated any errors messages
641 -- (it might have recovered internally)
642 -- If so, it fails too.
643 -- Regardless, any errors generated by m are propagated to the enclosing context.
645 = do { (msgs, mb_res) <- tryTcLIE main
649 Just val -> return val
652 ifErrsM :: TcRn r -> TcRn r -> TcRn r
653 -- ifErrsM bale_out main
654 -- does 'bale_out' if there are errors in errors collection
655 -- otherwise does 'main'
656 ifErrsM bale_out normal
657 = do { errs_var <- getErrsVar ;
658 msgs <- readMutVar errs_var ;
660 if errorsFound dflags msgs then
665 failIfErrsM :: TcRn ()
666 -- Useful to avoid error cascades
667 failIfErrsM = ifErrsM failM (return ())
671 %************************************************************************
673 Context management and error message generation
676 %************************************************************************
679 getErrCtxt :: TcM ErrCtxt
680 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
682 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
683 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
685 addErrCtxt :: Message -> TcM a -> TcM a
686 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
688 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
689 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
691 -- Helper function for the above
692 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
693 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
694 env { tcl_ctxt = upd ctxt })
696 -- Conditionally add an error context
697 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
698 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
699 maybeAddErrCtxt Nothing thing_inside = thing_inside
701 popErrCtxt :: TcM a -> TcM a
702 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
704 getInstLoc :: InstOrigin -> TcM InstLoc
706 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
707 return (InstLoc origin loc (tcl_ctxt env)) }
709 addInstCtxt :: InstLoc -> TcM a -> TcM a
710 -- Add the SrcSpan and context from the first Inst in the list
711 -- (they all have similar locations)
712 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
713 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
716 The addErrTc functions add an error message, but do not cause failure.
717 The 'M' variants pass a TidyEnv that has already been used to
718 tidy up the message; we then use it to tidy the context messages
721 addErrTc :: Message -> TcM ()
722 addErrTc err_msg = do { env0 <- tcInitTidyEnv
723 ; addErrTcM (env0, err_msg) }
725 addErrsTc :: [Message] -> TcM ()
726 addErrsTc err_msgs = mappM_ addErrTc err_msgs
728 addErrTcM :: (TidyEnv, Message) -> TcM ()
729 addErrTcM (tidy_env, err_msg)
730 = do { ctxt <- getErrCtxt ;
732 add_err_tcm tidy_env err_msg loc ctxt }
735 The failWith functions add an error message and cause failure
738 failWithTc :: Message -> TcM a -- Add an error message and fail
740 = addErrTc err_msg >> failM
742 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
743 failWithTcM local_and_msg
744 = addErrTcM local_and_msg >> failM
746 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
747 checkTc True err = returnM ()
748 checkTc False err = failWithTc err
751 Warnings have no 'M' variant, nor failure
754 addWarnTc :: Message -> TcM ()
756 = do { ctxt <- getErrCtxt ;
757 env0 <- tcInitTidyEnv ;
758 ctxt_msgs <- do_ctxt env0 ctxt ;
759 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
761 warnTc :: Bool -> Message -> TcM ()
762 warnTc warn_if_true warn_msg
763 | warn_if_true = addWarnTc warn_msg
764 | otherwise = return ()
767 -----------------------------------
770 We initialise the "tidy-env", used for tidying types before printing,
771 by building a reverse map from the in-scope type variables to the
772 OccName that the programmer originally used for them
775 tcInitTidyEnv :: TcM TidyEnv
777 = do { lcl_env <- getLclEnv
778 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
779 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
781 ; return (foldl add emptyTidyEnv nm_tv_prs) }
783 add (env,subst) (name, tyvar)
784 = case tidyOccName env (nameOccName name) of
785 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
787 tyvar' = setTyVarName tyvar name'
788 name' = tidyNameOcc name occ'
791 -----------------------------------
792 Other helper functions
795 add_err_tcm tidy_env err_msg loc ctxt
796 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
797 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
801 do_ctxt tidy_env (c:cs)
802 = do { (tidy_env', m) <- c tidy_env ;
803 ms <- do_ctxt tidy_env' cs ;
806 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
807 | otherwise = take 3 ctxt
810 debugTc is useful for monadic debugging code
813 debugTc :: TcM () -> TcM ()
815 debugTc thing = thing
817 debugTc thing = return ()
821 %************************************************************************
823 Type constraints (the so-called LIE)
825 %************************************************************************
828 nextDFunIndex :: TcM Int -- Get the next dfun index
829 nextDFunIndex = do { env <- getGblEnv
830 ; let dfun_n_var = tcg_dfun_n env
831 ; n <- readMutVar dfun_n_var
832 ; writeMutVar dfun_n_var (n+1)
835 getLIEVar :: TcM (TcRef LIE)
836 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
838 setLIEVar :: TcRef LIE -> TcM a -> TcM a
839 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
841 getLIE :: TcM a -> TcM (a, [Inst])
842 -- (getLIE m) runs m, and returns the type constraints it generates
844 = do { lie_var <- newMutVar emptyLIE ;
845 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
847 lie <- readMutVar lie_var ;
848 return (res, lieToList lie) }
850 extendLIE :: Inst -> TcM ()
852 = do { lie_var <- getLIEVar ;
853 lie <- readMutVar lie_var ;
854 writeMutVar lie_var (inst `consLIE` lie) }
856 extendLIEs :: [Inst] -> TcM ()
860 = do { lie_var <- getLIEVar ;
861 lie <- readMutVar lie_var ;
862 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
866 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
867 -- Set the local type envt, but do *not* disturb other fields,
868 -- notably the lie_var
869 setLclTypeEnv lcl_env thing_inside
870 = updLclEnv upd thing_inside
872 upd env = env { tcl_env = tcl_env lcl_env,
873 tcl_tyvars = tcl_tyvars lcl_env }
877 %************************************************************************
879 Template Haskell context
881 %************************************************************************
884 recordThUse :: TcM ()
885 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
887 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
888 keepAliveTc n = do { env <- getGblEnv;
889 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
891 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
892 keepAliveSetTc ns = do { env <- getGblEnv;
893 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
895 getStage :: TcM ThStage
896 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
898 setStage :: ThStage -> TcM a -> TcM a
899 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
903 %************************************************************************
905 Stuff for the renamer's local env
907 %************************************************************************
910 getLocalRdrEnv :: RnM LocalRdrEnv
911 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
913 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
914 setLocalRdrEnv rdr_env thing_inside
915 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
919 %************************************************************************
921 Stuff for interface decls
923 %************************************************************************
926 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
927 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
929 if_tv_env = emptyOccEnv,
930 if_id_env = emptyOccEnv }
932 initIfaceTcRn :: IfG a -> TcRn a
933 initIfaceTcRn thing_inside
934 = do { tcg_env <- getGblEnv
935 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
936 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
937 ; setEnvs (if_env, ()) thing_inside }
939 initIfaceExtCore :: IfL a -> TcRn a
940 initIfaceExtCore thing_inside
941 = do { tcg_env <- getGblEnv
942 ; let { mod = tcg_mod tcg_env
943 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
944 ; if_env = IfGblEnv {
945 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
946 ; if_lenv = mkIfLclEnv mod doc
948 ; setEnvs (if_env, if_lenv) thing_inside }
950 initIfaceCheck :: HscEnv -> IfG a -> IO a
951 -- Used when checking the up-to-date-ness of the old Iface
952 -- Initialise the environment with no useful info at all
953 initIfaceCheck hsc_env do_this
954 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
955 ; initTcRnIf 'i' hsc_env gbl_env () do_this
958 initIfaceTc :: ModIface
959 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
960 -- Used when type-checking checking an up-to-date interface file
961 -- No type envt from the current module, but we do know the module dependencies
962 initIfaceTc iface do_this
963 = do { tc_env_var <- newMutVar emptyTypeEnv
964 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
965 ; if_lenv = mkIfLclEnv mod doc
967 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
970 mod = mi_module iface
971 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
973 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
974 -- Used when sucking in new Rules in SimplCore
975 -- We have available the type envt of the module being compiled, and we must use it
976 initIfaceRules hsc_env guts do_this
978 type_info = (mg_module guts, return (mg_types guts))
979 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
982 -- Run the thing; any exceptions just bubble out from here
983 ; initTcRnIf 'i' hsc_env gbl_env () do_this
986 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
987 initIfaceLcl mod loc_doc thing_inside
988 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
990 getIfModule :: IfL Module
991 getIfModule = do { env <- getLclEnv; return (if_mod env) }
994 failIfM :: Message -> IfL a
995 -- The Iface monad doesn't have a place to accumulate errors, so we
996 -- just fall over fast if one happens; it "shouldnt happen".
997 -- We use IfL here so that we can get context info out of the local env
999 = do { env <- getLclEnv
1000 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1001 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
1004 --------------------
1005 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1006 -- Run thing_inside in an interleaved thread.
1007 -- It shares everything with the parent thread, so this is DANGEROUS.
1009 -- It returns Nothing if the computation fails
1011 -- It's used for lazily type-checking interface
1012 -- signatures, which is pretty benign
1014 forkM_maybe doc thing_inside
1015 = do { unsafeInterleaveM $
1016 do { traceIf (text "Starting fork {" <+> doc)
1018 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1021 Right r -> do { traceIf (text "} ending fork" <+> doc)
1025 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1026 -- Otherwise we silently discard errors. Errors can legitimately
1027 -- happen when compiling interface signatures (see tcInterfaceSigs)
1028 ifOptM Opt_D_dump_if_trace
1029 (print_errs (hang (text "forkM failed:" <+> doc)
1030 4 (text (show exn))))
1032 ; traceIf (text "} ending fork (badly)" <+> doc)
1036 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1038 forkM :: SDoc -> IfL a -> IfL a
1039 forkM doc thing_inside
1040 = do { mb_res <- forkM_maybe doc thing_inside
1041 ; return (case mb_res of
1042 Nothing -> pgmError "Cannot continue after interface file error"
1043 -- pprPanic "forkM" doc