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 )
24 import HsSyn ( emptyLHsBinds )
25 import HscTypes ( HscEnv(..), ModGuts(..), ModIface(..),
26 TypeEnv, emptyTypeEnv, HscSource(..), isHsBoot,
27 ExternalPackageState(..), HomePackageTable,
28 Deprecs(..), FixityEnv, FixItem,
30 import Module ( Module, moduleName )
31 import RdrName ( GlobalRdrEnv, LocalRdrEnv, emptyLocalRdrEnv )
32 import Name ( Name, mkInternalName, tidyNameOcc, nameOccName, getSrcLoc )
34 import TcType ( tcIsTyVarTy, tcGetTyVar )
35 import NameEnv ( extendNameEnvList, nameEnvElts )
36 import InstEnv ( emptyInstEnv )
38 import Var ( setTyVarName )
39 import VarSet ( emptyVarSet )
40 import VarEnv ( TidyEnv, emptyTidyEnv, extendVarEnv )
41 import ErrUtils ( Message, Messages, emptyMessages, errorsFound,
42 mkWarnMsg, printErrorsAndWarnings,
43 mkLocMessage, mkLongErrMsg )
44 import SrcLoc ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
45 import NameEnv ( emptyNameEnv )
46 import NameSet ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
47 import OccName ( emptyOccEnv, tidyOccName )
48 import Bag ( emptyBag )
50 import UniqSupply ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
51 import UniqFM ( unitUFM )
52 import Unique ( Unique )
53 import DynFlags ( DynFlags(..), DynFlag(..), dopt, dopt_set,
55 import StaticFlags ( opt_PprStyle_Debug )
56 import Bag ( snocBag, unionBags )
57 import Panic ( showException )
60 import DATA_IOREF ( newIORef, readIORef )
61 import EXCEPTION ( Exception )
66 %************************************************************************
70 %************************************************************************
73 ioToTcRn :: IO r -> TcRn r
82 -> IO (Messages, Maybe r)
83 -- Nothing => error thrown by the thing inside
84 -- (error messages should have been printed already)
86 initTc hsc_env hsc_src mod do_this
87 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
88 tvs_var <- newIORef emptyVarSet ;
89 type_env_var <- newIORef emptyNameEnv ;
90 dfuns_var <- newIORef emptyNameSet ;
91 keep_var <- newIORef emptyNameSet ;
92 th_var <- newIORef False ;
93 dfun_n_var <- newIORef 1 ;
98 tcg_rdr_env = hsc_global_rdr_env hsc_env,
99 tcg_fix_env = emptyNameEnv,
100 tcg_default = Nothing,
101 tcg_type_env = hsc_global_type_env hsc_env,
102 tcg_type_env_var = type_env_var,
103 tcg_inst_env = emptyInstEnv,
104 tcg_inst_uses = dfuns_var,
105 tcg_th_used = th_var,
106 tcg_exports = emptyNameSet,
107 tcg_imports = init_imports,
109 tcg_rn_imports = Nothing,
110 tcg_rn_exports = Nothing,
111 tcg_rn_decls = Nothing,
112 tcg_binds = emptyLHsBinds,
113 tcg_deprecs = NoDeprecs,
117 tcg_dfun_n = dfun_n_var,
122 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
124 tcl_rdr = emptyLocalRdrEnv,
125 tcl_th_ctxt = topStage,
126 tcl_arrow_ctxt = NoArrowCtxt,
127 tcl_env = emptyNameEnv,
128 tcl_tyvars = tvs_var,
129 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
133 -- OK, here's the business end!
134 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
135 addBreakpointBindings $
136 do { r <- tryM do_this
138 Right res -> return (Just res)
139 Left _ -> return Nothing } ;
141 -- Collect any error messages
142 msgs <- readIORef errs_var ;
144 let { dflags = hsc_dflags hsc_env
145 ; final_res | errorsFound dflags msgs = Nothing
146 | otherwise = maybe_res } ;
148 return (msgs, final_res)
151 init_imports = emptyImportAvails {imp_env =
152 unitUFM (moduleName 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
170 addBreakpointBindings :: TcM a -> TcM a
171 addBreakpointBindings thing_inside
172 #if defined(GHCI) && defined(BREAKPOINT)
173 = do { unique <- newUnique
174 ; let { var = mkInternalName unique (mkOccName tvName "a") noSrcLoc;
175 tyvar = mkTyVar var liftedTypeKind;
176 basicType extra = (FunTy intTy
177 (FunTy (mkListTy unitTy)
181 (FunTy (TyVarTy tyvar)
182 (TyVarTy tyvar)))))));
184 = mkGlobalId VanillaGlobal breakpointJumpName
185 (basicType id) vanillaIdInfo;
187 = mkGlobalId VanillaGlobal breakpointCondJumpName
188 (basicType (FunTy boolTy)) vanillaIdInfo
190 ; extendIdEnv [breakpoingJumpId, breakpointCondJumpId] thing_inside}
196 %************************************************************************
200 %************************************************************************
204 initTcRnIf :: Char -- Tag for unique supply
209 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
210 = do { us <- mkSplitUniqSupply uniq_tag ;
211 ; us_var <- newIORef us ;
213 ; let { env = Env { env_top = hsc_env,
216 env_lcl = lcl_env } }
218 ; runIOEnv env thing_inside
222 %************************************************************************
226 %************************************************************************
229 getTopEnv :: TcRnIf gbl lcl HscEnv
230 getTopEnv = do { env <- getEnv; return (env_top env) }
232 getGblEnv :: TcRnIf gbl lcl gbl
233 getGblEnv = do { env <- getEnv; return (env_gbl env) }
235 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
236 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
237 env { env_gbl = upd gbl })
239 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
240 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
242 getLclEnv :: TcRnIf gbl lcl lcl
243 getLclEnv = do { env <- getEnv; return (env_lcl env) }
245 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
246 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
247 env { env_lcl = upd lcl })
249 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
250 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
252 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
253 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
255 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
256 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
263 getDOpts :: TcRnIf gbl lcl DynFlags
264 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
266 doptM :: DynFlag -> TcRnIf gbl lcl Bool
267 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
269 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
270 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
271 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
273 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
274 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
275 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
277 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
278 ifOptM flag thing_inside = do { b <- doptM flag;
279 if b then thing_inside else return () }
281 getGhcMode :: TcRnIf gbl lcl GhcMode
282 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
286 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
287 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
289 getEps :: TcRnIf gbl lcl ExternalPackageState
290 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
292 -- Updating the EPS. This should be an atomic operation.
293 -- Note the delicate 'seq' which forces the EPS before putting it in the
294 -- variable. Otherwise what happens is that we get
295 -- write eps_var (....(unsafeRead eps_var)....)
296 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
297 -- we make the unsafeRead happen before we update the variable.
299 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
301 updateEps upd_fn = do { traceIf (text "updating EPS")
302 ; eps_var <- getEpsVar
303 ; eps <- readMutVar eps_var
304 ; let { (eps', val) = upd_fn eps }
305 ; seq eps' (writeMutVar eps_var eps')
308 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
310 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
311 ; eps_var <- getEpsVar
312 ; eps <- readMutVar eps_var
313 ; let { eps' = upd_fn eps }
314 ; seq eps' (writeMutVar eps_var eps') }
316 getHpt :: TcRnIf gbl lcl HomePackageTable
317 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
319 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
320 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
321 ; return (eps, hsc_HPT env) }
324 %************************************************************************
328 %************************************************************************
331 newUnique :: TcRnIf gbl lcl Unique
333 = do { env <- getEnv ;
334 let { u_var = env_us env } ;
335 us <- readMutVar u_var ;
336 case splitUniqSupply us of { (us1,_) -> do {
337 writeMutVar u_var us1 ;
338 return $! uniqFromSupply us }}}
339 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
340 -- a chain of unevaluated supplies behind.
341 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
342 -- throw away one half of the new split supply. This is safe because this
343 -- is the only place we use that unique. Using the other half of the split
344 -- supply is safer, but slower.
346 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
348 = do { env <- getEnv ;
349 let { u_var = env_us env } ;
350 us <- readMutVar u_var ;
351 case splitUniqSupply us of { (us1,us2) -> do {
352 writeMutVar u_var us1 ;
355 newLocalName :: Name -> TcRnIf gbl lcl Name
356 newLocalName name -- Make a clone
357 = newUnique `thenM` \ uniq ->
358 returnM (mkInternalName uniq (nameOccName name) (getSrcLoc name))
362 %************************************************************************
366 %************************************************************************
369 traceTc, traceRn :: SDoc -> TcRn ()
370 traceRn = traceOptTcRn Opt_D_dump_rn_trace
371 traceTc = traceOptTcRn Opt_D_dump_tc_trace
372 traceSplice = traceOptTcRn Opt_D_dump_splices
375 traceIf :: SDoc -> TcRnIf m n ()
376 traceIf = traceOptIf Opt_D_dump_if_trace
377 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
380 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
381 traceOptIf flag doc = ifOptM flag $
382 ioToIOEnv (printForUser stderr alwaysQualify doc)
384 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
385 traceOptTcRn flag doc = ifOptM flag $ do
388 ; env0 <- tcInitTidyEnv
389 ; ctxt_msgs <- do_ctxt env0 ctxt
390 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
391 ; dumpTcRn real_doc }
393 dumpTcRn :: SDoc -> TcRn ()
394 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
395 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
397 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
398 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
402 %************************************************************************
404 Typechecker global environment
406 %************************************************************************
409 getModule :: TcRn Module
410 getModule = do { env <- getGblEnv; return (tcg_mod env) }
412 setModule :: Module -> TcRn a -> TcRn a
413 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
415 tcIsHsBoot :: TcRn Bool
416 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
418 getGlobalRdrEnv :: TcRn GlobalRdrEnv
419 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
421 getImports :: TcRn ImportAvails
422 getImports = do { env <- getGblEnv; return (tcg_imports env) }
424 getFixityEnv :: TcRn FixityEnv
425 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
427 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
428 extendFixityEnv new_bit
429 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
430 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
432 getDefaultTys :: TcRn (Maybe [Type])
433 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
436 %************************************************************************
440 %************************************************************************
443 getSrcSpanM :: TcRn SrcSpan
444 -- Avoid clash with Name.getSrcLoc
445 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
447 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
448 setSrcSpan loc thing_inside
449 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
450 | otherwise = thing_inside -- Don't overwrite useful info with useless
452 addLocM :: (a -> TcM b) -> Located a -> TcM b
453 addLocM fn (L loc a) = setSrcSpan loc $ fn a
455 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
456 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
458 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
459 wrapLocFstM fn (L loc a) =
464 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
465 wrapLocSndM fn (L loc a) =
473 getErrsVar :: TcRn (TcRef Messages)
474 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
476 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
477 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
479 addErr :: Message -> TcRn ()
480 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
482 addLocErr :: Located e -> (e -> Message) -> TcRn ()
483 addLocErr (L loc e) fn = addErrAt loc (fn e)
485 addErrAt :: SrcSpan -> Message -> TcRn ()
486 addErrAt loc msg = addLongErrAt loc msg empty
488 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
489 addLongErrAt loc msg extra
490 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
491 errs_var <- getErrsVar ;
492 rdr_env <- getGlobalRdrEnv ;
493 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
494 (warns, errs) <- readMutVar errs_var ;
495 writeMutVar errs_var (warns, errs `snocBag` err) }
497 addErrs :: [(SrcSpan,Message)] -> TcRn ()
498 addErrs msgs = mappM_ add msgs
500 add (loc,msg) = addErrAt loc msg
502 addReport :: Message -> TcRn ()
503 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
505 addReportAt :: SrcSpan -> Message -> TcRn ()
507 = do { errs_var <- getErrsVar ;
508 rdr_env <- getGlobalRdrEnv ;
509 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
510 (warns, errs) <- readMutVar errs_var ;
511 writeMutVar errs_var (warns `snocBag` warn, errs) }
513 addWarn :: Message -> TcRn ()
514 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
516 addWarnAt :: SrcSpan -> Message -> TcRn ()
517 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
519 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
520 addLocWarn (L loc e) fn = addReportAt loc (fn e)
522 checkErr :: Bool -> Message -> TcRn ()
523 -- Add the error if the bool is False
524 checkErr ok msg = checkM ok (addErr msg)
526 warnIf :: Bool -> Message -> TcRn ()
527 warnIf True msg = addWarn msg
528 warnIf False msg = return ()
530 addMessages :: Messages -> TcRn ()
531 addMessages (m_warns, m_errs)
532 = do { errs_var <- getErrsVar ;
533 (warns, errs) <- readMutVar errs_var ;
534 writeMutVar errs_var (warns `unionBags` m_warns,
535 errs `unionBags` m_errs) }
537 discardWarnings :: TcRn a -> TcRn a
538 -- Ignore warnings inside the thing inside;
539 -- used to ignore-unused-variable warnings inside derived code
540 -- With -dppr-debug, the effects is switched off, so you can still see
541 -- what warnings derived code would give
542 discardWarnings thing_inside
543 | opt_PprStyle_Debug = thing_inside
545 = do { errs_var <- newMutVar emptyMessages
546 ; result <- setErrsVar errs_var thing_inside
547 ; (_warns, errs) <- readMutVar errs_var
548 ; addMessages (emptyBag, errs)
554 try_m :: TcRn r -> TcRn (Either Exception r)
555 -- Does try_m, with a debug-trace on failure
557 = do { mb_r <- tryM thing ;
559 Left exn -> do { traceTc (exn_msg exn); return mb_r }
560 Right r -> return mb_r }
562 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
564 -----------------------
565 recoverM :: TcRn r -- Recovery action; do this if the main one fails
566 -> TcRn r -- Main action: do this first
568 -- Errors in 'thing' are retained
569 recoverM recover thing
570 = do { mb_res <- try_m thing ;
573 Right res -> returnM res }
575 -----------------------
576 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
577 -- (tryTc m) executes m, and returns
578 -- Just r, if m succeeds (returning r)
579 -- Nothing, if m fails
580 -- It also returns all the errors and warnings accumulated by m
581 -- It always succeeds (never raises an exception)
583 = do { errs_var <- newMutVar emptyMessages ;
584 res <- try_m (setErrsVar errs_var m) ;
585 msgs <- readMutVar errs_var ;
586 return (msgs, case res of
588 Right val -> Just val)
589 -- The exception is always the IOEnv built-in
590 -- in exception; see IOEnv.failM
593 -----------------------
594 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
595 -- Run the thing, returning
596 -- Just r, if m succceeds with no error messages
597 -- Nothing, if m fails, or if it succeeds but has error messages
598 -- Either way, the messages are returned; even in the Just case
599 -- there might be warnings
601 = do { (msgs, res) <- tryTc thing
603 ; let errs_found = errorsFound dflags msgs
604 ; return (msgs, case res of
606 Just val | errs_found -> Nothing
607 | otherwise -> Just val)
610 -----------------------
611 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
612 -- Just like tryTcErrs, except that it ensures that the LIE
613 -- for the thing is propagated only if there are no errors
614 -- Hence it's restricted to the type-check monad
615 tryTcLIE thing_inside
616 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
618 Nothing -> return (msgs, Nothing)
619 Just val -> do { extendLIEs lie; return (msgs, Just val) }
622 -----------------------
623 tryTcLIE_ :: TcM r -> TcM r -> TcM r
624 -- (tryTcLIE_ r m) tries m;
625 -- if m succeeds with no error messages, it's the answer
626 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
627 tryTcLIE_ recover main
628 = do { (msgs, mb_res) <- tryTcLIE main
630 Just val -> do { addMessages msgs -- There might be warnings
632 Nothing -> recover -- Discard all msgs
635 -----------------------
636 checkNoErrs :: TcM r -> TcM r
637 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
638 -- If m fails then (checkNoErrsTc m) fails.
639 -- If m succeeds, it checks whether m generated any errors messages
640 -- (it might have recovered internally)
641 -- If so, it fails too.
642 -- Regardless, any errors generated by m are propagated to the enclosing context.
644 = do { (msgs, mb_res) <- tryTcLIE main
648 Just val -> return val
651 ifErrsM :: TcRn r -> TcRn r -> TcRn r
652 -- ifErrsM bale_out main
653 -- does 'bale_out' if there are errors in errors collection
654 -- otherwise does 'main'
655 ifErrsM bale_out normal
656 = do { errs_var <- getErrsVar ;
657 msgs <- readMutVar errs_var ;
659 if errorsFound dflags msgs then
664 failIfErrsM :: TcRn ()
665 -- Useful to avoid error cascades
666 failIfErrsM = ifErrsM failM (return ())
670 %************************************************************************
672 Context management and error message generation
675 %************************************************************************
678 getErrCtxt :: TcM ErrCtxt
679 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
681 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
682 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
684 addErrCtxt :: Message -> TcM a -> TcM a
685 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
687 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
688 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
690 -- Helper function for the above
691 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
692 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
693 env { tcl_ctxt = upd ctxt })
695 -- Conditionally add an error context
696 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
697 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
698 maybeAddErrCtxt Nothing thing_inside = thing_inside
700 popErrCtxt :: TcM a -> TcM a
701 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
703 getInstLoc :: InstOrigin -> TcM InstLoc
705 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
706 return (InstLoc origin loc (tcl_ctxt env)) }
708 addInstCtxt :: InstLoc -> TcM a -> TcM a
709 -- Add the SrcSpan and context from the first Inst in the list
710 -- (they all have similar locations)
711 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
712 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
715 The addErrTc functions add an error message, but do not cause failure.
716 The 'M' variants pass a TidyEnv that has already been used to
717 tidy up the message; we then use it to tidy the context messages
720 addErrTc :: Message -> TcM ()
721 addErrTc err_msg = do { env0 <- tcInitTidyEnv
722 ; addErrTcM (env0, err_msg) }
724 addErrsTc :: [Message] -> TcM ()
725 addErrsTc err_msgs = mappM_ addErrTc err_msgs
727 addErrTcM :: (TidyEnv, Message) -> TcM ()
728 addErrTcM (tidy_env, err_msg)
729 = do { ctxt <- getErrCtxt ;
731 add_err_tcm tidy_env err_msg loc ctxt }
734 The failWith functions add an error message and cause failure
737 failWithTc :: Message -> TcM a -- Add an error message and fail
739 = addErrTc err_msg >> failM
741 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
742 failWithTcM local_and_msg
743 = addErrTcM local_and_msg >> failM
745 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
746 checkTc True err = returnM ()
747 checkTc False err = failWithTc err
750 Warnings have no 'M' variant, nor failure
753 addWarnTc :: Message -> TcM ()
755 = do { ctxt <- getErrCtxt ;
756 env0 <- tcInitTidyEnv ;
757 ctxt_msgs <- do_ctxt env0 ctxt ;
758 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
760 warnTc :: Bool -> Message -> TcM ()
761 warnTc warn_if_true warn_msg
762 | warn_if_true = addWarnTc warn_msg
763 | otherwise = return ()
766 -----------------------------------
769 We initialise the "tidy-env", used for tidying types before printing,
770 by building a reverse map from the in-scope type variables to the
771 OccName that the programmer originally used for them
774 tcInitTidyEnv :: TcM TidyEnv
776 = do { lcl_env <- getLclEnv
777 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
778 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
780 ; return (foldl add emptyTidyEnv nm_tv_prs) }
782 add (env,subst) (name, tyvar)
783 = case tidyOccName env (nameOccName name) of
784 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
786 tyvar' = setTyVarName tyvar name'
787 name' = tidyNameOcc name occ'
790 -----------------------------------
791 Other helper functions
794 add_err_tcm tidy_env err_msg loc ctxt
795 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
796 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
800 do_ctxt tidy_env (c:cs)
801 = do { (tidy_env', m) <- c tidy_env ;
802 ms <- do_ctxt tidy_env' cs ;
805 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
806 | otherwise = take 3 ctxt
809 debugTc is useful for monadic debugging code
812 debugTc :: TcM () -> TcM ()
814 debugTc thing = thing
816 debugTc thing = return ()
820 %************************************************************************
822 Type constraints (the so-called LIE)
824 %************************************************************************
827 nextDFunIndex :: TcM Int -- Get the next dfun index
828 nextDFunIndex = do { env <- getGblEnv
829 ; let dfun_n_var = tcg_dfun_n env
830 ; n <- readMutVar dfun_n_var
831 ; writeMutVar dfun_n_var (n+1)
834 getLIEVar :: TcM (TcRef LIE)
835 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
837 setLIEVar :: TcRef LIE -> TcM a -> TcM a
838 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
840 getLIE :: TcM a -> TcM (a, [Inst])
841 -- (getLIE m) runs m, and returns the type constraints it generates
843 = do { lie_var <- newMutVar emptyLIE ;
844 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
846 lie <- readMutVar lie_var ;
847 return (res, lieToList lie) }
849 extendLIE :: Inst -> TcM ()
851 = do { lie_var <- getLIEVar ;
852 lie <- readMutVar lie_var ;
853 writeMutVar lie_var (inst `consLIE` lie) }
855 extendLIEs :: [Inst] -> TcM ()
859 = do { lie_var <- getLIEVar ;
860 lie <- readMutVar lie_var ;
861 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
865 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
866 -- Set the local type envt, but do *not* disturb other fields,
867 -- notably the lie_var
868 setLclTypeEnv lcl_env thing_inside
869 = updLclEnv upd thing_inside
871 upd env = env { tcl_env = tcl_env lcl_env,
872 tcl_tyvars = tcl_tyvars lcl_env }
876 %************************************************************************
878 Template Haskell context
880 %************************************************************************
883 recordThUse :: TcM ()
884 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
886 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
887 keepAliveTc n = do { env <- getGblEnv;
888 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
890 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
891 keepAliveSetTc ns = do { env <- getGblEnv;
892 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
894 getStage :: TcM ThStage
895 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
897 setStage :: ThStage -> TcM a -> TcM a
898 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
902 %************************************************************************
904 Stuff for the renamer's local env
906 %************************************************************************
909 getLocalRdrEnv :: RnM LocalRdrEnv
910 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
912 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
913 setLocalRdrEnv rdr_env thing_inside
914 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
918 %************************************************************************
920 Stuff for interface decls
922 %************************************************************************
925 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
926 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
928 if_tv_env = emptyOccEnv,
929 if_id_env = emptyOccEnv }
931 initIfaceTcRn :: IfG a -> TcRn a
932 initIfaceTcRn thing_inside
933 = do { tcg_env <- getGblEnv
934 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
935 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
936 ; setEnvs (if_env, ()) thing_inside }
938 initIfaceExtCore :: IfL a -> TcRn a
939 initIfaceExtCore thing_inside
940 = do { tcg_env <- getGblEnv
941 ; let { mod = tcg_mod tcg_env
942 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
943 ; if_env = IfGblEnv {
944 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
945 ; if_lenv = mkIfLclEnv mod doc
947 ; setEnvs (if_env, if_lenv) thing_inside }
949 initIfaceCheck :: HscEnv -> IfG a -> IO a
950 -- Used when checking the up-to-date-ness of the old Iface
951 -- Initialise the environment with no useful info at all
952 initIfaceCheck hsc_env do_this
953 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
954 ; initTcRnIf 'i' hsc_env gbl_env () do_this
957 initIfaceTc :: ModIface
958 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
959 -- Used when type-checking checking an up-to-date interface file
960 -- No type envt from the current module, but we do know the module dependencies
961 initIfaceTc iface do_this
962 = do { tc_env_var <- newMutVar emptyTypeEnv
963 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
964 ; if_lenv = mkIfLclEnv mod doc
966 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
969 mod = mi_module iface
970 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
972 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
973 -- Used when sucking in new Rules in SimplCore
974 -- We have available the type envt of the module being compiled, and we must use it
975 initIfaceRules hsc_env guts do_this
977 type_info = (mg_module guts, return (mg_types guts))
978 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
981 -- Run the thing; any exceptions just bubble out from here
982 ; initTcRnIf 'i' hsc_env gbl_env () do_this
985 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
986 initIfaceLcl mod loc_doc thing_inside
987 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
989 getIfModule :: IfL Module
990 getIfModule = do { env <- getLclEnv; return (if_mod env) }
993 failIfM :: Message -> IfL a
994 -- The Iface monad doesn't have a place to accumulate errors, so we
995 -- just fall over fast if one happens; it "shouldnt happen".
996 -- We use IfL here so that we can get context info out of the local env
998 = do { env <- getLclEnv
999 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1000 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
1003 --------------------
1004 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1005 -- Run thing_inside in an interleaved thread.
1006 -- It shares everything with the parent thread, so this is DANGEROUS.
1008 -- It returns Nothing if the computation fails
1010 -- It's used for lazily type-checking interface
1011 -- signatures, which is pretty benign
1013 forkM_maybe doc thing_inside
1014 = do { unsafeInterleaveM $
1015 do { traceIf (text "Starting fork {" <+> doc)
1017 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1020 Right r -> do { traceIf (text "} ending fork" <+> doc)
1024 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1025 -- Otherwise we silently discard errors. Errors can legitimately
1026 -- happen when compiling interface signatures (see tcInterfaceSigs)
1027 ifOptM Opt_D_dump_if_trace
1028 (print_errs (hang (text "forkM failed:" <+> doc)
1029 4 (text (show exn))))
1031 ; traceIf (text "} ending fork (badly)" <+> doc)
1035 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1037 forkM :: SDoc -> IfL a -> IfL a
1038 forkM doc thing_inside
1039 = do { mb_res <- forkM_maybe doc thing_inside
1040 ; return (case mb_res of
1041 Nothing -> pgmError "Cannot continue after interface file error"
1042 -- pprPanic "forkM" doc