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, TyThing(..) )
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 )
20 import PrelNames ( breakpointJumpName )
21 import NameEnv ( mkNameEnv )
24 import HsSyn ( emptyLHsBinds )
25 import HscTypes ( HscEnv(..), ModGuts(..), ModIface(..),
26 TyThing, TypeEnv, emptyTypeEnv, HscSource(..),
27 isHsBoot, ModSummary(..),
28 ExternalPackageState(..), HomePackageTable,
29 Deprecs(..), FixityEnv, FixItem,
30 lookupType, unQualInScope )
31 import Module ( Module, unitModuleEnv )
32 import RdrName ( GlobalRdrEnv, emptyGlobalRdrEnv,
33 LocalRdrEnv, emptyLocalRdrEnv )
34 import Name ( Name, isInternalName, mkInternalName, tidyNameOcc, nameOccName, getSrcLoc )
36 import TcType ( tcIsTyVarTy, tcGetTyVar )
37 import NameEnv ( extendNameEnvList, nameEnvElts )
38 import InstEnv ( emptyInstEnv )
40 import Var ( setTyVarName )
41 import VarSet ( emptyVarSet )
42 import VarEnv ( TidyEnv, emptyTidyEnv, extendVarEnv )
43 import ErrUtils ( Message, Messages, emptyMessages, errorsFound,
44 mkWarnMsg, printErrorsAndWarnings,
45 mkLocMessage, mkLongErrMsg )
46 import Packages ( mkHomeModules )
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, splitUniqSupply )
54 import Unique ( Unique )
55 import DynFlags ( DynFlags(..), DynFlag(..), dopt, dopt_set, GhcMode )
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 = emptyGlobalRdrEnv,
100 tcg_fix_env = emptyNameEnv,
101 tcg_default = Nothing,
102 tcg_type_env = emptyNameEnv,
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,
109 tcg_home_mods = home_mods,
111 tcg_rn_imports = Nothing,
112 tcg_rn_exports = Nothing,
113 tcg_rn_decls = Nothing,
114 tcg_binds = emptyLHsBinds,
115 tcg_deprecs = NoDeprecs,
119 tcg_dfun_n = dfun_n_var,
124 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
126 tcl_rdr = emptyLocalRdrEnv,
127 tcl_th_ctxt = topStage,
128 tcl_arrow_ctxt = NoArrowCtxt,
129 tcl_env = emptyNameEnv,
130 tcl_tyvars = tvs_var,
131 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
135 -- OK, here's the business end!
136 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
138 #if defined(GHCI) && defined(BREAKPOINT)
139 unique <- newUnique ;
140 let { var = mkInternalName unique (mkOccName tvName "a") noSrcLoc;
141 tyvar = mkTyVar var liftedTypeKind;
142 breakpointJumpType = mkGlobalId
146 (FunTy (mkListTy unitTy)
149 (FunTy (TyVarTy tyvar)
152 new_env = mkNameEnv [(breakpointJumpName,AGlobal (AnId breakpointJumpType))];
154 r <- tryM (updLclEnv (\gbl -> gbl{tcl_env=new_env}) do_this)
159 Right res -> return (Just res)
160 Left _ -> return Nothing } ;
162 -- Collect any error messages
163 msgs <- readIORef errs_var ;
165 let { dflags = hsc_dflags hsc_env
166 ; final_res | errorsFound dflags msgs = Nothing
167 | otherwise = maybe_res } ;
169 return (msgs, final_res)
172 home_mods = mkHomeModules (map ms_mod (hsc_mod_graph hsc_env))
173 -- A guess at the home modules. This will be correct in
174 -- --make and GHCi modes, but in one-shot mode we need to
175 -- fix it up after we know the real dependencies of the current
176 -- module (see tcRnModule).
177 -- Setting it here is necessary for the typechecker entry points
178 -- other than tcRnModule: tcRnGetInfo, for example. These are
179 -- all called via the GHC module, so hsc_mod_graph will contain
180 -- something sensible.
182 init_imports = emptyImportAvails {imp_env = unitModuleEnv mod emptyNameSet}
183 -- Initialise tcg_imports with an empty set of bindings for
184 -- this module, so that if we see 'module M' in the export
185 -- list, and there are no bindings in M, we don't bleat
186 -- "unknown module M".
188 initTcPrintErrors -- Used from the interactive loop only
193 initTcPrintErrors env mod todo = do
194 (msgs, res) <- initTc env HsSrcFile mod todo
195 printErrorsAndWarnings (hsc_dflags env) msgs
198 -- mkImpTypeEnv makes the imported symbol table
199 mkImpTypeEnv :: ExternalPackageState -> HomePackageTable
200 -> Name -> Maybe TyThing
201 mkImpTypeEnv pcs hpt = lookup
204 lookup name | isInternalName name = Nothing
205 | otherwise = lookupType hpt pte name
209 %************************************************************************
213 %************************************************************************
217 initTcRnIf :: Char -- Tag for unique supply
222 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
223 = do { us <- mkSplitUniqSupply uniq_tag ;
224 ; us_var <- newIORef us ;
226 ; let { env = Env { env_top = hsc_env,
229 env_lcl = lcl_env } }
231 ; runIOEnv env thing_inside
235 %************************************************************************
239 %************************************************************************
242 getTopEnv :: TcRnIf gbl lcl HscEnv
243 getTopEnv = do { env <- getEnv; return (env_top env) }
245 getGblEnv :: TcRnIf gbl lcl gbl
246 getGblEnv = do { env <- getEnv; return (env_gbl env) }
248 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
249 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
250 env { env_gbl = upd gbl })
252 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
253 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
255 getLclEnv :: TcRnIf gbl lcl lcl
256 getLclEnv = do { env <- getEnv; return (env_lcl env) }
258 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
259 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
260 env { env_lcl = upd lcl })
262 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
263 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
265 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
266 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
268 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
269 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
276 getDOpts :: TcRnIf gbl lcl DynFlags
277 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
279 doptM :: DynFlag -> TcRnIf gbl lcl Bool
280 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
282 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
283 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
284 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
286 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
287 ifOptM flag thing_inside = do { b <- doptM flag;
288 if b then thing_inside else return () }
290 getGhcMode :: TcRnIf gbl lcl GhcMode
291 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
295 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
296 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
298 getEps :: TcRnIf gbl lcl ExternalPackageState
299 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
301 -- Updating the EPS. This should be an atomic operation.
302 -- Note the delicate 'seq' which forces the EPS before putting it in the
303 -- variable. Otherwise what happens is that we get
304 -- write eps_var (....(unsafeRead eps_var)....)
305 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
306 -- we make the unsafeRead happen before we update the variable.
308 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
310 updateEps upd_fn = do { traceIf (text "updating EPS")
311 ; eps_var <- getEpsVar
312 ; eps <- readMutVar eps_var
313 ; let { (eps', val) = upd_fn eps }
314 ; seq eps' (writeMutVar eps_var eps')
317 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
319 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
320 ; eps_var <- getEpsVar
321 ; eps <- readMutVar eps_var
322 ; let { eps' = upd_fn eps }
323 ; seq eps' (writeMutVar eps_var eps') }
325 getHpt :: TcRnIf gbl lcl HomePackageTable
326 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
328 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
329 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
330 ; return (eps, hsc_HPT env) }
333 %************************************************************************
337 %************************************************************************
340 newUnique :: TcRnIf gbl lcl Unique
341 newUnique = do { us <- newUniqueSupply ;
342 return (uniqFromSupply us) }
344 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
346 = do { env <- getEnv ;
347 let { u_var = env_us env } ;
348 us <- readMutVar u_var ;
349 let { (us1, us2) = splitUniqSupply us } ;
350 writeMutVar u_var us1 ;
353 newLocalName :: Name -> TcRnIf gbl lcl Name
354 newLocalName name -- Make a clone
355 = newUnique `thenM` \ uniq ->
356 returnM (mkInternalName uniq (nameOccName name) (getSrcLoc name))
360 %************************************************************************
364 %************************************************************************
367 traceTc, traceRn :: SDoc -> TcRn ()
368 traceRn = traceOptTcRn Opt_D_dump_rn_trace
369 traceTc = traceOptTcRn Opt_D_dump_tc_trace
370 traceSplice = traceOptTcRn Opt_D_dump_splices
373 traceIf :: SDoc -> TcRnIf m n ()
374 traceIf = traceOptIf Opt_D_dump_if_trace
375 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
378 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
379 traceOptIf flag doc = ifOptM flag $
380 ioToIOEnv (printForUser stderr alwaysQualify doc)
382 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
383 traceOptTcRn flag doc = ifOptM flag $ do
386 ; env0 <- tcInitTidyEnv
387 ; ctxt_msgs <- do_ctxt env0 ctxt
388 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
389 ; dumpTcRn real_doc }
391 dumpTcRn :: SDoc -> TcRn ()
392 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
393 ioToTcRn (printForUser stderr (unQualInScope rdr_env) doc) }
395 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
396 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
400 %************************************************************************
402 Typechecker global environment
404 %************************************************************************
407 getModule :: TcRn Module
408 getModule = do { env <- getGblEnv; return (tcg_mod env) }
410 setModule :: Module -> TcRn a -> TcRn a
411 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
413 tcIsHsBoot :: TcRn Bool
414 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
416 getGlobalRdrEnv :: TcRn GlobalRdrEnv
417 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
419 getImports :: TcRn ImportAvails
420 getImports = do { env <- getGblEnv; return (tcg_imports env) }
422 getFixityEnv :: TcRn FixityEnv
423 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
425 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
426 extendFixityEnv new_bit
427 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
428 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
430 getDefaultTys :: TcRn (Maybe [Type])
431 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
434 %************************************************************************
438 %************************************************************************
441 getSrcSpanM :: TcRn SrcSpan
442 -- Avoid clash with Name.getSrcLoc
443 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
445 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
446 setSrcSpan loc thing_inside
447 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
448 | otherwise = thing_inside -- Don't overwrite useful info with useless
450 addLocM :: (a -> TcM b) -> Located a -> TcM b
451 addLocM fn (L loc a) = setSrcSpan loc $ fn a
453 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
454 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
456 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
457 wrapLocFstM fn (L loc a) =
462 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
463 wrapLocSndM fn (L loc a) =
471 getErrsVar :: TcRn (TcRef Messages)
472 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
474 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
475 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
477 addErr :: Message -> TcRn ()
478 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
480 addLocErr :: Located e -> (e -> Message) -> TcRn ()
481 addLocErr (L loc e) fn = addErrAt loc (fn e)
483 addErrAt :: SrcSpan -> Message -> TcRn ()
484 addErrAt loc msg = addLongErrAt loc msg empty
486 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
487 addLongErrAt loc msg extra
488 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
489 errs_var <- getErrsVar ;
490 rdr_env <- getGlobalRdrEnv ;
491 let { err = mkLongErrMsg loc (unQualInScope rdr_env) msg extra } ;
492 (warns, errs) <- readMutVar errs_var ;
493 writeMutVar errs_var (warns, errs `snocBag` err) }
495 addErrs :: [(SrcSpan,Message)] -> TcRn ()
496 addErrs msgs = mappM_ add msgs
498 add (loc,msg) = addErrAt loc msg
500 addReport :: Message -> TcRn ()
501 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
503 addReportAt :: SrcSpan -> Message -> TcRn ()
505 = do { errs_var <- getErrsVar ;
506 rdr_env <- getGlobalRdrEnv ;
507 let { warn = mkWarnMsg loc (unQualInScope rdr_env) msg } ;
508 (warns, errs) <- readMutVar errs_var ;
509 writeMutVar errs_var (warns `snocBag` warn, errs) }
511 addWarn :: Message -> TcRn ()
512 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
514 addWarnAt :: SrcSpan -> Message -> TcRn ()
515 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
517 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
518 addLocWarn (L loc e) fn = addReportAt loc (fn e)
520 checkErr :: Bool -> Message -> TcRn ()
521 -- Add the error if the bool is False
522 checkErr ok msg = checkM ok (addErr msg)
524 warnIf :: Bool -> Message -> TcRn ()
525 warnIf True msg = addWarn msg
526 warnIf False msg = return ()
528 addMessages :: Messages -> TcRn ()
529 addMessages (m_warns, m_errs)
530 = do { errs_var <- getErrsVar ;
531 (warns, errs) <- readMutVar errs_var ;
532 writeMutVar errs_var (warns `unionBags` m_warns,
533 errs `unionBags` m_errs) }
535 discardWarnings :: TcRn a -> TcRn a
536 -- Ignore warnings inside the thing inside;
537 -- used to ignore-unused-variable warnings inside derived code
538 -- With -dppr-debug, the effects is switched off, so you can still see
539 -- what warnings derived code would give
540 discardWarnings thing_inside
541 | opt_PprStyle_Debug = thing_inside
543 = do { errs_var <- newMutVar emptyMessages
544 ; result <- setErrsVar errs_var thing_inside
545 ; (_warns, errs) <- readMutVar errs_var
546 ; addMessages (emptyBag, errs)
552 try_m :: TcRn r -> TcRn (Either Exception r)
553 -- Does try_m, with a debug-trace on failure
555 = do { mb_r <- tryM thing ;
557 Left exn -> do { traceTc (exn_msg exn); return mb_r }
558 Right r -> return mb_r }
560 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
562 -----------------------
563 recoverM :: TcRn r -- Recovery action; do this if the main one fails
564 -> TcRn r -- Main action: do this first
566 -- Errors in 'thing' are retained
567 recoverM recover thing
568 = do { mb_res <- try_m thing ;
571 Right res -> returnM res }
573 -----------------------
574 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
575 -- (tryTc m) executes m, and returns
576 -- Just r, if m succeeds (returning r)
577 -- Nothing, if m fails
578 -- It also returns all the errors and warnings accumulated by m
579 -- It always succeeds (never raises an exception)
581 = do { errs_var <- newMutVar emptyMessages ;
582 res <- try_m (setErrsVar errs_var m) ;
583 msgs <- readMutVar errs_var ;
584 return (msgs, case res of
586 Right val -> Just val)
587 -- The exception is always the IOEnv built-in
588 -- in exception; see IOEnv.failM
591 -----------------------
592 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
593 -- Run the thing, returning
594 -- Just r, if m succceeds with no error messages
595 -- Nothing, if m fails, or if it succeeds but has error messages
596 -- Either way, the messages are returned; even in the Just case
597 -- there might be warnings
599 = do { (msgs, res) <- tryTc thing
601 ; let errs_found = errorsFound dflags msgs
602 ; return (msgs, case res of
604 Just val | errs_found -> Nothing
605 | otherwise -> Just val)
608 -----------------------
609 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
610 -- Just like tryTcErrs, except that it ensures that the LIE
611 -- for the thing is propagated only if there are no errors
612 -- Hence it's restricted to the type-check monad
613 tryTcLIE thing_inside
614 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
616 Nothing -> return (msgs, Nothing)
617 Just val -> do { extendLIEs lie; return (msgs, Just val) }
620 -----------------------
621 tryTcLIE_ :: TcM r -> TcM r -> TcM r
622 -- (tryTcLIE_ r m) tries m;
623 -- if m succeeds with no error messages, it's the answer
624 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
625 tryTcLIE_ recover main
626 = do { (msgs, mb_res) <- tryTcLIE main
628 Just val -> do { addMessages msgs -- There might be warnings
630 Nothing -> recover -- Discard all msgs
633 -----------------------
634 checkNoErrs :: TcM r -> TcM r
635 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
636 -- If m fails then (checkNoErrsTc m) fails.
637 -- If m succeeds, it checks whether m generated any errors messages
638 -- (it might have recovered internally)
639 -- If so, it fails too.
640 -- Regardless, any errors generated by m are propagated to the enclosing context.
642 = do { (msgs, mb_res) <- tryTcLIE main
646 Just val -> return val
649 ifErrsM :: TcRn r -> TcRn r -> TcRn r
650 -- ifErrsM bale_out main
651 -- does 'bale_out' if there are errors in errors collection
652 -- otherwise does 'main'
653 ifErrsM bale_out normal
654 = do { errs_var <- getErrsVar ;
655 msgs <- readMutVar errs_var ;
657 if errorsFound dflags msgs then
662 failIfErrsM :: TcRn ()
663 -- Useful to avoid error cascades
664 failIfErrsM = ifErrsM failM (return ())
668 %************************************************************************
670 Context management and error message generation
673 %************************************************************************
676 getErrCtxt :: TcM ErrCtxt
677 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
679 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
680 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
682 addErrCtxt :: Message -> TcM a -> TcM a
683 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
685 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
686 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
688 -- Helper function for the above
689 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
690 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
691 env { tcl_ctxt = upd ctxt })
693 -- Conditionally add an error context
694 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
695 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
696 maybeAddErrCtxt Nothing thing_inside = thing_inside
698 popErrCtxt :: TcM a -> TcM a
699 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
701 getInstLoc :: InstOrigin -> TcM InstLoc
703 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
704 return (InstLoc origin loc (tcl_ctxt env)) }
706 addInstCtxt :: InstLoc -> TcM a -> TcM a
707 -- Add the SrcSpan and context from the first Inst in the list
708 -- (they all have similar locations)
709 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
710 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
713 The addErrTc functions add an error message, but do not cause failure.
714 The 'M' variants pass a TidyEnv that has already been used to
715 tidy up the message; we then use it to tidy the context messages
718 addErrTc :: Message -> TcM ()
719 addErrTc err_msg = do { env0 <- tcInitTidyEnv
720 ; addErrTcM (env0, err_msg) }
722 addErrsTc :: [Message] -> TcM ()
723 addErrsTc err_msgs = mappM_ addErrTc err_msgs
725 addErrTcM :: (TidyEnv, Message) -> TcM ()
726 addErrTcM (tidy_env, err_msg)
727 = do { ctxt <- getErrCtxt ;
729 add_err_tcm tidy_env err_msg loc ctxt }
732 The failWith functions add an error message and cause failure
735 failWithTc :: Message -> TcM a -- Add an error message and fail
737 = addErrTc err_msg >> failM
739 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
740 failWithTcM local_and_msg
741 = addErrTcM local_and_msg >> failM
743 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
744 checkTc True err = returnM ()
745 checkTc False err = failWithTc err
748 Warnings have no 'M' variant, nor failure
751 addWarnTc :: Message -> TcM ()
753 = do { ctxt <- getErrCtxt ;
754 env0 <- tcInitTidyEnv ;
755 ctxt_msgs <- do_ctxt env0 ctxt ;
756 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
758 warnTc :: Bool -> Message -> TcM ()
759 warnTc warn_if_true warn_msg
760 | warn_if_true = addWarnTc warn_msg
761 | otherwise = return ()
764 -----------------------------------
767 We initialise the "tidy-env", used for tidying types before printing,
768 by building a reverse map from the in-scope type variables to the
769 OccName that the programmer originally used for them
772 tcInitTidyEnv :: TcM TidyEnv
774 = do { lcl_env <- getLclEnv
775 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
776 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
778 ; return (foldl add emptyTidyEnv nm_tv_prs) }
780 add (env,subst) (name, tyvar)
781 = case tidyOccName env (nameOccName name) of
782 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
784 tyvar' = setTyVarName tyvar name'
785 name' = tidyNameOcc name occ'
788 -----------------------------------
789 Other helper functions
792 add_err_tcm tidy_env err_msg loc ctxt
793 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
794 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
798 do_ctxt tidy_env (c:cs)
799 = do { (tidy_env', m) <- c tidy_env ;
800 ms <- do_ctxt tidy_env' cs ;
803 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
804 | otherwise = take 3 ctxt
807 debugTc is useful for monadic debugging code
810 debugTc :: TcM () -> TcM ()
812 debugTc thing = thing
814 debugTc thing = return ()
818 %************************************************************************
820 Type constraints (the so-called LIE)
822 %************************************************************************
825 nextDFunIndex :: TcM Int -- Get the next dfun index
826 nextDFunIndex = do { env <- getGblEnv
827 ; let dfun_n_var = tcg_dfun_n env
828 ; n <- readMutVar dfun_n_var
829 ; writeMutVar dfun_n_var (n+1)
832 getLIEVar :: TcM (TcRef LIE)
833 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
835 setLIEVar :: TcRef LIE -> TcM a -> TcM a
836 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
838 getLIE :: TcM a -> TcM (a, [Inst])
839 -- (getLIE m) runs m, and returns the type constraints it generates
841 = do { lie_var <- newMutVar emptyLIE ;
842 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
844 lie <- readMutVar lie_var ;
845 return (res, lieToList lie) }
847 extendLIE :: Inst -> TcM ()
849 = do { lie_var <- getLIEVar ;
850 lie <- readMutVar lie_var ;
851 writeMutVar lie_var (inst `consLIE` lie) }
853 extendLIEs :: [Inst] -> TcM ()
857 = do { lie_var <- getLIEVar ;
858 lie <- readMutVar lie_var ;
859 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
863 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
864 -- Set the local type envt, but do *not* disturb other fields,
865 -- notably the lie_var
866 setLclTypeEnv lcl_env thing_inside
867 = updLclEnv upd thing_inside
869 upd env = env { tcl_env = tcl_env lcl_env,
870 tcl_tyvars = tcl_tyvars lcl_env }
874 %************************************************************************
876 Template Haskell context
878 %************************************************************************
881 recordThUse :: TcM ()
882 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
884 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
885 keepAliveTc n = do { env <- getGblEnv;
886 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
888 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
889 keepAliveSetTc ns = do { env <- getGblEnv;
890 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
892 getStage :: TcM ThStage
893 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
895 setStage :: ThStage -> TcM a -> TcM a
896 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
900 %************************************************************************
902 Stuff for the renamer's local env
904 %************************************************************************
907 getLocalRdrEnv :: RnM LocalRdrEnv
908 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
910 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
911 setLocalRdrEnv rdr_env thing_inside
912 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
916 %************************************************************************
918 Stuff for interface decls
920 %************************************************************************
923 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
924 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
926 if_tv_env = emptyOccEnv,
927 if_id_env = emptyOccEnv }
929 initIfaceTcRn :: IfG a -> TcRn a
930 initIfaceTcRn thing_inside
931 = do { tcg_env <- getGblEnv
932 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
933 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
934 ; setEnvs (if_env, ()) thing_inside }
936 initIfaceExtCore :: IfL a -> TcRn a
937 initIfaceExtCore thing_inside
938 = do { tcg_env <- getGblEnv
939 ; let { mod = tcg_mod tcg_env
940 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
941 ; if_env = IfGblEnv {
942 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
943 ; if_lenv = mkIfLclEnv mod doc
945 ; setEnvs (if_env, if_lenv) thing_inside }
947 initIfaceCheck :: HscEnv -> IfG a -> IO a
948 -- Used when checking the up-to-date-ness of the old Iface
949 -- Initialise the environment with no useful info at all
950 initIfaceCheck hsc_env do_this
951 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
952 ; initTcRnIf 'i' hsc_env gbl_env () do_this
955 initIfaceTc :: ModIface
956 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
957 -- Used when type-checking checking an up-to-date interface file
958 -- No type envt from the current module, but we do know the module dependencies
959 initIfaceTc iface do_this
960 = do { tc_env_var <- newMutVar emptyTypeEnv
961 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
962 ; if_lenv = mkIfLclEnv mod doc
964 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
967 mod = mi_module iface
968 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
970 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
971 -- Used when sucking in new Rules in SimplCore
972 -- We have available the type envt of the module being compiled, and we must use it
973 initIfaceRules hsc_env guts do_this
975 type_info = (mg_module guts, return (mg_types guts))
976 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
979 -- Run the thing; any exceptions just bubble out from here
980 ; initTcRnIf 'i' hsc_env gbl_env () do_this
983 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
984 initIfaceLcl mod loc_doc thing_inside
985 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
987 getIfModule :: IfL Module
988 getIfModule = do { env <- getLclEnv; return (if_mod env) }
991 failIfM :: Message -> IfL a
992 -- The Iface monad doesn't have a place to accumulate errors, so we
993 -- just fall over fast if one happens; it "shouldnt happen".
994 -- We use IfL here so that we can get context info out of the local env
996 = do { env <- getLclEnv
997 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
998 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
1001 --------------------
1002 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1003 -- Run thing_inside in an interleaved thread.
1004 -- It shares everything with the parent thread, so this is DANGEROUS.
1006 -- It returns Nothing if the computation fails
1008 -- It's used for lazily type-checking interface
1009 -- signatures, which is pretty benign
1011 forkM_maybe doc thing_inside
1012 = do { unsafeInterleaveM $
1013 do { traceIf (text "Starting fork {" <+> doc)
1014 ; mb_res <- tryM thing_inside ;
1016 Right r -> do { traceIf (text "} ending fork" <+> doc)
1020 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1021 -- Otherwise we silently discard errors. Errors can legitimately
1022 -- happen when compiling interface signatures (see tcInterfaceSigs)
1023 ifOptM Opt_D_dump_if_trace
1024 (print_errs (hang (text "forkM failed:" <+> doc)
1025 4 (text (show exn))))
1027 ; traceIf (text "} ending fork (badly)" <+> doc)
1031 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1033 forkM :: SDoc -> IfL a -> IfL a
1034 forkM doc thing_inside
1035 = do { mb_res <- forkM_maybe doc thing_inside
1036 ; return (case mb_res of
1037 Nothing -> pgmError "Cannot continue after interface file error"
1038 -- pprPanic "forkM" doc