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 )
38 import FamInstEnv ( emptyFamInstEnv )
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 SrcLoc ( mkGeneralSrcSpan, isGoodSrcSpan, SrcSpan, Located(..) )
47 import NameEnv ( emptyNameEnv )
48 import NameSet ( NameSet, emptyDUs, emptyNameSet, unionNameSets, addOneToNameSet )
49 import OccName ( emptyOccEnv, tidyOccName )
50 import Bag ( emptyBag )
52 import UniqSupply ( UniqSupply, mkSplitUniqSupply, uniqFromSupply, splitUniqSupply )
53 import UniqFM ( unitUFM )
54 import Unique ( Unique )
55 import DynFlags ( DynFlags(..), DynFlag(..), dopt, dopt_set,
57 import StaticFlags ( opt_PprStyle_Debug )
58 import Bag ( snocBag, unionBags )
59 import Panic ( showException )
62 import DATA_IOREF ( newIORef, readIORef )
63 import EXCEPTION ( Exception )
68 %************************************************************************
72 %************************************************************************
75 ioToTcRn :: IO r -> TcRn r
84 -> IO (Messages, Maybe r)
85 -- Nothing => error thrown by the thing inside
86 -- (error messages should have been printed already)
88 initTc hsc_env hsc_src mod do_this
89 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
90 tvs_var <- newIORef emptyVarSet ;
91 type_env_var <- newIORef emptyNameEnv ;
92 dfuns_var <- newIORef emptyNameSet ;
93 keep_var <- newIORef emptyNameSet ;
94 th_var <- newIORef False ;
95 dfun_n_var <- newIORef 1 ;
100 tcg_rdr_env = hsc_global_rdr_env hsc_env,
101 tcg_fix_env = emptyNameEnv,
102 tcg_default = Nothing,
103 tcg_type_env = hsc_global_type_env hsc_env,
104 tcg_type_env_var = type_env_var,
105 tcg_inst_env = emptyInstEnv,
106 tcg_fam_inst_env = emptyFamInstEnv,
107 tcg_inst_uses = dfuns_var,
108 tcg_th_used = th_var,
109 tcg_exports = emptyNameSet,
110 tcg_imports = init_imports,
112 tcg_rn_imports = Nothing,
113 tcg_rn_exports = Nothing,
114 tcg_rn_decls = Nothing,
115 tcg_binds = emptyLHsBinds,
116 tcg_deprecs = NoDeprecs,
120 tcg_dfun_n = dfun_n_var,
125 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
127 tcl_rdr = emptyLocalRdrEnv,
128 tcl_th_ctxt = topStage,
129 tcl_arrow_ctxt = NoArrowCtxt,
130 tcl_env = emptyNameEnv,
131 tcl_tyvars = tvs_var,
132 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
136 -- OK, here's the business end!
137 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
138 addBreakpointBindings $
139 do { r <- tryM do_this
141 Right res -> return (Just res)
142 Left _ -> return Nothing } ;
144 -- Collect any error messages
145 msgs <- readIORef errs_var ;
147 let { dflags = hsc_dflags hsc_env
148 ; final_res | errorsFound dflags msgs = Nothing
149 | otherwise = maybe_res } ;
151 return (msgs, final_res)
154 init_imports = emptyImportAvails {imp_env =
155 unitUFM (moduleName mod) emptyNameSet}
156 -- Initialise tcg_imports with an empty set of bindings for
157 -- this module, so that if we see 'module M' in the export
158 -- list, and there are no bindings in M, we don't bleat
159 -- "unknown module M".
161 initTcPrintErrors -- Used from the interactive loop only
166 initTcPrintErrors env mod todo = do
167 (msgs, res) <- initTc env HsSrcFile mod todo
168 printErrorsAndWarnings (hsc_dflags env) msgs
173 addBreakpointBindings :: TcM a -> TcM a
174 addBreakpointBindings thing_inside
175 #if defined(GHCI) && defined(BREAKPOINT)
176 = do { unique <- newUnique
177 ; let { var = mkInternalName unique (mkOccName tvName "a") noSrcLoc;
178 tyvar = mkTyVar var liftedTypeKind;
179 basicType extra = (FunTy intTy
180 (FunTy (mkListTy unitTy)
184 (FunTy (TyVarTy tyvar)
185 (TyVarTy tyvar)))))));
187 = mkGlobalId VanillaGlobal breakpointJumpName
188 (basicType id) vanillaIdInfo;
190 = mkGlobalId VanillaGlobal breakpointCondJumpName
191 (basicType (FunTy boolTy)) vanillaIdInfo
193 ; tcExtendIdEnv [breakpointJumpId, breakpointCondJumpId] thing_inside}
199 %************************************************************************
203 %************************************************************************
207 initTcRnIf :: Char -- Tag for unique supply
212 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
213 = do { us <- mkSplitUniqSupply uniq_tag ;
214 ; us_var <- newIORef us ;
216 ; let { env = Env { env_top = hsc_env,
219 env_lcl = lcl_env } }
221 ; runIOEnv env thing_inside
225 %************************************************************************
229 %************************************************************************
232 getTopEnv :: TcRnIf gbl lcl HscEnv
233 getTopEnv = do { env <- getEnv; return (env_top env) }
235 getGblEnv :: TcRnIf gbl lcl gbl
236 getGblEnv = do { env <- getEnv; return (env_gbl env) }
238 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
239 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
240 env { env_gbl = upd gbl })
242 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
243 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
245 getLclEnv :: TcRnIf gbl lcl lcl
246 getLclEnv = do { env <- getEnv; return (env_lcl env) }
248 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
249 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
250 env { env_lcl = upd lcl })
252 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
253 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
255 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
256 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
258 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
259 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
266 getDOpts :: TcRnIf gbl lcl DynFlags
267 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
269 doptM :: DynFlag -> TcRnIf gbl lcl Bool
270 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
272 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
273 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
274 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
276 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
277 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
278 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
280 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
281 ifOptM flag thing_inside = do { b <- doptM flag;
282 if b then thing_inside else return () }
284 getGhcMode :: TcRnIf gbl lcl GhcMode
285 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
289 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
290 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
292 getEps :: TcRnIf gbl lcl ExternalPackageState
293 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
295 -- Updating the EPS. This should be an atomic operation.
296 -- Note the delicate 'seq' which forces the EPS before putting it in the
297 -- variable. Otherwise what happens is that we get
298 -- write eps_var (....(unsafeRead eps_var)....)
299 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
300 -- we make the unsafeRead happen before we update the variable.
302 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
304 updateEps upd_fn = do { traceIf (text "updating EPS")
305 ; eps_var <- getEpsVar
306 ; eps <- readMutVar eps_var
307 ; let { (eps', val) = upd_fn eps }
308 ; seq eps' (writeMutVar eps_var eps')
311 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
313 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
314 ; eps_var <- getEpsVar
315 ; eps <- readMutVar eps_var
316 ; let { eps' = upd_fn eps }
317 ; seq eps' (writeMutVar eps_var eps') }
319 getHpt :: TcRnIf gbl lcl HomePackageTable
320 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
322 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
323 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
324 ; return (eps, hsc_HPT env) }
327 %************************************************************************
331 %************************************************************************
334 newUnique :: TcRnIf gbl lcl Unique
336 = do { env <- getEnv ;
337 let { u_var = env_us env } ;
338 us <- readMutVar u_var ;
339 case splitUniqSupply us of { (us1,_) -> do {
340 writeMutVar u_var us1 ;
341 return $! uniqFromSupply us }}}
342 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
343 -- a chain of unevaluated supplies behind.
344 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
345 -- throw away one half of the new split supply. This is safe because this
346 -- is the only place we use that unique. Using the other half of the split
347 -- supply is safer, but slower.
349 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
351 = do { env <- getEnv ;
352 let { u_var = env_us env } ;
353 us <- readMutVar u_var ;
354 case splitUniqSupply us of { (us1,us2) -> do {
355 writeMutVar u_var us1 ;
358 newLocalName :: Name -> TcRnIf gbl lcl Name
359 newLocalName name -- Make a clone
360 = newUnique `thenM` \ uniq ->
361 returnM (mkInternalName uniq (nameOccName name) (getSrcLoc name))
365 %************************************************************************
369 %************************************************************************
372 traceTc, traceRn :: SDoc -> TcRn ()
373 traceRn = traceOptTcRn Opt_D_dump_rn_trace
374 traceTc = traceOptTcRn Opt_D_dump_tc_trace
375 traceSplice = traceOptTcRn Opt_D_dump_splices
378 traceIf :: SDoc -> TcRnIf m n ()
379 traceIf = traceOptIf Opt_D_dump_if_trace
380 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
383 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
384 traceOptIf flag doc = ifOptM flag $
385 ioToIOEnv (printForUser stderr alwaysQualify doc)
387 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
388 traceOptTcRn flag doc = ifOptM flag $ do
391 ; env0 <- tcInitTidyEnv
392 ; ctxt_msgs <- do_ctxt env0 ctxt
393 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
394 ; dumpTcRn real_doc }
396 dumpTcRn :: SDoc -> TcRn ()
397 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
398 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
400 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
401 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
405 %************************************************************************
407 Typechecker global environment
409 %************************************************************************
412 getModule :: TcRn Module
413 getModule = do { env <- getGblEnv; return (tcg_mod env) }
415 setModule :: Module -> TcRn a -> TcRn a
416 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
418 tcIsHsBoot :: TcRn Bool
419 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
421 getGlobalRdrEnv :: TcRn GlobalRdrEnv
422 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
424 getImports :: TcRn ImportAvails
425 getImports = do { env <- getGblEnv; return (tcg_imports env) }
427 getFixityEnv :: TcRn FixityEnv
428 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
430 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
431 extendFixityEnv new_bit
432 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
433 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
435 getDefaultTys :: TcRn (Maybe [Type])
436 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
439 %************************************************************************
443 %************************************************************************
446 getSrcSpanM :: TcRn SrcSpan
447 -- Avoid clash with Name.getSrcLoc
448 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
450 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
451 setSrcSpan loc thing_inside
452 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
453 | otherwise = thing_inside -- Don't overwrite useful info with useless
455 addLocM :: (a -> TcM b) -> Located a -> TcM b
456 addLocM fn (L loc a) = setSrcSpan loc $ fn a
458 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
459 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
461 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
462 wrapLocFstM fn (L loc a) =
467 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
468 wrapLocSndM fn (L loc a) =
476 getErrsVar :: TcRn (TcRef Messages)
477 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
479 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
480 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
482 addErr :: Message -> TcRn ()
483 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
485 addLocErr :: Located e -> (e -> Message) -> TcRn ()
486 addLocErr (L loc e) fn = addErrAt loc (fn e)
488 addErrAt :: SrcSpan -> Message -> TcRn ()
489 addErrAt loc msg = addLongErrAt loc msg empty
491 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
492 addLongErrAt loc msg extra
493 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
494 errs_var <- getErrsVar ;
495 rdr_env <- getGlobalRdrEnv ;
496 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
497 (warns, errs) <- readMutVar errs_var ;
498 writeMutVar errs_var (warns, errs `snocBag` err) }
500 addErrs :: [(SrcSpan,Message)] -> TcRn ()
501 addErrs msgs = mappM_ add msgs
503 add (loc,msg) = addErrAt loc msg
505 addReport :: Message -> TcRn ()
506 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
508 addReportAt :: SrcSpan -> Message -> TcRn ()
510 = do { errs_var <- getErrsVar ;
511 rdr_env <- getGlobalRdrEnv ;
512 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
513 (warns, errs) <- readMutVar errs_var ;
514 writeMutVar errs_var (warns `snocBag` warn, errs) }
516 addWarn :: Message -> TcRn ()
517 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
519 addWarnAt :: SrcSpan -> Message -> TcRn ()
520 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
522 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
523 addLocWarn (L loc e) fn = addReportAt loc (fn e)
525 checkErr :: Bool -> Message -> TcRn ()
526 -- Add the error if the bool is False
527 checkErr ok msg = checkM ok (addErr msg)
529 warnIf :: Bool -> Message -> TcRn ()
530 warnIf True msg = addWarn msg
531 warnIf False msg = return ()
533 addMessages :: Messages -> TcRn ()
534 addMessages (m_warns, m_errs)
535 = do { errs_var <- getErrsVar ;
536 (warns, errs) <- readMutVar errs_var ;
537 writeMutVar errs_var (warns `unionBags` m_warns,
538 errs `unionBags` m_errs) }
540 discardWarnings :: TcRn a -> TcRn a
541 -- Ignore warnings inside the thing inside;
542 -- used to ignore-unused-variable warnings inside derived code
543 -- With -dppr-debug, the effects is switched off, so you can still see
544 -- what warnings derived code would give
545 discardWarnings thing_inside
546 | opt_PprStyle_Debug = thing_inside
548 = do { errs_var <- newMutVar emptyMessages
549 ; result <- setErrsVar errs_var thing_inside
550 ; (_warns, errs) <- readMutVar errs_var
551 ; addMessages (emptyBag, errs)
557 try_m :: TcRn r -> TcRn (Either Exception r)
558 -- Does try_m, with a debug-trace on failure
560 = do { mb_r <- tryM thing ;
562 Left exn -> do { traceTc (exn_msg exn); return mb_r }
563 Right r -> return mb_r }
565 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
567 -----------------------
568 recoverM :: TcRn r -- Recovery action; do this if the main one fails
569 -> TcRn r -- Main action: do this first
571 -- Errors in 'thing' are retained
572 recoverM recover thing
573 = do { mb_res <- try_m thing ;
576 Right res -> returnM res }
578 -----------------------
579 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
580 -- (tryTc m) executes m, and returns
581 -- Just r, if m succeeds (returning r)
582 -- Nothing, if m fails
583 -- It also returns all the errors and warnings accumulated by m
584 -- It always succeeds (never raises an exception)
586 = do { errs_var <- newMutVar emptyMessages ;
587 res <- try_m (setErrsVar errs_var m) ;
588 msgs <- readMutVar errs_var ;
589 return (msgs, case res of
591 Right val -> Just val)
592 -- The exception is always the IOEnv built-in
593 -- in exception; see IOEnv.failM
596 -----------------------
597 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
598 -- Run the thing, returning
599 -- Just r, if m succceeds with no error messages
600 -- Nothing, if m fails, or if it succeeds but has error messages
601 -- Either way, the messages are returned; even in the Just case
602 -- there might be warnings
604 = do { (msgs, res) <- tryTc thing
606 ; let errs_found = errorsFound dflags msgs
607 ; return (msgs, case res of
609 Just val | errs_found -> Nothing
610 | otherwise -> Just val)
613 -----------------------
614 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
615 -- Just like tryTcErrs, except that it ensures that the LIE
616 -- for the thing is propagated only if there are no errors
617 -- Hence it's restricted to the type-check monad
618 tryTcLIE thing_inside
619 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
621 Nothing -> return (msgs, Nothing)
622 Just val -> do { extendLIEs lie; return (msgs, Just val) }
625 -----------------------
626 tryTcLIE_ :: TcM r -> TcM r -> TcM r
627 -- (tryTcLIE_ r m) tries m;
628 -- if m succeeds with no error messages, it's the answer
629 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
630 tryTcLIE_ recover main
631 = do { (msgs, mb_res) <- tryTcLIE main
633 Just val -> do { addMessages msgs -- There might be warnings
635 Nothing -> recover -- Discard all msgs
638 -----------------------
639 checkNoErrs :: TcM r -> TcM r
640 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
641 -- If m fails then (checkNoErrsTc m) fails.
642 -- If m succeeds, it checks whether m generated any errors messages
643 -- (it might have recovered internally)
644 -- If so, it fails too.
645 -- Regardless, any errors generated by m are propagated to the enclosing context.
647 = do { (msgs, mb_res) <- tryTcLIE main
651 Just val -> return val
654 ifErrsM :: TcRn r -> TcRn r -> TcRn r
655 -- ifErrsM bale_out main
656 -- does 'bale_out' if there are errors in errors collection
657 -- otherwise does 'main'
658 ifErrsM bale_out normal
659 = do { errs_var <- getErrsVar ;
660 msgs <- readMutVar errs_var ;
662 if errorsFound dflags msgs then
667 failIfErrsM :: TcRn ()
668 -- Useful to avoid error cascades
669 failIfErrsM = ifErrsM failM (return ())
673 %************************************************************************
675 Context management and error message generation
678 %************************************************************************
681 getErrCtxt :: TcM ErrCtxt
682 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
684 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
685 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
687 addErrCtxt :: Message -> TcM a -> TcM a
688 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
690 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
691 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
693 -- Helper function for the above
694 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
695 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
696 env { tcl_ctxt = upd ctxt })
698 -- Conditionally add an error context
699 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
700 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
701 maybeAddErrCtxt Nothing thing_inside = thing_inside
703 popErrCtxt :: TcM a -> TcM a
704 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
706 getInstLoc :: InstOrigin -> TcM InstLoc
708 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
709 return (InstLoc origin loc (tcl_ctxt env)) }
711 addInstCtxt :: InstLoc -> TcM a -> TcM a
712 -- Add the SrcSpan and context from the first Inst in the list
713 -- (they all have similar locations)
714 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
715 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
718 The addErrTc functions add an error message, but do not cause failure.
719 The 'M' variants pass a TidyEnv that has already been used to
720 tidy up the message; we then use it to tidy the context messages
723 addErrTc :: Message -> TcM ()
724 addErrTc err_msg = do { env0 <- tcInitTidyEnv
725 ; addErrTcM (env0, err_msg) }
727 addErrsTc :: [Message] -> TcM ()
728 addErrsTc err_msgs = mappM_ addErrTc err_msgs
730 addErrTcM :: (TidyEnv, Message) -> TcM ()
731 addErrTcM (tidy_env, err_msg)
732 = do { ctxt <- getErrCtxt ;
734 add_err_tcm tidy_env err_msg loc ctxt }
737 The failWith functions add an error message and cause failure
740 failWithTc :: Message -> TcM a -- Add an error message and fail
742 = addErrTc err_msg >> failM
744 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
745 failWithTcM local_and_msg
746 = addErrTcM local_and_msg >> failM
748 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
749 checkTc True err = returnM ()
750 checkTc False err = failWithTc err
753 Warnings have no 'M' variant, nor failure
756 addWarnTc :: Message -> TcM ()
758 = do { ctxt <- getErrCtxt ;
759 env0 <- tcInitTidyEnv ;
760 ctxt_msgs <- do_ctxt env0 ctxt ;
761 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
763 warnTc :: Bool -> Message -> TcM ()
764 warnTc warn_if_true warn_msg
765 | warn_if_true = addWarnTc warn_msg
766 | otherwise = return ()
769 -----------------------------------
772 We initialise the "tidy-env", used for tidying types before printing,
773 by building a reverse map from the in-scope type variables to the
774 OccName that the programmer originally used for them
777 tcInitTidyEnv :: TcM TidyEnv
779 = do { lcl_env <- getLclEnv
780 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
781 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
783 ; return (foldl add emptyTidyEnv nm_tv_prs) }
785 add (env,subst) (name, tyvar)
786 = case tidyOccName env (nameOccName name) of
787 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
789 tyvar' = setTyVarName tyvar name'
790 name' = tidyNameOcc name occ'
793 -----------------------------------
794 Other helper functions
797 add_err_tcm tidy_env err_msg loc ctxt
798 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
799 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
803 do_ctxt tidy_env (c:cs)
804 = do { (tidy_env', m) <- c tidy_env ;
805 ms <- do_ctxt tidy_env' cs ;
808 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
809 | otherwise = take 3 ctxt
812 debugTc is useful for monadic debugging code
815 debugTc :: TcM () -> TcM ()
817 debugTc thing = thing
819 debugTc thing = return ()
823 %************************************************************************
825 Type constraints (the so-called LIE)
827 %************************************************************************
830 nextDFunIndex :: TcM Int -- Get the next dfun index
831 nextDFunIndex = do { env <- getGblEnv
832 ; let dfun_n_var = tcg_dfun_n env
833 ; n <- readMutVar dfun_n_var
834 ; writeMutVar dfun_n_var (n+1)
837 getLIEVar :: TcM (TcRef LIE)
838 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
840 setLIEVar :: TcRef LIE -> TcM a -> TcM a
841 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
843 getLIE :: TcM a -> TcM (a, [Inst])
844 -- (getLIE m) runs m, and returns the type constraints it generates
846 = do { lie_var <- newMutVar emptyLIE ;
847 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
849 lie <- readMutVar lie_var ;
850 return (res, lieToList lie) }
852 extendLIE :: Inst -> TcM ()
854 = do { lie_var <- getLIEVar ;
855 lie <- readMutVar lie_var ;
856 writeMutVar lie_var (inst `consLIE` lie) }
858 extendLIEs :: [Inst] -> TcM ()
862 = do { lie_var <- getLIEVar ;
863 lie <- readMutVar lie_var ;
864 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
868 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
869 -- Set the local type envt, but do *not* disturb other fields,
870 -- notably the lie_var
871 setLclTypeEnv lcl_env thing_inside
872 = updLclEnv upd thing_inside
874 upd env = env { tcl_env = tcl_env lcl_env,
875 tcl_tyvars = tcl_tyvars lcl_env }
879 %************************************************************************
881 Template Haskell context
883 %************************************************************************
886 recordThUse :: TcM ()
887 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
889 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
890 keepAliveTc n = do { env <- getGblEnv;
891 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
893 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
894 keepAliveSetTc ns = do { env <- getGblEnv;
895 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
897 getStage :: TcM ThStage
898 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
900 setStage :: ThStage -> TcM a -> TcM a
901 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
905 %************************************************************************
907 Stuff for the renamer's local env
909 %************************************************************************
912 getLocalRdrEnv :: RnM LocalRdrEnv
913 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
915 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
916 setLocalRdrEnv rdr_env thing_inside
917 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
921 %************************************************************************
923 Stuff for interface decls
925 %************************************************************************
928 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
929 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
931 if_tv_env = emptyOccEnv,
932 if_id_env = emptyOccEnv }
934 initIfaceTcRn :: IfG a -> TcRn a
935 initIfaceTcRn thing_inside
936 = do { tcg_env <- getGblEnv
937 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
938 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
939 ; setEnvs (if_env, ()) thing_inside }
941 initIfaceExtCore :: IfL a -> TcRn a
942 initIfaceExtCore thing_inside
943 = do { tcg_env <- getGblEnv
944 ; let { mod = tcg_mod tcg_env
945 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
946 ; if_env = IfGblEnv {
947 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
948 ; if_lenv = mkIfLclEnv mod doc
950 ; setEnvs (if_env, if_lenv) thing_inside }
952 initIfaceCheck :: HscEnv -> IfG a -> IO a
953 -- Used when checking the up-to-date-ness of the old Iface
954 -- Initialise the environment with no useful info at all
955 initIfaceCheck hsc_env do_this
956 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
957 ; initTcRnIf 'i' hsc_env gbl_env () do_this
960 initIfaceTc :: ModIface
961 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
962 -- Used when type-checking checking an up-to-date interface file
963 -- No type envt from the current module, but we do know the module dependencies
964 initIfaceTc iface do_this
965 = do { tc_env_var <- newMutVar emptyTypeEnv
966 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
967 ; if_lenv = mkIfLclEnv mod doc
969 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
972 mod = mi_module iface
973 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
975 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
976 -- Used when sucking in new Rules in SimplCore
977 -- We have available the type envt of the module being compiled, and we must use it
978 initIfaceRules hsc_env guts do_this
980 type_info = (mg_module guts, return (mg_types guts))
981 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
984 -- Run the thing; any exceptions just bubble out from here
985 ; initTcRnIf 'i' hsc_env gbl_env () do_this
988 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
989 initIfaceLcl mod loc_doc thing_inside
990 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
992 getIfModule :: IfL Module
993 getIfModule = do { env <- getLclEnv; return (if_mod env) }
996 failIfM :: Message -> IfL a
997 -- The Iface monad doesn't have a place to accumulate errors, so we
998 -- just fall over fast if one happens; it "shouldnt happen".
999 -- We use IfL here so that we can get context info out of the local env
1001 = do { env <- getLclEnv
1002 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1003 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
1006 --------------------
1007 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1008 -- Run thing_inside in an interleaved thread.
1009 -- It shares everything with the parent thread, so this is DANGEROUS.
1011 -- It returns Nothing if the computation fails
1013 -- It's used for lazily type-checking interface
1014 -- signatures, which is pretty benign
1016 forkM_maybe doc thing_inside
1017 = do { unsafeInterleaveM $
1018 do { traceIf (text "Starting fork {" <+> doc)
1020 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1023 Right r -> do { traceIf (text "} ending fork" <+> doc)
1027 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1028 -- Otherwise we silently discard errors. Errors can legitimately
1029 -- happen when compiling interface signatures (see tcInterfaceSigs)
1030 ifOptM Opt_D_dump_if_trace
1031 (print_errs (hang (text "forkM failed:" <+> doc)
1032 4 (text (show exn))))
1034 ; traceIf (text "} ending fork (badly)" <+> doc)
1038 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1040 forkM :: SDoc -> IfL a -> IfL a
1041 forkM doc thing_inside
1042 = do { mb_res <- forkM_maybe doc thing_inside
1043 ; return (case mb_res of
1044 Nothing -> pgmError "Cannot continue after interface file error"
1045 -- pprPanic "forkM" doc