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)
56 import Control.Exception
62 %************************************************************************
66 %************************************************************************
72 -> Bool -- True <=> retain renamed syntax trees
75 -> IO (Messages, Maybe r)
76 -- Nothing => error thrown by the thing inside
77 -- (error messages should have been printed already)
79 initTc hsc_env hsc_src keep_rn_syntax mod do_this
80 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
81 tvs_var <- newIORef emptyVarSet ;
82 type_env_var <- newIORef emptyNameEnv ;
83 dfuns_var <- newIORef emptyNameSet ;
84 keep_var <- newIORef emptyNameSet ;
85 th_var <- newIORef False ;
86 dfun_n_var <- newIORef 1 ;
88 maybe_rn_syntax empty_val
89 | keep_rn_syntax = Just empty_val
90 | otherwise = Nothing ;
95 tcg_rdr_env = hsc_global_rdr_env hsc_env,
96 tcg_fix_env = emptyNameEnv,
97 tcg_field_env = emptyNameEnv,
98 tcg_default = Nothing,
99 tcg_type_env = hsc_global_type_env hsc_env,
100 tcg_type_env_var = type_env_var,
101 tcg_inst_env = emptyInstEnv,
102 tcg_fam_inst_env = emptyFamInstEnv,
103 tcg_inst_uses = dfuns_var,
104 tcg_th_used = th_var,
106 tcg_imports = emptyImportAvails,
109 tcg_rn_imports = maybe_rn_syntax [],
110 tcg_rn_exports = maybe_rn_syntax [],
111 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
113 tcg_binds = emptyLHsBinds,
114 tcg_deprecs = NoDeprecs,
119 tcg_dfun_n = dfun_n_var,
122 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing,
127 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
129 tcl_rdr = emptyLocalRdrEnv,
130 tcl_th_ctxt = topStage,
131 tcl_arrow_ctxt = NoArrowCtxt,
132 tcl_env = emptyNameEnv,
133 tcl_tyvars = tvs_var,
134 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
138 -- OK, here's the business end!
139 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
140 do { r <- tryM do_this
142 Right res -> return (Just res)
143 Left _ -> return Nothing } ;
145 -- Collect any error messages
146 msgs <- readIORef errs_var ;
148 let { dflags = hsc_dflags hsc_env
149 ; final_res | errorsFound dflags msgs = Nothing
150 | otherwise = maybe_res } ;
152 return (msgs, final_res)
155 initTcPrintErrors -- Used from the interactive loop only
160 initTcPrintErrors env mod todo = do
161 (msgs, res) <- initTc env HsSrcFile False mod todo
162 printErrorsAndWarnings (hsc_dflags env) msgs
166 %************************************************************************
170 %************************************************************************
174 initTcRnIf :: Char -- Tag for unique supply
179 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
180 = do { us <- mkSplitUniqSupply uniq_tag ;
181 ; us_var <- newIORef us ;
183 ; let { env = Env { env_top = hsc_env,
188 ; runIOEnv env thing_inside
192 %************************************************************************
196 %************************************************************************
199 getTopEnv :: TcRnIf gbl lcl HscEnv
200 getTopEnv = do { env <- getEnv; return (env_top env) }
202 getGblEnv :: TcRnIf gbl lcl gbl
203 getGblEnv = do { env <- getEnv; return (env_gbl env) }
205 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
206 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
207 env { env_gbl = upd gbl })
209 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
210 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
212 getLclEnv :: TcRnIf gbl lcl lcl
213 getLclEnv = do { env <- getEnv; return (env_lcl env) }
215 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
216 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
217 env { env_lcl = upd lcl })
219 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
220 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
222 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
223 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
225 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
226 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
233 getDOpts :: TcRnIf gbl lcl DynFlags
234 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
236 doptM :: DynFlag -> TcRnIf gbl lcl Bool
237 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
239 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
240 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
241 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
243 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
244 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
245 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
247 -- | Do it flag is true
248 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
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) (getSrcSpan 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 liftIO (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 ;
372 liftIO (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
374 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
375 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
379 %************************************************************************
381 Typechecker global environment
383 %************************************************************************
386 getModule :: TcRn Module
387 getModule = do { env <- getGblEnv; return (tcg_mod env) }
389 setModule :: Module -> TcRn a -> TcRn a
390 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
392 tcIsHsBoot :: TcRn Bool
393 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
395 getGlobalRdrEnv :: TcRn GlobalRdrEnv
396 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
398 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
399 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
401 getImports :: TcRn ImportAvails
402 getImports = do { env <- getGblEnv; return (tcg_imports env) }
404 getFixityEnv :: TcRn FixityEnv
405 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
407 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
408 extendFixityEnv new_bit
409 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
410 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
412 getRecFieldEnv :: TcRn RecFieldEnv
413 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
415 extendRecFieldEnv :: RecFieldEnv -> RnM a -> RnM a
416 extendRecFieldEnv new_bit
417 = updGblEnv (\env@(TcGblEnv { tcg_field_env = old_env }) ->
418 env {tcg_field_env = old_env `plusNameEnv` new_bit})
420 getDeclaredDefaultTys :: TcRn (Maybe [Type])
421 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
424 %************************************************************************
428 %************************************************************************
431 getSrcSpanM :: TcRn SrcSpan
432 -- Avoid clash with Name.getSrcLoc
433 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
435 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
436 setSrcSpan loc thing_inside
437 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
438 | otherwise = thing_inside -- Don't overwrite useful info with useless
440 addLocM :: (a -> TcM b) -> Located a -> TcM b
441 addLocM fn (L loc a) = setSrcSpan loc $ fn a
443 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
444 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
446 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
447 wrapLocFstM fn (L loc a) =
452 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
453 wrapLocSndM fn (L loc a) =
461 getErrsVar :: TcRn (TcRef Messages)
462 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
464 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
465 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
467 addErr :: Message -> TcRn ()
468 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
470 addLocErr :: Located e -> (e -> Message) -> TcRn ()
471 addLocErr (L loc e) fn = addErrAt loc (fn e)
473 addErrAt :: SrcSpan -> Message -> TcRn ()
474 addErrAt loc msg = addLongErrAt loc msg empty
476 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
477 addLongErrAt loc msg extra
478 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
479 errs_var <- getErrsVar ;
480 rdr_env <- getGlobalRdrEnv ;
482 let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
483 (warns, errs) <- readMutVar errs_var ;
484 writeMutVar errs_var (warns, errs `snocBag` err) }
486 addErrs :: [(SrcSpan,Message)] -> TcRn ()
487 addErrs msgs = mapM_ add msgs
489 add (loc,msg) = addErrAt loc msg
491 addReport :: Message -> TcRn ()
492 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
494 addReportAt :: SrcSpan -> Message -> TcRn ()
496 = do { errs_var <- getErrsVar ;
497 rdr_env <- getGlobalRdrEnv ;
499 let { warn = mkWarnMsg loc (mkPrintUnqualified dflags rdr_env) msg } ;
500 (warns, errs) <- readMutVar errs_var ;
501 writeMutVar errs_var (warns `snocBag` warn, errs) }
503 addWarn :: Message -> TcRn ()
504 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
506 addWarnAt :: SrcSpan -> Message -> TcRn ()
507 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
509 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
510 addLocWarn (L loc e) fn = addReportAt loc (fn e)
512 checkErr :: Bool -> Message -> TcRn ()
513 -- Add the error if the bool is False
514 checkErr ok msg = unless ok (addErr msg)
516 warnIf :: Bool -> Message -> TcRn ()
517 warnIf True msg = addWarn msg
518 warnIf False msg = return ()
520 addMessages :: Messages -> TcRn ()
521 addMessages (m_warns, m_errs)
522 = do { errs_var <- getErrsVar ;
523 (warns, errs) <- readMutVar errs_var ;
524 writeMutVar errs_var (warns `unionBags` m_warns,
525 errs `unionBags` m_errs) }
527 discardWarnings :: TcRn a -> TcRn a
528 -- Ignore warnings inside the thing inside;
529 -- used to ignore-unused-variable warnings inside derived code
530 -- With -dppr-debug, the effects is switched off, so you can still see
531 -- what warnings derived code would give
532 discardWarnings thing_inside
533 | opt_PprStyle_Debug = thing_inside
535 = do { errs_var <- newMutVar emptyMessages
536 ; result <- setErrsVar errs_var thing_inside
537 ; (_warns, errs) <- readMutVar errs_var
538 ; addMessages (emptyBag, errs)
544 try_m :: TcRn r -> TcRn (Either Exception r)
545 -- Does try_m, with a debug-trace on failure
547 = do { mb_r <- tryM thing ;
549 Left exn -> do { traceTc (exn_msg exn); return mb_r }
550 Right r -> return mb_r }
552 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
554 -----------------------
555 recoverM :: TcRn r -- Recovery action; do this if the main one fails
556 -> TcRn r -- Main action: do this first
558 -- Errors in 'thing' are retained
559 recoverM recover thing
560 = do { mb_res <- try_m thing ;
563 Right res -> return res }
566 -----------------------
567 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
568 -- Drop elements of the input that fail, so the result
569 -- list can be shorter than the argument list
570 mapAndRecoverM f [] = return []
571 mapAndRecoverM f (x:xs) = do { mb_r <- tryM (f x)
572 ; rs <- mapAndRecoverM f xs
573 ; return (case mb_r of
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 -> return (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 = mapM_ 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 = return ()
750 checkTc False err = failWithTc err
753 Warnings have no 'M' variant, nor failure
756 addWarnTc :: Message -> TcM ()
757 addWarnTc msg = do { env0 <- tcInitTidyEnv
758 ; addWarnTcM (env0, msg) }
760 addWarnTcM :: (TidyEnv, Message) -> TcM ()
761 addWarnTcM (env0, msg)
762 = do { ctxt <- getErrCtxt ;
763 ctxt_msgs <- do_ctxt env0 ctxt ;
764 addReport (vcat (ptext SLIT("Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
766 warnTc :: Bool -> Message -> TcM ()
767 warnTc warn_if_true warn_msg
768 | warn_if_true = addWarnTc warn_msg
769 | otherwise = return ()
772 -----------------------------------
775 We initialise the "tidy-env", used for tidying types before printing,
776 by building a reverse map from the in-scope type variables to the
777 OccName that the programmer originally used for them
780 tcInitTidyEnv :: TcM TidyEnv
782 = do { lcl_env <- getLclEnv
783 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
784 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
786 ; return (foldl add emptyTidyEnv nm_tv_prs) }
788 add (env,subst) (name, tyvar)
789 = case tidyOccName env (nameOccName name) of
790 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
792 tyvar' = setTyVarName tyvar name'
793 name' = tidyNameOcc name occ'
796 -----------------------------------
797 Other helper functions
800 add_err_tcm tidy_env err_msg loc ctxt
801 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
802 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
806 do_ctxt tidy_env (c:cs)
807 = do { (tidy_env', m) <- c tidy_env ;
808 ms <- do_ctxt tidy_env' cs ;
811 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
812 | otherwise = take 3 ctxt
815 debugTc is useful for monadic debugging code
818 debugTc :: TcM () -> TcM ()
821 | otherwise = return ()
824 %************************************************************************
826 Type constraints (the so-called LIE)
828 %************************************************************************
831 nextDFunIndex :: TcM Int -- Get the next dfun index
832 nextDFunIndex = do { env <- getGblEnv
833 ; let dfun_n_var = tcg_dfun_n env
834 ; n <- readMutVar dfun_n_var
835 ; writeMutVar dfun_n_var (n+1)
838 getLIEVar :: TcM (TcRef LIE)
839 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
841 setLIEVar :: TcRef LIE -> TcM a -> TcM a
842 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
844 getLIE :: TcM a -> TcM (a, [Inst])
845 -- (getLIE m) runs m, and returns the type constraints it generates
847 = do { lie_var <- newMutVar emptyLIE ;
848 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
850 lie <- readMutVar lie_var ;
851 return (res, lieToList lie) }
853 extendLIE :: Inst -> TcM ()
855 = do { lie_var <- getLIEVar ;
856 lie <- readMutVar lie_var ;
857 writeMutVar lie_var (inst `consLIE` lie) }
859 extendLIEs :: [Inst] -> TcM ()
863 = do { lie_var <- getLIEVar ;
864 lie <- readMutVar lie_var ;
865 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
869 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
870 -- Set the local type envt, but do *not* disturb other fields,
871 -- notably the lie_var
872 setLclTypeEnv lcl_env thing_inside
873 = updLclEnv upd thing_inside
875 upd env = env { tcl_env = tcl_env lcl_env,
876 tcl_tyvars = tcl_tyvars lcl_env }
880 %************************************************************************
882 Template Haskell context
884 %************************************************************************
887 recordThUse :: TcM ()
888 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
890 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
892 | isLocalId id = do { env <- getGblEnv;
893 ; updMutVar (tcg_keep env) (`addOneToNameSet` idName id) }
894 | otherwise = return ()
896 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
897 keepAliveSetTc ns = do { env <- getGblEnv;
898 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
900 getStage :: TcM ThStage
901 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
903 setStage :: ThStage -> TcM a -> TcM a
904 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
908 %************************************************************************
910 Stuff for the renamer's local env
912 %************************************************************************
915 getLocalRdrEnv :: RnM LocalRdrEnv
916 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
918 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
919 setLocalRdrEnv rdr_env thing_inside
920 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
924 %************************************************************************
926 Stuff for interface decls
928 %************************************************************************
931 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
932 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
934 if_tv_env = emptyUFM,
935 if_id_env = emptyUFM }
937 initIfaceTcRn :: IfG a -> TcRn a
938 initIfaceTcRn thing_inside
939 = do { tcg_env <- getGblEnv
940 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
941 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
942 ; setEnvs (if_env, ()) thing_inside }
944 initIfaceExtCore :: IfL a -> TcRn a
945 initIfaceExtCore thing_inside
946 = do { tcg_env <- getGblEnv
947 ; let { mod = tcg_mod tcg_env
948 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
949 ; if_env = IfGblEnv {
950 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
951 ; if_lenv = mkIfLclEnv mod doc
953 ; setEnvs (if_env, if_lenv) thing_inside }
955 initIfaceCheck :: HscEnv -> IfG a -> IO a
956 -- Used when checking the up-to-date-ness of the old Iface
957 -- Initialise the environment with no useful info at all
958 initIfaceCheck hsc_env do_this
959 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
960 ; initTcRnIf 'i' hsc_env gbl_env () do_this
963 initIfaceTc :: ModIface
964 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
965 -- Used when type-checking checking an up-to-date interface file
966 -- No type envt from the current module, but we do know the module dependencies
967 initIfaceTc iface do_this
968 = do { tc_env_var <- newMutVar emptyTypeEnv
969 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
970 ; if_lenv = mkIfLclEnv mod doc
972 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
975 mod = mi_module iface
976 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
978 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
979 -- Used when sucking in new Rules in SimplCore
980 -- We have available the type envt of the module being compiled, and we must use it
981 initIfaceRules hsc_env guts do_this
983 type_info = (mg_module guts, return (mg_types guts))
984 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
987 -- Run the thing; any exceptions just bubble out from here
988 ; initTcRnIf 'i' hsc_env gbl_env () do_this
991 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
992 initIfaceLcl mod loc_doc thing_inside
993 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
995 getIfModule :: IfL Module
996 getIfModule = do { env <- getLclEnv; return (if_mod env) }
999 failIfM :: Message -> IfL a
1000 -- The Iface monad doesn't have a place to accumulate errors, so we
1001 -- just fall over fast if one happens; it "shouldnt happen".
1002 -- We use IfL here so that we can get context info out of the local env
1004 = do { env <- getLclEnv
1005 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1006 ; liftIO (printErrs (full_msg defaultErrStyle))
1009 --------------------
1010 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1011 -- Run thing_inside in an interleaved thread.
1012 -- It shares everything with the parent thread, so this is DANGEROUS.
1014 -- It returns Nothing if the computation fails
1016 -- It's used for lazily type-checking interface
1017 -- signatures, which is pretty benign
1019 forkM_maybe doc thing_inside
1020 = do { unsafeInterleaveM $
1021 do { traceIf (text "Starting fork {" <+> doc)
1023 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1026 Right r -> do { traceIf (text "} ending fork" <+> doc)
1030 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1031 -- Otherwise we silently discard errors. Errors can legitimately
1032 -- happen when compiling interface signatures (see tcInterfaceSigs)
1033 ifOptM Opt_D_dump_if_trace
1034 (print_errs (hang (text "forkM failed:" <+> doc)
1035 4 (text (show exn))))
1037 ; traceIf (text "} ending fork (badly)" <+> doc)
1041 print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1043 forkM :: SDoc -> IfL a -> IfL a
1044 forkM doc thing_inside
1045 = do { mb_res <- forkM_maybe doc thing_inside
1046 ; return (case mb_res of
1047 Nothing -> pgmError "Cannot continue after interface file error"
1048 -- pprPanic "forkM" doc