2 % (c) The University of Glasgow 2006
12 #include "HsVersions.h"
14 import TcRnTypes -- Re-export all
15 import IOEnv -- Re-export all
17 import HsSyn hiding (LIE)
46 import Control.Exception
51 %************************************************************************
55 %************************************************************************
58 ioToTcRn :: IO r -> TcRn r
66 -> Bool -- True <=> retain renamed syntax trees
69 -> IO (Messages, Maybe r)
70 -- Nothing => error thrown by the thing inside
71 -- (error messages should have been printed already)
73 initTc hsc_env hsc_src keep_rn_syntax mod do_this
74 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
75 tvs_var <- newIORef emptyVarSet ;
76 type_env_var <- newIORef emptyNameEnv ;
77 dfuns_var <- newIORef emptyNameSet ;
78 keep_var <- newIORef emptyNameSet ;
79 th_var <- newIORef False ;
80 dfun_n_var <- newIORef 1 ;
82 maybe_rn_syntax empty_val
83 | keep_rn_syntax = Just empty_val
84 | otherwise = Nothing ;
89 tcg_rdr_env = hsc_global_rdr_env hsc_env,
90 tcg_fix_env = emptyNameEnv,
91 tcg_field_env = emptyNameEnv,
92 tcg_default = Nothing,
93 tcg_type_env = hsc_global_type_env hsc_env,
94 tcg_type_env_var = type_env_var,
95 tcg_inst_env = emptyInstEnv,
96 tcg_fam_inst_env = emptyFamInstEnv,
97 tcg_inst_uses = dfuns_var,
100 tcg_imports = emptyImportAvails,
103 tcg_rn_imports = maybe_rn_syntax [],
104 tcg_rn_exports = maybe_rn_syntax [],
105 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
107 tcg_binds = emptyLHsBinds,
108 tcg_deprecs = NoDeprecs,
113 tcg_dfun_n = dfun_n_var,
116 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing,
121 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
123 tcl_rdr = emptyLocalRdrEnv,
124 tcl_th_ctxt = topStage,
125 tcl_arrow_ctxt = NoArrowCtxt,
126 tcl_env = emptyNameEnv,
127 tcl_tyvars = tvs_var,
128 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
132 -- OK, here's the business end!
133 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
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 False mod todo
156 printErrorsAndWarnings (hsc_dflags env) msgs
160 %************************************************************************
164 %************************************************************************
168 initTcRnIf :: Char -- Tag for unique supply
173 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
174 = do { us <- mkSplitUniqSupply uniq_tag ;
175 ; us_var <- newIORef us ;
177 ; let { env = Env { env_top = hsc_env,
180 env_lcl = lcl_env } }
182 ; runIOEnv env thing_inside
186 %************************************************************************
190 %************************************************************************
193 getTopEnv :: TcRnIf gbl lcl HscEnv
194 getTopEnv = do { env <- getEnv; return (env_top env) }
196 getGblEnv :: TcRnIf gbl lcl gbl
197 getGblEnv = do { env <- getEnv; return (env_gbl env) }
199 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
200 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
201 env { env_gbl = upd gbl })
203 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
204 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
206 getLclEnv :: TcRnIf gbl lcl lcl
207 getLclEnv = do { env <- getEnv; return (env_lcl env) }
209 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
210 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
211 env { env_lcl = upd lcl })
213 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
214 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
216 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
217 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
219 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
220 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
227 getDOpts :: TcRnIf gbl lcl DynFlags
228 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
230 doptM :: DynFlag -> TcRnIf gbl lcl Bool
231 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
233 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
234 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
235 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
237 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
238 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
239 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
241 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
242 ifOptM flag thing_inside = do { b <- doptM flag;
243 if b then thing_inside else return () }
245 getGhcMode :: TcRnIf gbl lcl GhcMode
246 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
250 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
251 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
253 getEps :: TcRnIf gbl lcl ExternalPackageState
254 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
256 -- Updating the EPS. This should be an atomic operation.
257 -- Note the delicate 'seq' which forces the EPS before putting it in the
258 -- variable. Otherwise what happens is that we get
259 -- write eps_var (....(unsafeRead eps_var)....)
260 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
261 -- we make the unsafeRead happen before we update the variable.
263 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
265 updateEps upd_fn = do { traceIf (text "updating EPS")
266 ; eps_var <- getEpsVar
267 ; eps <- readMutVar eps_var
268 ; let { (eps', val) = upd_fn eps }
269 ; seq eps' (writeMutVar eps_var eps')
272 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
274 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
275 ; eps_var <- getEpsVar
276 ; eps <- readMutVar eps_var
277 ; let { eps' = upd_fn eps }
278 ; seq eps' (writeMutVar eps_var eps') }
280 getHpt :: TcRnIf gbl lcl HomePackageTable
281 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
283 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
284 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
285 ; return (eps, hsc_HPT env) }
288 %************************************************************************
292 %************************************************************************
295 newUnique :: TcRnIf gbl lcl Unique
297 = do { env <- getEnv ;
298 let { u_var = env_us env } ;
299 us <- readMutVar u_var ;
300 case splitUniqSupply us of { (us1,_) -> do {
301 writeMutVar u_var us1 ;
302 return $! uniqFromSupply us }}}
303 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
304 -- a chain of unevaluated supplies behind.
305 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
306 -- throw away one half of the new split supply. This is safe because this
307 -- is the only place we use that unique. Using the other half of the split
308 -- supply is safer, but slower.
310 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
312 = do { env <- getEnv ;
313 let { u_var = env_us env } ;
314 us <- readMutVar u_var ;
315 case splitUniqSupply us of { (us1,us2) -> do {
316 writeMutVar u_var us1 ;
319 newLocalName :: Name -> TcRnIf gbl lcl Name
320 newLocalName name -- Make a clone
321 = do { uniq <- newUnique
322 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
324 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
325 newSysLocalIds fs tys
326 = do { us <- newUniqueSupply
327 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
331 %************************************************************************
335 %************************************************************************
338 traceTc, traceRn :: SDoc -> TcRn ()
339 traceRn = traceOptTcRn Opt_D_dump_rn_trace
340 traceTc = traceOptTcRn Opt_D_dump_tc_trace
341 traceSplice = traceOptTcRn Opt_D_dump_splices
344 traceIf :: SDoc -> TcRnIf m n ()
345 traceIf = traceOptIf Opt_D_dump_if_trace
346 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
349 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
350 traceOptIf flag doc = ifOptM flag $
351 ioToIOEnv (printForUser stderr alwaysQualify doc)
353 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
354 traceOptTcRn flag doc = ifOptM flag $ do
357 ; env0 <- tcInitTidyEnv
358 ; ctxt_msgs <- do_ctxt env0 ctxt
359 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
360 ; dumpTcRn real_doc }
362 dumpTcRn :: SDoc -> TcRn ()
363 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
364 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
366 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
367 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
371 %************************************************************************
373 Typechecker global environment
375 %************************************************************************
378 getModule :: TcRn Module
379 getModule = do { env <- getGblEnv; return (tcg_mod env) }
381 setModule :: Module -> TcRn a -> TcRn a
382 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
384 tcIsHsBoot :: TcRn Bool
385 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
387 getGlobalRdrEnv :: TcRn GlobalRdrEnv
388 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
390 getImports :: TcRn ImportAvails
391 getImports = do { env <- getGblEnv; return (tcg_imports env) }
393 getFixityEnv :: TcRn FixityEnv
394 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
396 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
397 extendFixityEnv new_bit
398 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
399 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
401 getRecFieldEnv :: TcRn RecFieldEnv
402 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
404 extendRecFieldEnv :: RecFieldEnv -> RnM a -> RnM a
405 extendRecFieldEnv new_bit
406 = updGblEnv (\env@(TcGblEnv { tcg_field_env = old_env }) ->
407 env {tcg_field_env = old_env `plusNameEnv` new_bit})
409 getDeclaredDefaultTys :: TcRn (Maybe [Type])
410 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
413 %************************************************************************
417 %************************************************************************
420 getSrcSpanM :: TcRn SrcSpan
421 -- Avoid clash with Name.getSrcLoc
422 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
424 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
425 setSrcSpan loc thing_inside
426 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
427 | otherwise = thing_inside -- Don't overwrite useful info with useless
429 addLocM :: (a -> TcM b) -> Located a -> TcM b
430 addLocM fn (L loc a) = setSrcSpan loc $ fn a
432 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
433 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
435 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
436 wrapLocFstM fn (L loc a) =
441 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
442 wrapLocSndM fn (L loc a) =
450 getErrsVar :: TcRn (TcRef Messages)
451 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
453 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
454 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
456 addErr :: Message -> TcRn ()
457 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
459 addLocErr :: Located e -> (e -> Message) -> TcRn ()
460 addLocErr (L loc e) fn = addErrAt loc (fn e)
462 addErrAt :: SrcSpan -> Message -> TcRn ()
463 addErrAt loc msg = addLongErrAt loc msg empty
465 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
466 addLongErrAt loc msg extra
467 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
468 errs_var <- getErrsVar ;
469 rdr_env <- getGlobalRdrEnv ;
470 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
471 (warns, errs) <- readMutVar errs_var ;
472 writeMutVar errs_var (warns, errs `snocBag` err) }
474 addErrs :: [(SrcSpan,Message)] -> TcRn ()
475 addErrs msgs = mappM_ add msgs
477 add (loc,msg) = addErrAt loc msg
479 addReport :: Message -> TcRn ()
480 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
482 addReportAt :: SrcSpan -> Message -> TcRn ()
484 = do { errs_var <- getErrsVar ;
485 rdr_env <- getGlobalRdrEnv ;
486 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
487 (warns, errs) <- readMutVar errs_var ;
488 writeMutVar errs_var (warns `snocBag` warn, errs) }
490 addWarn :: Message -> TcRn ()
491 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
493 addWarnAt :: SrcSpan -> Message -> TcRn ()
494 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
496 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
497 addLocWarn (L loc e) fn = addReportAt loc (fn e)
499 checkErr :: Bool -> Message -> TcRn ()
500 -- Add the error if the bool is False
501 checkErr ok msg = checkM ok (addErr msg)
503 warnIf :: Bool -> Message -> TcRn ()
504 warnIf True msg = addWarn msg
505 warnIf False msg = return ()
507 addMessages :: Messages -> TcRn ()
508 addMessages (m_warns, m_errs)
509 = do { errs_var <- getErrsVar ;
510 (warns, errs) <- readMutVar errs_var ;
511 writeMutVar errs_var (warns `unionBags` m_warns,
512 errs `unionBags` m_errs) }
514 discardWarnings :: TcRn a -> TcRn a
515 -- Ignore warnings inside the thing inside;
516 -- used to ignore-unused-variable warnings inside derived code
517 -- With -dppr-debug, the effects is switched off, so you can still see
518 -- what warnings derived code would give
519 discardWarnings thing_inside
520 | opt_PprStyle_Debug = thing_inside
522 = do { errs_var <- newMutVar emptyMessages
523 ; result <- setErrsVar errs_var thing_inside
524 ; (_warns, errs) <- readMutVar errs_var
525 ; addMessages (emptyBag, errs)
531 try_m :: TcRn r -> TcRn (Either Exception r)
532 -- Does try_m, with a debug-trace on failure
534 = do { mb_r <- tryM thing ;
536 Left exn -> do { traceTc (exn_msg exn); return mb_r }
537 Right r -> return mb_r }
539 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
541 -----------------------
542 recoverM :: TcRn r -- Recovery action; do this if the main one fails
543 -> TcRn r -- Main action: do this first
545 -- Errors in 'thing' are retained
546 recoverM recover thing
547 = do { mb_res <- try_m thing ;
550 Right res -> returnM res }
552 -----------------------
553 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
554 -- (tryTc m) executes m, and returns
555 -- Just r, if m succeeds (returning r)
556 -- Nothing, if m fails
557 -- It also returns all the errors and warnings accumulated by m
558 -- It always succeeds (never raises an exception)
560 = do { errs_var <- newMutVar emptyMessages ;
561 res <- try_m (setErrsVar errs_var m) ;
562 msgs <- readMutVar errs_var ;
563 return (msgs, case res of
565 Right val -> Just val)
566 -- The exception is always the IOEnv built-in
567 -- in exception; see IOEnv.failM
570 -----------------------
571 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
572 -- Run the thing, returning
573 -- Just r, if m succceeds with no error messages
574 -- Nothing, if m fails, or if it succeeds but has error messages
575 -- Either way, the messages are returned; even in the Just case
576 -- there might be warnings
578 = do { (msgs, res) <- tryTc thing
580 ; let errs_found = errorsFound dflags msgs
581 ; return (msgs, case res of
583 Just val | errs_found -> Nothing
584 | otherwise -> Just val)
587 -----------------------
588 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
589 -- Just like tryTcErrs, except that it ensures that the LIE
590 -- for the thing is propagated only if there are no errors
591 -- Hence it's restricted to the type-check monad
592 tryTcLIE thing_inside
593 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
595 Nothing -> return (msgs, Nothing)
596 Just val -> do { extendLIEs lie; return (msgs, Just val) }
599 -----------------------
600 tryTcLIE_ :: TcM r -> TcM r -> TcM r
601 -- (tryTcLIE_ r m) tries m;
602 -- if m succeeds with no error messages, it's the answer
603 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
604 tryTcLIE_ recover main
605 = do { (msgs, mb_res) <- tryTcLIE main
607 Just val -> do { addMessages msgs -- There might be warnings
609 Nothing -> recover -- Discard all msgs
612 -----------------------
613 checkNoErrs :: TcM r -> TcM r
614 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
615 -- If m fails then (checkNoErrsTc m) fails.
616 -- If m succeeds, it checks whether m generated any errors messages
617 -- (it might have recovered internally)
618 -- If so, it fails too.
619 -- Regardless, any errors generated by m are propagated to the enclosing context.
621 = do { (msgs, mb_res) <- tryTcLIE main
625 Just val -> return val
628 ifErrsM :: TcRn r -> TcRn r -> TcRn r
629 -- ifErrsM bale_out main
630 -- does 'bale_out' if there are errors in errors collection
631 -- otherwise does 'main'
632 ifErrsM bale_out normal
633 = do { errs_var <- getErrsVar ;
634 msgs <- readMutVar errs_var ;
636 if errorsFound dflags msgs then
641 failIfErrsM :: TcRn ()
642 -- Useful to avoid error cascades
643 failIfErrsM = ifErrsM failM (return ())
647 %************************************************************************
649 Context management and error message generation
652 %************************************************************************
655 getErrCtxt :: TcM ErrCtxt
656 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
658 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
659 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
661 addErrCtxt :: Message -> TcM a -> TcM a
662 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
664 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
665 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
667 -- Helper function for the above
668 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
669 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
670 env { tcl_ctxt = upd ctxt })
672 -- Conditionally add an error context
673 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
674 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
675 maybeAddErrCtxt Nothing thing_inside = thing_inside
677 popErrCtxt :: TcM a -> TcM a
678 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
680 getInstLoc :: InstOrigin -> TcM InstLoc
682 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
683 return (InstLoc origin loc (tcl_ctxt env)) }
685 addInstCtxt :: InstLoc -> TcM a -> TcM a
686 -- Add the SrcSpan and context from the first Inst in the list
687 -- (they all have similar locations)
688 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
689 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
692 The addErrTc functions add an error message, but do not cause failure.
693 The 'M' variants pass a TidyEnv that has already been used to
694 tidy up the message; we then use it to tidy the context messages
697 addErrTc :: Message -> TcM ()
698 addErrTc err_msg = do { env0 <- tcInitTidyEnv
699 ; addErrTcM (env0, err_msg) }
701 addErrsTc :: [Message] -> TcM ()
702 addErrsTc err_msgs = mappM_ addErrTc err_msgs
704 addErrTcM :: (TidyEnv, Message) -> TcM ()
705 addErrTcM (tidy_env, err_msg)
706 = do { ctxt <- getErrCtxt ;
708 add_err_tcm tidy_env err_msg loc ctxt }
711 The failWith functions add an error message and cause failure
714 failWithTc :: Message -> TcM a -- Add an error message and fail
716 = addErrTc err_msg >> failM
718 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
719 failWithTcM local_and_msg
720 = addErrTcM local_and_msg >> failM
722 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
723 checkTc True err = returnM ()
724 checkTc False err = failWithTc err
727 Warnings have no 'M' variant, nor failure
730 addWarnTc :: Message -> TcM ()
731 addWarnTc msg = do { env0 <- tcInitTidyEnv
732 ; addWarnTcM (env0, msg) }
734 addWarnTcM :: (TidyEnv, Message) -> TcM ()
735 addWarnTcM (env0, msg)
736 = do { ctxt <- getErrCtxt ;
737 ctxt_msgs <- do_ctxt env0 ctxt ;
738 addReport (vcat (ptext SLIT("Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
740 warnTc :: Bool -> Message -> TcM ()
741 warnTc warn_if_true warn_msg
742 | warn_if_true = addWarnTc warn_msg
743 | otherwise = return ()
746 -----------------------------------
749 We initialise the "tidy-env", used for tidying types before printing,
750 by building a reverse map from the in-scope type variables to the
751 OccName that the programmer originally used for them
754 tcInitTidyEnv :: TcM TidyEnv
756 = do { lcl_env <- getLclEnv
757 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
758 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
760 ; return (foldl add emptyTidyEnv nm_tv_prs) }
762 add (env,subst) (name, tyvar)
763 = case tidyOccName env (nameOccName name) of
764 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
766 tyvar' = setTyVarName tyvar name'
767 name' = tidyNameOcc name occ'
770 -----------------------------------
771 Other helper functions
774 add_err_tcm tidy_env err_msg loc ctxt
775 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
776 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
780 do_ctxt tidy_env (c:cs)
781 = do { (tidy_env', m) <- c tidy_env ;
782 ms <- do_ctxt tidy_env' cs ;
785 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
786 | otherwise = take 3 ctxt
789 debugTc is useful for monadic debugging code
792 debugTc :: TcM () -> TcM ()
794 debugTc thing = thing
796 debugTc thing = return ()
800 %************************************************************************
802 Type constraints (the so-called LIE)
804 %************************************************************************
807 nextDFunIndex :: TcM Int -- Get the next dfun index
808 nextDFunIndex = do { env <- getGblEnv
809 ; let dfun_n_var = tcg_dfun_n env
810 ; n <- readMutVar dfun_n_var
811 ; writeMutVar dfun_n_var (n+1)
814 getLIEVar :: TcM (TcRef LIE)
815 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
817 setLIEVar :: TcRef LIE -> TcM a -> TcM a
818 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
820 getLIE :: TcM a -> TcM (a, [Inst])
821 -- (getLIE m) runs m, and returns the type constraints it generates
823 = do { lie_var <- newMutVar emptyLIE ;
824 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
826 lie <- readMutVar lie_var ;
827 return (res, lieToList lie) }
829 extendLIE :: Inst -> TcM ()
831 = do { lie_var <- getLIEVar ;
832 lie <- readMutVar lie_var ;
833 writeMutVar lie_var (inst `consLIE` lie) }
835 extendLIEs :: [Inst] -> TcM ()
839 = do { lie_var <- getLIEVar ;
840 lie <- readMutVar lie_var ;
841 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
845 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
846 -- Set the local type envt, but do *not* disturb other fields,
847 -- notably the lie_var
848 setLclTypeEnv lcl_env thing_inside
849 = updLclEnv upd thing_inside
851 upd env = env { tcl_env = tcl_env lcl_env,
852 tcl_tyvars = tcl_tyvars lcl_env }
856 %************************************************************************
858 Template Haskell context
860 %************************************************************************
863 recordThUse :: TcM ()
864 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
866 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
867 keepAliveTc n = do { env <- getGblEnv;
868 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
870 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
871 keepAliveSetTc ns = do { env <- getGblEnv;
872 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
874 getStage :: TcM ThStage
875 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
877 setStage :: ThStage -> TcM a -> TcM a
878 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
882 %************************************************************************
884 Stuff for the renamer's local env
886 %************************************************************************
889 getLocalRdrEnv :: RnM LocalRdrEnv
890 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
892 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
893 setLocalRdrEnv rdr_env thing_inside
894 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
898 %************************************************************************
900 Stuff for interface decls
902 %************************************************************************
905 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
906 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
908 if_tv_env = emptyOccEnv,
909 if_id_env = emptyOccEnv }
911 initIfaceTcRn :: IfG a -> TcRn a
912 initIfaceTcRn thing_inside
913 = do { tcg_env <- getGblEnv
914 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
915 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
916 ; setEnvs (if_env, ()) thing_inside }
918 initIfaceExtCore :: IfL a -> TcRn a
919 initIfaceExtCore thing_inside
920 = do { tcg_env <- getGblEnv
921 ; let { mod = tcg_mod tcg_env
922 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
923 ; if_env = IfGblEnv {
924 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
925 ; if_lenv = mkIfLclEnv mod doc
927 ; setEnvs (if_env, if_lenv) thing_inside }
929 initIfaceCheck :: HscEnv -> IfG a -> IO a
930 -- Used when checking the up-to-date-ness of the old Iface
931 -- Initialise the environment with no useful info at all
932 initIfaceCheck hsc_env do_this
933 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
934 ; initTcRnIf 'i' hsc_env gbl_env () do_this
937 initIfaceTc :: ModIface
938 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
939 -- Used when type-checking checking an up-to-date interface file
940 -- No type envt from the current module, but we do know the module dependencies
941 initIfaceTc iface do_this
942 = do { tc_env_var <- newMutVar emptyTypeEnv
943 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
944 ; if_lenv = mkIfLclEnv mod doc
946 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
949 mod = mi_module iface
950 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
952 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
953 -- Used when sucking in new Rules in SimplCore
954 -- We have available the type envt of the module being compiled, and we must use it
955 initIfaceRules hsc_env guts do_this
957 type_info = (mg_module guts, return (mg_types guts))
958 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
961 -- Run the thing; any exceptions just bubble out from here
962 ; initTcRnIf 'i' hsc_env gbl_env () do_this
965 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
966 initIfaceLcl mod loc_doc thing_inside
967 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
969 getIfModule :: IfL Module
970 getIfModule = do { env <- getLclEnv; return (if_mod env) }
973 failIfM :: Message -> IfL a
974 -- The Iface monad doesn't have a place to accumulate errors, so we
975 -- just fall over fast if one happens; it "shouldnt happen".
976 -- We use IfL here so that we can get context info out of the local env
978 = do { env <- getLclEnv
979 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
980 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
984 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
985 -- Run thing_inside in an interleaved thread.
986 -- It shares everything with the parent thread, so this is DANGEROUS.
988 -- It returns Nothing if the computation fails
990 -- It's used for lazily type-checking interface
991 -- signatures, which is pretty benign
993 forkM_maybe doc thing_inside
994 = do { unsafeInterleaveM $
995 do { traceIf (text "Starting fork {" <+> doc)
997 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1000 Right r -> do { traceIf (text "} ending fork" <+> doc)
1004 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1005 -- Otherwise we silently discard errors. Errors can legitimately
1006 -- happen when compiling interface signatures (see tcInterfaceSigs)
1007 ifOptM Opt_D_dump_if_trace
1008 (print_errs (hang (text "forkM failed:" <+> doc)
1009 4 (text (show exn))))
1011 ; traceIf (text "} ending fork (badly)" <+> doc)
1015 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1017 forkM :: SDoc -> IfL a -> IfL a
1018 forkM doc thing_inside
1019 = do { mb_res <- forkM_maybe doc thing_inside
1020 ; return (case mb_res of
1021 Nothing -> pgmError "Cannot continue after interface file error"
1022 -- pprPanic "forkM" doc