2 % (c) The University of Glasgow 2006
7 -- The above warning supression flag is a temporary kludge.
8 -- While working on this module you are encouraged to remove it and fix
9 -- any warnings in the module. See
10 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
19 #include "HsVersions.h"
21 import TcRnTypes -- Re-export all
22 import IOEnv -- Re-export all
24 import HsSyn hiding (LIE)
54 import Control.Exception
59 %************************************************************************
63 %************************************************************************
66 ioToTcRn :: IO r -> TcRn r
74 -> Bool -- True <=> retain renamed syntax trees
77 -> IO (Messages, Maybe r)
78 -- Nothing => error thrown by the thing inside
79 -- (error messages should have been printed already)
81 initTc hsc_env hsc_src keep_rn_syntax mod do_this
82 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
83 tvs_var <- newIORef emptyVarSet ;
84 type_env_var <- newIORef emptyNameEnv ;
85 dfuns_var <- newIORef emptyNameSet ;
86 keep_var <- newIORef emptyNameSet ;
87 th_var <- newIORef False ;
88 dfun_n_var <- newIORef 1 ;
90 maybe_rn_syntax empty_val
91 | keep_rn_syntax = Just empty_val
92 | otherwise = Nothing ;
97 tcg_rdr_env = hsc_global_rdr_env hsc_env,
98 tcg_fix_env = emptyNameEnv,
99 tcg_field_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_fam_inst_env = emptyFamInstEnv,
105 tcg_inst_uses = dfuns_var,
106 tcg_th_used = th_var,
108 tcg_imports = emptyImportAvails,
111 tcg_rn_imports = maybe_rn_syntax [],
112 tcg_rn_exports = maybe_rn_syntax [],
113 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
115 tcg_binds = emptyLHsBinds,
116 tcg_deprecs = NoDeprecs,
121 tcg_dfun_n = dfun_n_var,
124 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing,
129 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
131 tcl_rdr = emptyLocalRdrEnv,
132 tcl_th_ctxt = topStage,
133 tcl_arrow_ctxt = NoArrowCtxt,
134 tcl_env = emptyNameEnv,
135 tcl_tyvars = tvs_var,
136 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
140 -- OK, here's the business end!
141 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
142 do { r <- tryM do_this
144 Right res -> return (Just res)
145 Left _ -> return Nothing } ;
147 -- Collect any error messages
148 msgs <- readIORef errs_var ;
150 let { dflags = hsc_dflags hsc_env
151 ; final_res | errorsFound dflags msgs = Nothing
152 | otherwise = maybe_res } ;
154 return (msgs, final_res)
157 initTcPrintErrors -- Used from the interactive loop only
162 initTcPrintErrors env mod todo = do
163 (msgs, res) <- initTc env HsSrcFile False mod todo
164 printErrorsAndWarnings (hsc_dflags env) msgs
168 %************************************************************************
172 %************************************************************************
176 initTcRnIf :: Char -- Tag for unique supply
181 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
182 = do { us <- mkSplitUniqSupply uniq_tag ;
183 ; us_var <- newIORef us ;
185 ; let { env = Env { env_top = hsc_env,
190 ; runIOEnv env thing_inside
194 %************************************************************************
198 %************************************************************************
201 getTopEnv :: TcRnIf gbl lcl HscEnv
202 getTopEnv = do { env <- getEnv; return (env_top env) }
204 getGblEnv :: TcRnIf gbl lcl gbl
205 getGblEnv = do { env <- getEnv; return (env_gbl env) }
207 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
208 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
209 env { env_gbl = upd gbl })
211 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
212 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
214 getLclEnv :: TcRnIf gbl lcl lcl
215 getLclEnv = do { env <- getEnv; return (env_lcl env) }
217 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
218 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
219 env { env_lcl = upd lcl })
221 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
222 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
224 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
225 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
227 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
228 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
235 getDOpts :: TcRnIf gbl lcl DynFlags
236 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
238 doptM :: DynFlag -> TcRnIf gbl lcl Bool
239 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
241 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
242 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
243 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
245 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
246 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
247 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
249 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
250 ifOptM flag thing_inside = do { b <- doptM flag;
251 if b then thing_inside else return () }
253 getGhcMode :: TcRnIf gbl lcl GhcMode
254 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
258 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
259 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
261 getEps :: TcRnIf gbl lcl ExternalPackageState
262 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
264 -- Updating the EPS. This should be an atomic operation.
265 -- Note the delicate 'seq' which forces the EPS before putting it in the
266 -- variable. Otherwise what happens is that we get
267 -- write eps_var (....(unsafeRead eps_var)....)
268 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
269 -- we make the unsafeRead happen before we update the variable.
271 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
273 updateEps upd_fn = do { traceIf (text "updating EPS")
274 ; eps_var <- getEpsVar
275 ; eps <- readMutVar eps_var
276 ; let { (eps', val) = upd_fn eps }
277 ; seq eps' (writeMutVar eps_var eps')
280 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
282 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
283 ; eps_var <- getEpsVar
284 ; eps <- readMutVar eps_var
285 ; let { eps' = upd_fn eps }
286 ; seq eps' (writeMutVar eps_var eps') }
288 getHpt :: TcRnIf gbl lcl HomePackageTable
289 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
291 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
292 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
293 ; return (eps, hsc_HPT env) }
296 %************************************************************************
300 %************************************************************************
303 newUnique :: TcRnIf gbl lcl Unique
305 = do { env <- getEnv ;
306 let { u_var = env_us env } ;
307 us <- readMutVar u_var ;
308 case splitUniqSupply us of { (us1,_) -> do {
309 writeMutVar u_var us1 ;
310 return $! uniqFromSupply us }}}
311 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
312 -- a chain of unevaluated supplies behind.
313 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
314 -- throw away one half of the new split supply. This is safe because this
315 -- is the only place we use that unique. Using the other half of the split
316 -- supply is safer, but slower.
318 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
320 = do { env <- getEnv ;
321 let { u_var = env_us env } ;
322 us <- readMutVar u_var ;
323 case splitUniqSupply us of { (us1,us2) -> do {
324 writeMutVar u_var us1 ;
327 newLocalName :: Name -> TcRnIf gbl lcl Name
328 newLocalName name -- Make a clone
329 = do { uniq <- newUnique
330 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
332 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
333 newSysLocalIds fs tys
334 = do { us <- newUniqueSupply
335 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
339 %************************************************************************
343 %************************************************************************
346 traceTc, traceRn :: SDoc -> TcRn ()
347 traceRn = traceOptTcRn Opt_D_dump_rn_trace
348 traceTc = traceOptTcRn Opt_D_dump_tc_trace
349 traceSplice = traceOptTcRn Opt_D_dump_splices
352 traceIf :: SDoc -> TcRnIf m n ()
353 traceIf = traceOptIf Opt_D_dump_if_trace
354 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
357 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
358 traceOptIf flag doc = ifOptM flag $
359 ioToIOEnv (printForUser stderr alwaysQualify doc)
361 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
362 traceOptTcRn flag doc = ifOptM flag $ do
365 ; env0 <- tcInitTidyEnv
366 ; ctxt_msgs <- do_ctxt env0 ctxt
367 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
368 ; dumpTcRn real_doc }
370 dumpTcRn :: SDoc -> TcRn ()
371 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
373 ioToTcRn (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
375 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
376 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
380 %************************************************************************
382 Typechecker global environment
384 %************************************************************************
387 getModule :: TcRn Module
388 getModule = do { env <- getGblEnv; return (tcg_mod env) }
390 setModule :: Module -> TcRn a -> TcRn a
391 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
393 tcIsHsBoot :: TcRn Bool
394 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
396 getGlobalRdrEnv :: TcRn GlobalRdrEnv
397 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
399 getImports :: TcRn ImportAvails
400 getImports = do { env <- getGblEnv; return (tcg_imports env) }
402 getFixityEnv :: TcRn FixityEnv
403 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
405 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
406 extendFixityEnv new_bit
407 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
408 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
410 getRecFieldEnv :: TcRn RecFieldEnv
411 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
413 extendRecFieldEnv :: RecFieldEnv -> RnM a -> RnM a
414 extendRecFieldEnv new_bit
415 = updGblEnv (\env@(TcGblEnv { tcg_field_env = old_env }) ->
416 env {tcg_field_env = old_env `plusNameEnv` new_bit})
418 getDeclaredDefaultTys :: TcRn (Maybe [Type])
419 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
422 %************************************************************************
426 %************************************************************************
429 getSrcSpanM :: TcRn SrcSpan
430 -- Avoid clash with Name.getSrcLoc
431 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
433 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
434 setSrcSpan loc thing_inside
435 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
436 | otherwise = thing_inside -- Don't overwrite useful info with useless
438 addLocM :: (a -> TcM b) -> Located a -> TcM b
439 addLocM fn (L loc a) = setSrcSpan loc $ fn a
441 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
442 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
444 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
445 wrapLocFstM fn (L loc a) =
450 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
451 wrapLocSndM fn (L loc a) =
459 getErrsVar :: TcRn (TcRef Messages)
460 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
462 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
463 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
465 addErr :: Message -> TcRn ()
466 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
468 addLocErr :: Located e -> (e -> Message) -> TcRn ()
469 addLocErr (L loc e) fn = addErrAt loc (fn e)
471 addErrAt :: SrcSpan -> Message -> TcRn ()
472 addErrAt loc msg = addLongErrAt loc msg empty
474 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
475 addLongErrAt loc msg extra
476 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
477 errs_var <- getErrsVar ;
478 rdr_env <- getGlobalRdrEnv ;
480 let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
481 (warns, errs) <- readMutVar errs_var ;
482 writeMutVar errs_var (warns, errs `snocBag` err) }
484 addErrs :: [(SrcSpan,Message)] -> TcRn ()
485 addErrs msgs = mappM_ add msgs
487 add (loc,msg) = addErrAt loc msg
489 addReport :: Message -> TcRn ()
490 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
492 addReportAt :: SrcSpan -> Message -> TcRn ()
494 = do { errs_var <- getErrsVar ;
495 rdr_env <- getGlobalRdrEnv ;
497 let { warn = mkWarnMsg loc (mkPrintUnqualified dflags rdr_env) msg } ;
498 (warns, errs) <- readMutVar errs_var ;
499 writeMutVar errs_var (warns `snocBag` warn, errs) }
501 addWarn :: Message -> TcRn ()
502 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
504 addWarnAt :: SrcSpan -> Message -> TcRn ()
505 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
507 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
508 addLocWarn (L loc e) fn = addReportAt loc (fn e)
510 checkErr :: Bool -> Message -> TcRn ()
511 -- Add the error if the bool is False
512 checkErr ok msg = checkM ok (addErr msg)
514 warnIf :: Bool -> Message -> TcRn ()
515 warnIf True msg = addWarn msg
516 warnIf False msg = return ()
518 addMessages :: Messages -> TcRn ()
519 addMessages (m_warns, m_errs)
520 = do { errs_var <- getErrsVar ;
521 (warns, errs) <- readMutVar errs_var ;
522 writeMutVar errs_var (warns `unionBags` m_warns,
523 errs `unionBags` m_errs) }
525 discardWarnings :: TcRn a -> TcRn a
526 -- Ignore warnings inside the thing inside;
527 -- used to ignore-unused-variable warnings inside derived code
528 -- With -dppr-debug, the effects is switched off, so you can still see
529 -- what warnings derived code would give
530 discardWarnings thing_inside
531 | opt_PprStyle_Debug = thing_inside
533 = do { errs_var <- newMutVar emptyMessages
534 ; result <- setErrsVar errs_var thing_inside
535 ; (_warns, errs) <- readMutVar errs_var
536 ; addMessages (emptyBag, errs)
542 try_m :: TcRn r -> TcRn (Either Exception r)
543 -- Does try_m, with a debug-trace on failure
545 = do { mb_r <- tryM thing ;
547 Left exn -> do { traceTc (exn_msg exn); return mb_r }
548 Right r -> return mb_r }
550 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
552 -----------------------
553 recoverM :: TcRn r -- Recovery action; do this if the main one fails
554 -> TcRn r -- Main action: do this first
556 -- Errors in 'thing' are retained
557 recoverM recover thing
558 = do { mb_res <- try_m thing ;
561 Right res -> returnM res }
563 -----------------------
564 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
565 -- (tryTc m) executes m, and returns
566 -- Just r, if m succeeds (returning r)
567 -- Nothing, if m fails
568 -- It also returns all the errors and warnings accumulated by m
569 -- It always succeeds (never raises an exception)
571 = do { errs_var <- newMutVar emptyMessages ;
572 res <- try_m (setErrsVar errs_var m) ;
573 msgs <- readMutVar errs_var ;
574 return (msgs, case res of
576 Right val -> Just val)
577 -- The exception is always the IOEnv built-in
578 -- in exception; see IOEnv.failM
581 -----------------------
582 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
583 -- Run the thing, returning
584 -- Just r, if m succceeds with no error messages
585 -- Nothing, if m fails, or if it succeeds but has error messages
586 -- Either way, the messages are returned; even in the Just case
587 -- there might be warnings
589 = do { (msgs, res) <- tryTc thing
591 ; let errs_found = errorsFound dflags msgs
592 ; return (msgs, case res of
594 Just val | errs_found -> Nothing
595 | otherwise -> Just val)
598 -----------------------
599 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
600 -- Just like tryTcErrs, except that it ensures that the LIE
601 -- for the thing is propagated only if there are no errors
602 -- Hence it's restricted to the type-check monad
603 tryTcLIE thing_inside
604 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
606 Nothing -> return (msgs, Nothing)
607 Just val -> do { extendLIEs lie; return (msgs, Just val) }
610 -----------------------
611 tryTcLIE_ :: TcM r -> TcM r -> TcM r
612 -- (tryTcLIE_ r m) tries m;
613 -- if m succeeds with no error messages, it's the answer
614 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
615 tryTcLIE_ recover main
616 = do { (msgs, mb_res) <- tryTcLIE main
618 Just val -> do { addMessages msgs -- There might be warnings
620 Nothing -> recover -- Discard all msgs
623 -----------------------
624 checkNoErrs :: TcM r -> TcM r
625 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
626 -- If m fails then (checkNoErrsTc m) fails.
627 -- If m succeeds, it checks whether m generated any errors messages
628 -- (it might have recovered internally)
629 -- If so, it fails too.
630 -- Regardless, any errors generated by m are propagated to the enclosing context.
632 = do { (msgs, mb_res) <- tryTcLIE main
636 Just val -> return val
639 ifErrsM :: TcRn r -> TcRn r -> TcRn r
640 -- ifErrsM bale_out main
641 -- does 'bale_out' if there are errors in errors collection
642 -- otherwise does 'main'
643 ifErrsM bale_out normal
644 = do { errs_var <- getErrsVar ;
645 msgs <- readMutVar errs_var ;
647 if errorsFound dflags msgs then
652 failIfErrsM :: TcRn ()
653 -- Useful to avoid error cascades
654 failIfErrsM = ifErrsM failM (return ())
658 %************************************************************************
660 Context management and error message generation
663 %************************************************************************
666 getErrCtxt :: TcM ErrCtxt
667 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
669 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
670 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
672 addErrCtxt :: Message -> TcM a -> TcM a
673 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
675 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
676 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
678 -- Helper function for the above
679 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
680 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
681 env { tcl_ctxt = upd ctxt })
683 -- Conditionally add an error context
684 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
685 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
686 maybeAddErrCtxt Nothing thing_inside = thing_inside
688 popErrCtxt :: TcM a -> TcM a
689 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
691 getInstLoc :: InstOrigin -> TcM InstLoc
693 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
694 return (InstLoc origin loc (tcl_ctxt env)) }
696 addInstCtxt :: InstLoc -> TcM a -> TcM a
697 -- Add the SrcSpan and context from the first Inst in the list
698 -- (they all have similar locations)
699 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
700 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
703 The addErrTc functions add an error message, but do not cause failure.
704 The 'M' variants pass a TidyEnv that has already been used to
705 tidy up the message; we then use it to tidy the context messages
708 addErrTc :: Message -> TcM ()
709 addErrTc err_msg = do { env0 <- tcInitTidyEnv
710 ; addErrTcM (env0, err_msg) }
712 addErrsTc :: [Message] -> TcM ()
713 addErrsTc err_msgs = mappM_ addErrTc err_msgs
715 addErrTcM :: (TidyEnv, Message) -> TcM ()
716 addErrTcM (tidy_env, err_msg)
717 = do { ctxt <- getErrCtxt ;
719 add_err_tcm tidy_env err_msg loc ctxt }
722 The failWith functions add an error message and cause failure
725 failWithTc :: Message -> TcM a -- Add an error message and fail
727 = addErrTc err_msg >> failM
729 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
730 failWithTcM local_and_msg
731 = addErrTcM local_and_msg >> failM
733 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
734 checkTc True err = returnM ()
735 checkTc False err = failWithTc err
738 Warnings have no 'M' variant, nor failure
741 addWarnTc :: Message -> TcM ()
742 addWarnTc msg = do { env0 <- tcInitTidyEnv
743 ; addWarnTcM (env0, msg) }
745 addWarnTcM :: (TidyEnv, Message) -> TcM ()
746 addWarnTcM (env0, msg)
747 = do { ctxt <- getErrCtxt ;
748 ctxt_msgs <- do_ctxt env0 ctxt ;
749 addReport (vcat (ptext SLIT("Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
751 warnTc :: Bool -> Message -> TcM ()
752 warnTc warn_if_true warn_msg
753 | warn_if_true = addWarnTc warn_msg
754 | otherwise = return ()
757 -----------------------------------
760 We initialise the "tidy-env", used for tidying types before printing,
761 by building a reverse map from the in-scope type variables to the
762 OccName that the programmer originally used for them
765 tcInitTidyEnv :: TcM TidyEnv
767 = do { lcl_env <- getLclEnv
768 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
769 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
771 ; return (foldl add emptyTidyEnv nm_tv_prs) }
773 add (env,subst) (name, tyvar)
774 = case tidyOccName env (nameOccName name) of
775 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
777 tyvar' = setTyVarName tyvar name'
778 name' = tidyNameOcc name occ'
781 -----------------------------------
782 Other helper functions
785 add_err_tcm tidy_env err_msg loc ctxt
786 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
787 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
791 do_ctxt tidy_env (c:cs)
792 = do { (tidy_env', m) <- c tidy_env ;
793 ms <- do_ctxt tidy_env' cs ;
796 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
797 | otherwise = take 3 ctxt
800 debugTc is useful for monadic debugging code
803 debugTc :: TcM () -> TcM ()
805 debugTc thing = thing
807 debugTc thing = return ()
811 %************************************************************************
813 Type constraints (the so-called LIE)
815 %************************************************************************
818 nextDFunIndex :: TcM Int -- Get the next dfun index
819 nextDFunIndex = do { env <- getGblEnv
820 ; let dfun_n_var = tcg_dfun_n env
821 ; n <- readMutVar dfun_n_var
822 ; writeMutVar dfun_n_var (n+1)
825 getLIEVar :: TcM (TcRef LIE)
826 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
828 setLIEVar :: TcRef LIE -> TcM a -> TcM a
829 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
831 getLIE :: TcM a -> TcM (a, [Inst])
832 -- (getLIE m) runs m, and returns the type constraints it generates
834 = do { lie_var <- newMutVar emptyLIE ;
835 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
837 lie <- readMutVar lie_var ;
838 return (res, lieToList lie) }
840 extendLIE :: Inst -> TcM ()
842 = do { lie_var <- getLIEVar ;
843 lie <- readMutVar lie_var ;
844 writeMutVar lie_var (inst `consLIE` lie) }
846 extendLIEs :: [Inst] -> TcM ()
850 = do { lie_var <- getLIEVar ;
851 lie <- readMutVar lie_var ;
852 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
856 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
857 -- Set the local type envt, but do *not* disturb other fields,
858 -- notably the lie_var
859 setLclTypeEnv lcl_env thing_inside
860 = updLclEnv upd thing_inside
862 upd env = env { tcl_env = tcl_env lcl_env,
863 tcl_tyvars = tcl_tyvars lcl_env }
867 %************************************************************************
869 Template Haskell context
871 %************************************************************************
874 recordThUse :: TcM ()
875 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
877 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
878 keepAliveTc n = do { env <- getGblEnv;
879 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
881 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
882 keepAliveSetTc ns = do { env <- getGblEnv;
883 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
885 getStage :: TcM ThStage
886 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
888 setStage :: ThStage -> TcM a -> TcM a
889 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
893 %************************************************************************
895 Stuff for the renamer's local env
897 %************************************************************************
900 getLocalRdrEnv :: RnM LocalRdrEnv
901 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
903 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
904 setLocalRdrEnv rdr_env thing_inside
905 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
909 %************************************************************************
911 Stuff for interface decls
913 %************************************************************************
916 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
917 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
919 if_tv_env = emptyOccEnv,
920 if_id_env = emptyOccEnv }
922 initIfaceTcRn :: IfG a -> TcRn a
923 initIfaceTcRn thing_inside
924 = do { tcg_env <- getGblEnv
925 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
926 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
927 ; setEnvs (if_env, ()) thing_inside }
929 initIfaceExtCore :: IfL a -> TcRn a
930 initIfaceExtCore thing_inside
931 = do { tcg_env <- getGblEnv
932 ; let { mod = tcg_mod tcg_env
933 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
934 ; if_env = IfGblEnv {
935 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
936 ; if_lenv = mkIfLclEnv mod doc
938 ; setEnvs (if_env, if_lenv) thing_inside }
940 initIfaceCheck :: HscEnv -> IfG a -> IO a
941 -- Used when checking the up-to-date-ness of the old Iface
942 -- Initialise the environment with no useful info at all
943 initIfaceCheck hsc_env do_this
944 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
945 ; initTcRnIf 'i' hsc_env gbl_env () do_this
948 initIfaceTc :: ModIface
949 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
950 -- Used when type-checking checking an up-to-date interface file
951 -- No type envt from the current module, but we do know the module dependencies
952 initIfaceTc iface do_this
953 = do { tc_env_var <- newMutVar emptyTypeEnv
954 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
955 ; if_lenv = mkIfLclEnv mod doc
957 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
960 mod = mi_module iface
961 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
963 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
964 -- Used when sucking in new Rules in SimplCore
965 -- We have available the type envt of the module being compiled, and we must use it
966 initIfaceRules hsc_env guts do_this
968 type_info = (mg_module guts, return (mg_types guts))
969 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
972 -- Run the thing; any exceptions just bubble out from here
973 ; initTcRnIf 'i' hsc_env gbl_env () do_this
976 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
977 initIfaceLcl mod loc_doc thing_inside
978 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
980 getIfModule :: IfL Module
981 getIfModule = do { env <- getLclEnv; return (if_mod env) }
984 failIfM :: Message -> IfL a
985 -- The Iface monad doesn't have a place to accumulate errors, so we
986 -- just fall over fast if one happens; it "shouldnt happen".
987 -- We use IfL here so that we can get context info out of the local env
989 = do { env <- getLclEnv
990 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
991 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
995 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
996 -- Run thing_inside in an interleaved thread.
997 -- It shares everything with the parent thread, so this is DANGEROUS.
999 -- It returns Nothing if the computation fails
1001 -- It's used for lazily type-checking interface
1002 -- signatures, which is pretty benign
1004 forkM_maybe doc thing_inside
1005 = do { unsafeInterleaveM $
1006 do { traceIf (text "Starting fork {" <+> doc)
1008 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1011 Right r -> do { traceIf (text "} ending fork" <+> doc)
1015 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1016 -- Otherwise we silently discard errors. Errors can legitimately
1017 -- happen when compiling interface signatures (see tcInterfaceSigs)
1018 ifOptM Opt_D_dump_if_trace
1019 (print_errs (hang (text "forkM failed:" <+> doc)
1020 4 (text (show exn))))
1022 ; traceIf (text "} ending fork (badly)" <+> doc)
1026 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1028 forkM :: SDoc -> IfL a -> IfL a
1029 forkM doc thing_inside
1030 = do { mb_res <- forkM_maybe doc thing_inside
1031 ; return (case mb_res of
1032 Nothing -> pgmError "Cannot continue after interface file error"
1033 -- pprPanic "forkM" doc