2 % (c) The University of Glasgow 2006
12 #include "HsVersions.h"
14 import TcRnTypes -- Re-export all
15 import IOEnv -- Re-export all
22 import {-#SOURCE#-} TcEnv
25 import HsSyn hiding (LIE)
54 import Control.Exception
59 %************************************************************************
63 %************************************************************************
66 ioToTcRn :: IO r -> TcRn r
76 -> IO (Messages, Maybe r)
77 -- Nothing => error thrown by the thing inside
78 -- (error messages should have been printed already)
80 initTc hsc_env hsc_src mod do_this
81 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
82 tvs_var <- newIORef emptyVarSet ;
83 type_env_var <- newIORef emptyNameEnv ;
84 dfuns_var <- newIORef emptyNameSet ;
85 keep_var <- newIORef emptyNameSet ;
86 th_var <- newIORef False ;
87 dfun_n_var <- newIORef 1 ;
92 tcg_rdr_env = hsc_global_rdr_env hsc_env,
93 tcg_fix_env = emptyNameEnv,
94 tcg_default = Nothing,
95 tcg_type_env = hsc_global_type_env hsc_env,
96 tcg_type_env_var = type_env_var,
97 tcg_inst_env = emptyInstEnv,
98 tcg_fam_inst_env = emptyFamInstEnv,
99 tcg_inst_uses = dfuns_var,
100 tcg_th_used = th_var,
102 tcg_imports = emptyImportAvails,
104 tcg_rn_imports = Nothing,
105 tcg_rn_exports = Nothing,
106 tcg_rn_decls = Nothing,
107 tcg_binds = emptyLHsBinds,
108 tcg_deprecs = NoDeprecs,
113 tcg_dfun_n = dfun_n_var,
116 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing
120 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
122 tcl_rdr = emptyLocalRdrEnv,
123 tcl_th_ctxt = topStage,
124 tcl_arrow_ctxt = NoArrowCtxt,
125 tcl_env = emptyNameEnv,
126 tcl_tyvars = tvs_var,
127 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
131 -- OK, here's the business end!
132 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
133 addBreakpointBindings $
134 do { r <- tryM do_this
136 Right res -> return (Just res)
137 Left _ -> return Nothing } ;
139 -- Collect any error messages
140 msgs <- readIORef errs_var ;
142 let { dflags = hsc_dflags hsc_env
143 ; final_res | errorsFound dflags msgs = Nothing
144 | otherwise = maybe_res } ;
146 return (msgs, final_res)
149 initTcPrintErrors -- Used from the interactive loop only
154 initTcPrintErrors env mod todo = do
155 (msgs, res) <- initTc env HsSrcFile mod todo
156 printErrorsAndWarnings (hsc_dflags env) msgs
161 addBreakpointBindings :: TcM a -> TcM a
162 addBreakpointBindings thing_inside
167 %************************************************************************
171 %************************************************************************
175 initTcRnIf :: Char -- Tag for unique supply
180 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
181 = do { us <- mkSplitUniqSupply uniq_tag ;
182 ; us_var <- newIORef us ;
184 ; let { env = Env { env_top = hsc_env,
187 env_lcl = lcl_env } }
189 ; runIOEnv env thing_inside
193 %************************************************************************
197 %************************************************************************
200 getTopEnv :: TcRnIf gbl lcl HscEnv
201 getTopEnv = do { env <- getEnv; return (env_top env) }
203 getGblEnv :: TcRnIf gbl lcl gbl
204 getGblEnv = do { env <- getEnv; return (env_gbl env) }
206 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
207 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
208 env { env_gbl = upd gbl })
210 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
211 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
213 getLclEnv :: TcRnIf gbl lcl lcl
214 getLclEnv = do { env <- getEnv; return (env_lcl env) }
216 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
217 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
218 env { env_lcl = upd lcl })
220 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
221 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
223 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
224 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
226 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
227 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
234 getDOpts :: TcRnIf gbl lcl DynFlags
235 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
237 doptM :: DynFlag -> TcRnIf gbl lcl Bool
238 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
240 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
241 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
242 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
244 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
245 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
246 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
248 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
249 ifOptM flag thing_inside = do { b <- doptM flag;
250 if b then thing_inside else return () }
252 getGhcMode :: TcRnIf gbl lcl GhcMode
253 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
257 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
258 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
260 getEps :: TcRnIf gbl lcl ExternalPackageState
261 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
263 -- Updating the EPS. This should be an atomic operation.
264 -- Note the delicate 'seq' which forces the EPS before putting it in the
265 -- variable. Otherwise what happens is that we get
266 -- write eps_var (....(unsafeRead eps_var)....)
267 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
268 -- we make the unsafeRead happen before we update the variable.
270 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
272 updateEps upd_fn = do { traceIf (text "updating EPS")
273 ; eps_var <- getEpsVar
274 ; eps <- readMutVar eps_var
275 ; let { (eps', val) = upd_fn eps }
276 ; seq eps' (writeMutVar eps_var eps')
279 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
281 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
282 ; eps_var <- getEpsVar
283 ; eps <- readMutVar eps_var
284 ; let { eps' = upd_fn eps }
285 ; seq eps' (writeMutVar eps_var eps') }
287 getHpt :: TcRnIf gbl lcl HomePackageTable
288 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
290 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
291 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
292 ; return (eps, hsc_HPT env) }
295 %************************************************************************
299 %************************************************************************
302 newUnique :: TcRnIf gbl lcl Unique
304 = do { env <- getEnv ;
305 let { u_var = env_us env } ;
306 us <- readMutVar u_var ;
307 case splitUniqSupply us of { (us1,_) -> do {
308 writeMutVar u_var us1 ;
309 return $! uniqFromSupply us }}}
310 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
311 -- a chain of unevaluated supplies behind.
312 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
313 -- throw away one half of the new split supply. This is safe because this
314 -- is the only place we use that unique. Using the other half of the split
315 -- supply is safer, but slower.
317 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
319 = do { env <- getEnv ;
320 let { u_var = env_us env } ;
321 us <- readMutVar u_var ;
322 case splitUniqSupply us of { (us1,us2) -> do {
323 writeMutVar u_var us1 ;
326 newLocalName :: Name -> TcRnIf gbl lcl Name
327 newLocalName name -- Make a clone
328 = do { uniq <- newUnique
329 ; return (mkInternalName uniq (nameOccName name) (getSrcLoc name)) }
331 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
332 newSysLocalIds fs tys
333 = do { us <- newUniqueSupply
334 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
338 %************************************************************************
342 %************************************************************************
345 traceTc, traceRn :: SDoc -> TcRn ()
346 traceRn = traceOptTcRn Opt_D_dump_rn_trace
347 traceTc = traceOptTcRn Opt_D_dump_tc_trace
348 traceSplice = traceOptTcRn Opt_D_dump_splices
351 traceIf :: SDoc -> TcRnIf m n ()
352 traceIf = traceOptIf Opt_D_dump_if_trace
353 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
356 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
357 traceOptIf flag doc = ifOptM flag $
358 ioToIOEnv (printForUser stderr alwaysQualify doc)
360 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
361 traceOptTcRn flag doc = ifOptM flag $ do
364 ; env0 <- tcInitTidyEnv
365 ; ctxt_msgs <- do_ctxt env0 ctxt
366 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
367 ; dumpTcRn real_doc }
369 dumpTcRn :: SDoc -> TcRn ()
370 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
371 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
373 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
374 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
378 %************************************************************************
380 Typechecker global environment
382 %************************************************************************
385 getModule :: TcRn Module
386 getModule = do { env <- getGblEnv; return (tcg_mod env) }
388 setModule :: Module -> TcRn a -> TcRn a
389 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
391 tcIsHsBoot :: TcRn Bool
392 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
394 getGlobalRdrEnv :: TcRn GlobalRdrEnv
395 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
397 getImports :: TcRn ImportAvails
398 getImports = do { env <- getGblEnv; return (tcg_imports env) }
400 getFixityEnv :: TcRn FixityEnv
401 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
403 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
404 extendFixityEnv new_bit
405 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
406 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
408 getDefaultTys :: TcRn (Maybe [Type])
409 getDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
412 %************************************************************************
416 %************************************************************************
419 getSrcSpanM :: TcRn SrcSpan
420 -- Avoid clash with Name.getSrcLoc
421 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
423 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
424 setSrcSpan loc thing_inside
425 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
426 | otherwise = thing_inside -- Don't overwrite useful info with useless
428 addLocM :: (a -> TcM b) -> Located a -> TcM b
429 addLocM fn (L loc a) = setSrcSpan loc $ fn a
431 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
432 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
434 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
435 wrapLocFstM fn (L loc a) =
440 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
441 wrapLocSndM fn (L loc a) =
449 getErrsVar :: TcRn (TcRef Messages)
450 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
452 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
453 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
455 addErr :: Message -> TcRn ()
456 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
458 addLocErr :: Located e -> (e -> Message) -> TcRn ()
459 addLocErr (L loc e) fn = addErrAt loc (fn e)
461 addErrAt :: SrcSpan -> Message -> TcRn ()
462 addErrAt loc msg = addLongErrAt loc msg empty
464 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
465 addLongErrAt loc msg extra
466 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
467 errs_var <- getErrsVar ;
468 rdr_env <- getGlobalRdrEnv ;
469 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
470 (warns, errs) <- readMutVar errs_var ;
471 writeMutVar errs_var (warns, errs `snocBag` err) }
473 addErrs :: [(SrcSpan,Message)] -> TcRn ()
474 addErrs msgs = mappM_ add msgs
476 add (loc,msg) = addErrAt loc msg
478 addReport :: Message -> TcRn ()
479 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
481 addReportAt :: SrcSpan -> Message -> TcRn ()
483 = do { errs_var <- getErrsVar ;
484 rdr_env <- getGlobalRdrEnv ;
485 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
486 (warns, errs) <- readMutVar errs_var ;
487 writeMutVar errs_var (warns `snocBag` warn, errs) }
489 addWarn :: Message -> TcRn ()
490 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
492 addWarnAt :: SrcSpan -> Message -> TcRn ()
493 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
495 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
496 addLocWarn (L loc e) fn = addReportAt loc (fn e)
498 checkErr :: Bool -> Message -> TcRn ()
499 -- Add the error if the bool is False
500 checkErr ok msg = checkM ok (addErr msg)
502 warnIf :: Bool -> Message -> TcRn ()
503 warnIf True msg = addWarn msg
504 warnIf False msg = return ()
506 addMessages :: Messages -> TcRn ()
507 addMessages (m_warns, m_errs)
508 = do { errs_var <- getErrsVar ;
509 (warns, errs) <- readMutVar errs_var ;
510 writeMutVar errs_var (warns `unionBags` m_warns,
511 errs `unionBags` m_errs) }
513 discardWarnings :: TcRn a -> TcRn a
514 -- Ignore warnings inside the thing inside;
515 -- used to ignore-unused-variable warnings inside derived code
516 -- With -dppr-debug, the effects is switched off, so you can still see
517 -- what warnings derived code would give
518 discardWarnings thing_inside
519 | opt_PprStyle_Debug = thing_inside
521 = do { errs_var <- newMutVar emptyMessages
522 ; result <- setErrsVar errs_var thing_inside
523 ; (_warns, errs) <- readMutVar errs_var
524 ; addMessages (emptyBag, errs)
530 try_m :: TcRn r -> TcRn (Either Exception r)
531 -- Does try_m, with a debug-trace on failure
533 = do { mb_r <- tryM thing ;
535 Left exn -> do { traceTc (exn_msg exn); return mb_r }
536 Right r -> return mb_r }
538 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
540 -----------------------
541 recoverM :: TcRn r -- Recovery action; do this if the main one fails
542 -> TcRn r -- Main action: do this first
544 -- Errors in 'thing' are retained
545 recoverM recover thing
546 = do { mb_res <- try_m thing ;
549 Right res -> returnM res }
551 -----------------------
552 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
553 -- (tryTc m) executes m, and returns
554 -- Just r, if m succeeds (returning r)
555 -- Nothing, if m fails
556 -- It also returns all the errors and warnings accumulated by m
557 -- It always succeeds (never raises an exception)
559 = do { errs_var <- newMutVar emptyMessages ;
560 res <- try_m (setErrsVar errs_var m) ;
561 msgs <- readMutVar errs_var ;
562 return (msgs, case res of
564 Right val -> Just val)
565 -- The exception is always the IOEnv built-in
566 -- in exception; see IOEnv.failM
569 -----------------------
570 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
571 -- Run the thing, returning
572 -- Just r, if m succceeds with no error messages
573 -- Nothing, if m fails, or if it succeeds but has error messages
574 -- Either way, the messages are returned; even in the Just case
575 -- there might be warnings
577 = do { (msgs, res) <- tryTc thing
579 ; let errs_found = errorsFound dflags msgs
580 ; return (msgs, case res of
582 Just val | errs_found -> Nothing
583 | otherwise -> Just val)
586 -----------------------
587 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
588 -- Just like tryTcErrs, except that it ensures that the LIE
589 -- for the thing is propagated only if there are no errors
590 -- Hence it's restricted to the type-check monad
591 tryTcLIE thing_inside
592 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
594 Nothing -> return (msgs, Nothing)
595 Just val -> do { extendLIEs lie; return (msgs, Just val) }
598 -----------------------
599 tryTcLIE_ :: TcM r -> TcM r -> TcM r
600 -- (tryTcLIE_ r m) tries m;
601 -- if m succeeds with no error messages, it's the answer
602 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
603 tryTcLIE_ recover main
604 = do { (msgs, mb_res) <- tryTcLIE main
606 Just val -> do { addMessages msgs -- There might be warnings
608 Nothing -> recover -- Discard all msgs
611 -----------------------
612 checkNoErrs :: TcM r -> TcM r
613 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
614 -- If m fails then (checkNoErrsTc m) fails.
615 -- If m succeeds, it checks whether m generated any errors messages
616 -- (it might have recovered internally)
617 -- If so, it fails too.
618 -- Regardless, any errors generated by m are propagated to the enclosing context.
620 = do { (msgs, mb_res) <- tryTcLIE main
624 Just val -> return val
627 ifErrsM :: TcRn r -> TcRn r -> TcRn r
628 -- ifErrsM bale_out main
629 -- does 'bale_out' if there are errors in errors collection
630 -- otherwise does 'main'
631 ifErrsM bale_out normal
632 = do { errs_var <- getErrsVar ;
633 msgs <- readMutVar errs_var ;
635 if errorsFound dflags msgs then
640 failIfErrsM :: TcRn ()
641 -- Useful to avoid error cascades
642 failIfErrsM = ifErrsM failM (return ())
646 %************************************************************************
648 Context management and error message generation
651 %************************************************************************
654 getErrCtxt :: TcM ErrCtxt
655 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
657 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
658 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
660 addErrCtxt :: Message -> TcM a -> TcM a
661 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
663 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
664 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
666 -- Helper function for the above
667 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
668 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
669 env { tcl_ctxt = upd ctxt })
671 -- Conditionally add an error context
672 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
673 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
674 maybeAddErrCtxt Nothing thing_inside = thing_inside
676 popErrCtxt :: TcM a -> TcM a
677 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
679 getInstLoc :: InstOrigin -> TcM InstLoc
681 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
682 return (InstLoc origin loc (tcl_ctxt env)) }
684 addInstCtxt :: InstLoc -> TcM a -> TcM a
685 -- Add the SrcSpan and context from the first Inst in the list
686 -- (they all have similar locations)
687 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
688 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
691 The addErrTc functions add an error message, but do not cause failure.
692 The 'M' variants pass a TidyEnv that has already been used to
693 tidy up the message; we then use it to tidy the context messages
696 addErrTc :: Message -> TcM ()
697 addErrTc err_msg = do { env0 <- tcInitTidyEnv
698 ; addErrTcM (env0, err_msg) }
700 addErrsTc :: [Message] -> TcM ()
701 addErrsTc err_msgs = mappM_ addErrTc err_msgs
703 addErrTcM :: (TidyEnv, Message) -> TcM ()
704 addErrTcM (tidy_env, err_msg)
705 = do { ctxt <- getErrCtxt ;
707 add_err_tcm tidy_env err_msg loc ctxt }
710 The failWith functions add an error message and cause failure
713 failWithTc :: Message -> TcM a -- Add an error message and fail
715 = addErrTc err_msg >> failM
717 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
718 failWithTcM local_and_msg
719 = addErrTcM local_and_msg >> failM
721 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
722 checkTc True err = returnM ()
723 checkTc False err = failWithTc err
726 Warnings have no 'M' variant, nor failure
729 addWarnTc :: Message -> TcM ()
731 = do { ctxt <- getErrCtxt ;
732 env0 <- tcInitTidyEnv ;
733 ctxt_msgs <- do_ctxt env0 ctxt ;
734 addWarn (vcat (msg : ctxt_to_use ctxt_msgs)) }
736 warnTc :: Bool -> Message -> TcM ()
737 warnTc warn_if_true warn_msg
738 | warn_if_true = addWarnTc warn_msg
739 | otherwise = return ()
742 -----------------------------------
745 We initialise the "tidy-env", used for tidying types before printing,
746 by building a reverse map from the in-scope type variables to the
747 OccName that the programmer originally used for them
750 tcInitTidyEnv :: TcM TidyEnv
752 = do { lcl_env <- getLclEnv
753 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
754 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
756 ; return (foldl add emptyTidyEnv nm_tv_prs) }
758 add (env,subst) (name, tyvar)
759 = case tidyOccName env (nameOccName name) of
760 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
762 tyvar' = setTyVarName tyvar name'
763 name' = tidyNameOcc name occ'
766 -----------------------------------
767 Other helper functions
770 add_err_tcm tidy_env err_msg loc ctxt
771 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
772 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
776 do_ctxt tidy_env (c:cs)
777 = do { (tidy_env', m) <- c tidy_env ;
778 ms <- do_ctxt tidy_env' cs ;
781 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
782 | otherwise = take 3 ctxt
785 debugTc is useful for monadic debugging code
788 debugTc :: TcM () -> TcM ()
790 debugTc thing = thing
792 debugTc thing = return ()
796 %************************************************************************
798 Type constraints (the so-called LIE)
800 %************************************************************************
803 nextDFunIndex :: TcM Int -- Get the next dfun index
804 nextDFunIndex = do { env <- getGblEnv
805 ; let dfun_n_var = tcg_dfun_n env
806 ; n <- readMutVar dfun_n_var
807 ; writeMutVar dfun_n_var (n+1)
810 getLIEVar :: TcM (TcRef LIE)
811 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
813 setLIEVar :: TcRef LIE -> TcM a -> TcM a
814 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
816 getLIE :: TcM a -> TcM (a, [Inst])
817 -- (getLIE m) runs m, and returns the type constraints it generates
819 = do { lie_var <- newMutVar emptyLIE ;
820 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
822 lie <- readMutVar lie_var ;
823 return (res, lieToList lie) }
825 extendLIE :: Inst -> TcM ()
827 = do { lie_var <- getLIEVar ;
828 lie <- readMutVar lie_var ;
829 writeMutVar lie_var (inst `consLIE` lie) }
831 extendLIEs :: [Inst] -> TcM ()
835 = do { lie_var <- getLIEVar ;
836 lie <- readMutVar lie_var ;
837 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
841 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
842 -- Set the local type envt, but do *not* disturb other fields,
843 -- notably the lie_var
844 setLclTypeEnv lcl_env thing_inside
845 = updLclEnv upd thing_inside
847 upd env = env { tcl_env = tcl_env lcl_env,
848 tcl_tyvars = tcl_tyvars lcl_env }
852 %************************************************************************
854 Template Haskell context
856 %************************************************************************
859 recordThUse :: TcM ()
860 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
862 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
863 keepAliveTc n = do { env <- getGblEnv;
864 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
866 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
867 keepAliveSetTc ns = do { env <- getGblEnv;
868 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
870 getStage :: TcM ThStage
871 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
873 setStage :: ThStage -> TcM a -> TcM a
874 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
878 %************************************************************************
880 Stuff for the renamer's local env
882 %************************************************************************
885 getLocalRdrEnv :: RnM LocalRdrEnv
886 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
888 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
889 setLocalRdrEnv rdr_env thing_inside
890 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
894 %************************************************************************
896 Stuff for interface decls
898 %************************************************************************
901 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
902 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
904 if_tv_env = emptyOccEnv,
905 if_id_env = emptyOccEnv }
907 initIfaceTcRn :: IfG a -> TcRn a
908 initIfaceTcRn thing_inside
909 = do { tcg_env <- getGblEnv
910 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
911 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
912 ; setEnvs (if_env, ()) thing_inside }
914 initIfaceExtCore :: IfL a -> TcRn a
915 initIfaceExtCore thing_inside
916 = do { tcg_env <- getGblEnv
917 ; let { mod = tcg_mod tcg_env
918 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
919 ; if_env = IfGblEnv {
920 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
921 ; if_lenv = mkIfLclEnv mod doc
923 ; setEnvs (if_env, if_lenv) thing_inside }
925 initIfaceCheck :: HscEnv -> IfG a -> IO a
926 -- Used when checking the up-to-date-ness of the old Iface
927 -- Initialise the environment with no useful info at all
928 initIfaceCheck hsc_env do_this
929 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
930 ; initTcRnIf 'i' hsc_env gbl_env () do_this
933 initIfaceTc :: ModIface
934 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
935 -- Used when type-checking checking an up-to-date interface file
936 -- No type envt from the current module, but we do know the module dependencies
937 initIfaceTc iface do_this
938 = do { tc_env_var <- newMutVar emptyTypeEnv
939 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
940 ; if_lenv = mkIfLclEnv mod doc
942 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
945 mod = mi_module iface
946 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
948 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
949 -- Used when sucking in new Rules in SimplCore
950 -- We have available the type envt of the module being compiled, and we must use it
951 initIfaceRules hsc_env guts do_this
953 type_info = (mg_module guts, return (mg_types guts))
954 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
957 -- Run the thing; any exceptions just bubble out from here
958 ; initTcRnIf 'i' hsc_env gbl_env () do_this
961 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
962 initIfaceLcl mod loc_doc thing_inside
963 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
965 getIfModule :: IfL Module
966 getIfModule = do { env <- getLclEnv; return (if_mod env) }
969 failIfM :: Message -> IfL a
970 -- The Iface monad doesn't have a place to accumulate errors, so we
971 -- just fall over fast if one happens; it "shouldnt happen".
972 -- We use IfL here so that we can get context info out of the local env
974 = do { env <- getLclEnv
975 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
976 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
980 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
981 -- Run thing_inside in an interleaved thread.
982 -- It shares everything with the parent thread, so this is DANGEROUS.
984 -- It returns Nothing if the computation fails
986 -- It's used for lazily type-checking interface
987 -- signatures, which is pretty benign
989 forkM_maybe doc thing_inside
990 = do { unsafeInterleaveM $
991 do { traceIf (text "Starting fork {" <+> doc)
993 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
996 Right r -> do { traceIf (text "} ending fork" <+> doc)
1000 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1001 -- Otherwise we silently discard errors. Errors can legitimately
1002 -- happen when compiling interface signatures (see tcInterfaceSigs)
1003 ifOptM Opt_D_dump_if_trace
1004 (print_errs (hang (text "forkM failed:" <+> doc)
1005 4 (text (show exn))))
1007 ; traceIf (text "} ending fork (badly)" <+> doc)
1011 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1013 forkM :: SDoc -> IfL a -> IfL a
1014 forkM doc thing_inside
1015 = do { mb_res <- forkM_maybe doc thing_inside
1016 ; return (case mb_res of
1017 Nothing -> pgmError "Cannot continue after interface file error"
1018 -- pprPanic "forkM" doc