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)
47 import qualified Data.Set as Set
53 %************************************************************************
57 %************************************************************************
63 -> Bool -- True <=> retain renamed syntax trees
66 -> IO (Messages, Maybe r)
67 -- Nothing => error thrown by the thing inside
68 -- (error messages should have been printed already)
70 initTc hsc_env hsc_src keep_rn_syntax mod do_this
71 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
72 tvs_var <- newIORef emptyVarSet ;
73 dfuns_var <- newIORef emptyNameSet ;
74 keep_var <- newIORef emptyNameSet ;
75 used_rdr_var <- newIORef Set.empty ;
76 th_var <- newIORef False ;
77 lie_var <- newIORef emptyBag ;
78 dfun_n_var <- newIORef emptyOccSet ;
79 type_env_var <- case hsc_type_env_var hsc_env of {
80 Just (_mod, te_var) -> return te_var ;
81 Nothing -> newIORef emptyNameEnv } ;
83 maybe_rn_syntax :: forall a. a -> Maybe a ;
84 maybe_rn_syntax empty_val
85 | keep_rn_syntax = Just empty_val
86 | otherwise = Nothing ;
91 tcg_rdr_env = hsc_global_rdr_env hsc_env,
92 tcg_fix_env = emptyNameEnv,
93 tcg_field_env = RecFields emptyNameEnv emptyNameSet,
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,
103 tcg_used_rdrnames = used_rdr_var,
107 tcg_rn_exports = maybe_rn_syntax [],
108 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
110 tcg_binds = emptyLHsBinds,
111 tcg_sigs = emptyNameSet,
112 tcg_ev_binds = emptyBag,
113 tcg_warns = NoWarnings,
119 tcg_dfun_n = dfun_n_var,
121 tcg_doc_hdr = 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,
135 tcl_untch = emptyVarSet
139 -- OK, here's the business end!
140 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
141 do { r <- tryM do_this
143 Right res -> return (Just res)
144 Left _ -> return Nothing } ;
146 -- Check for unsolved constraints
147 lie <- readIORef lie_var ;
150 else pprPanic "initTc: unsolved constraints"
151 (pprWantedsWithLocs lie) ;
153 -- Collect any error messages
154 msgs <- readIORef errs_var ;
156 let { dflags = hsc_dflags hsc_env
157 ; final_res | errorsFound dflags msgs = Nothing
158 | otherwise = maybe_res } ;
160 return (msgs, final_res)
163 initTcPrintErrors -- Used from the interactive loop only
167 -> IO (Messages, Maybe r)
168 initTcPrintErrors env mod todo = do
169 (msgs, res) <- initTc env HsSrcFile False mod todo
173 %************************************************************************
177 %************************************************************************
181 initTcRnIf :: Char -- Tag for unique supply
186 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
187 = do { us <- mkSplitUniqSupply uniq_tag ;
188 ; us_var <- newIORef us ;
190 ; let { env = Env { env_top = hsc_env,
195 ; runIOEnv env thing_inside
199 %************************************************************************
203 %************************************************************************
206 getTopEnv :: TcRnIf gbl lcl HscEnv
207 getTopEnv = do { env <- getEnv; return (env_top env) }
209 getGblEnv :: TcRnIf gbl lcl gbl
210 getGblEnv = do { env <- getEnv; return (env_gbl env) }
212 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
213 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
214 env { env_gbl = upd gbl })
216 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
217 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
219 getLclEnv :: TcRnIf gbl lcl lcl
220 getLclEnv = do { env <- getEnv; return (env_lcl env) }
222 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
223 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
224 env { env_lcl = upd lcl })
226 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
227 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
229 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
230 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
232 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
233 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
240 getDOpts :: TcRnIf gbl lcl DynFlags
241 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
243 xoptM :: ExtensionFlag -> TcRnIf gbl lcl Bool
244 xoptM flag = do { dflags <- getDOpts; return (xopt flag dflags) }
246 doptM :: DynFlag -> TcRnIf gbl lcl Bool
247 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
249 -- XXX setOptM and unsetOptM operate on different types. One should be renamed.
251 setOptM :: ExtensionFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
252 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
253 env { env_top = top { hsc_dflags = xopt_set_flattened (hsc_dflags top) flag}} )
255 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
256 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
257 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
259 -- | Do it flag is true
260 ifDOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
261 ifDOptM flag thing_inside = do { b <- doptM flag;
262 if b then thing_inside else return () }
264 ifXOptM :: ExtensionFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
265 ifXOptM flag thing_inside = do { b <- xoptM flag;
266 if b then thing_inside else return () }
268 getGhcMode :: TcRnIf gbl lcl GhcMode
269 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
273 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
274 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
276 getEps :: TcRnIf gbl lcl ExternalPackageState
277 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
279 -- | Update the external package state. Returns the second result of the
280 -- modifier function.
282 -- This is an atomic operation and forces evaluation of the modified EPS in
283 -- order to avoid space leaks.
284 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
286 updateEps upd_fn = do
287 traceIf (text "updating EPS")
289 atomicUpdMutVar' eps_var upd_fn
291 -- | Update the external package state.
293 -- This is an atomic operation and forces evaluation of the modified EPS in
294 -- order to avoid space leaks.
295 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
297 updateEps_ upd_fn = do
298 traceIf (text "updating EPS_")
300 atomicUpdMutVar' eps_var (\eps -> (upd_fn eps, ()))
302 getHpt :: TcRnIf gbl lcl HomePackageTable
303 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
305 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
306 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
307 ; return (eps, hsc_HPT env) }
310 %************************************************************************
314 %************************************************************************
317 newUnique :: TcRnIf gbl lcl Unique
319 = do { env <- getEnv ;
320 let { u_var = env_us env } ;
321 us <- readMutVar u_var ;
322 case splitUniqSupply us of { (us1,_) -> do {
323 writeMutVar u_var us1 ;
324 return $! uniqFromSupply us }}}
325 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
326 -- a chain of unevaluated supplies behind.
327 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
328 -- throw away one half of the new split supply. This is safe because this
329 -- is the only place we use that unique. Using the other half of the split
330 -- supply is safer, but slower.
332 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
334 = do { env <- getEnv ;
335 let { u_var = env_us env } ;
336 us <- readMutVar u_var ;
337 case splitUniqSupply us of { (us1,us2) -> do {
338 writeMutVar u_var us1 ;
341 newLocalName :: Name -> TcRnIf gbl lcl Name
342 newLocalName name -- Make a clone
343 = do { uniq <- newUnique
344 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
346 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
347 newSysLocalIds fs tys
348 = do { us <- newUniqueSupply
349 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
351 instance MonadUnique (IOEnv (Env gbl lcl)) where
352 getUniqueM = newUnique
353 getUniqueSupplyM = newUniqueSupply
357 %************************************************************************
361 %************************************************************************
364 newTcRef :: a -> TcRnIf gbl lcl (TcRef a)
367 readTcRef :: TcRef a -> TcRnIf gbl lcl a
368 readTcRef = readMutVar
370 writeTcRef :: TcRef a -> a -> TcRnIf gbl lcl ()
371 writeTcRef = writeMutVar
373 updTcRef :: TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
377 %************************************************************************
381 %************************************************************************
384 traceTc :: String -> SDoc -> TcRn ()
387 traceTcN :: Int -> String -> SDoc -> TcRn ()
388 traceTcN level herald doc
389 | level <= opt_TraceLevel = traceOptTcRn Opt_D_dump_tc_trace $
390 hang (text herald) 2 doc
391 | otherwise = return ()
393 traceRn, traceSplice :: SDoc -> TcRn ()
394 traceRn = traceOptTcRn Opt_D_dump_rn_trace
395 traceSplice = traceOptTcRn Opt_D_dump_splices
398 traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()
399 traceIf = traceOptIf Opt_D_dump_if_trace
400 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
403 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
404 traceOptIf flag doc = ifDOptM flag $
405 liftIO (printForUser stderr alwaysQualify doc)
407 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
408 -- Output the message, with current location if opt_PprStyle_Debug
409 traceOptTcRn flag doc = ifDOptM flag $ do
412 | opt_PprStyle_Debug = mkLocMessage loc doc
413 | otherwise = doc -- The full location is
414 -- usually way too much
415 ; dumpTcRn real_doc }
417 dumpTcRn :: SDoc -> TcRn ()
418 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv
420 ; liftIO (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
422 debugDumpTcRn :: SDoc -> TcRn ()
423 debugDumpTcRn doc | opt_NoDebugOutput = return ()
424 | otherwise = dumpTcRn doc
426 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
427 dumpOptTcRn flag doc = ifDOptM flag (dumpTcRn doc)
431 %************************************************************************
433 Typechecker global environment
435 %************************************************************************
438 getModule :: TcRn Module
439 getModule = do { env <- getGblEnv; return (tcg_mod env) }
441 setModule :: Module -> TcRn a -> TcRn a
442 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
444 tcIsHsBoot :: TcRn Bool
445 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
447 getGlobalRdrEnv :: TcRn GlobalRdrEnv
448 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
450 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
451 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
453 getImports :: TcRn ImportAvails
454 getImports = do { env <- getGblEnv; return (tcg_imports env) }
456 getFixityEnv :: TcRn FixityEnv
457 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
459 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
460 extendFixityEnv new_bit
461 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
462 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
464 getRecFieldEnv :: TcRn RecFieldEnv
465 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
467 getDeclaredDefaultTys :: TcRn (Maybe [Type])
468 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
471 %************************************************************************
475 %************************************************************************
478 getSrcSpanM :: TcRn SrcSpan
479 -- Avoid clash with Name.getSrcLoc
480 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
482 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
483 setSrcSpan loc thing_inside
484 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
485 | otherwise = thing_inside -- Don't overwrite useful info with useless
487 addLocM :: (a -> TcM b) -> Located a -> TcM b
488 addLocM fn (L loc a) = setSrcSpan loc $ fn a
490 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
491 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
493 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
494 wrapLocFstM fn (L loc a) =
499 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
500 wrapLocSndM fn (L loc a) =
509 getErrsVar :: TcRn (TcRef Messages)
510 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
512 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
513 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
515 addErr :: Message -> TcRn () -- Ignores the context stack
516 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
518 failWith :: Message -> TcRn a
519 failWith msg = addErr msg >> failM
521 addErrAt :: SrcSpan -> Message -> TcRn ()
522 -- addErrAt is mainly (exclusively?) used by the renamer, where
523 -- tidying is not an issue, but it's all lazy so the extra
524 -- work doesn't matter
525 addErrAt loc msg = do { ctxt <- getErrCtxt
526 ; tidy_env <- tcInitTidyEnv
527 ; err_info <- mkErrInfo tidy_env ctxt
528 ; addLongErrAt loc msg err_info }
530 addErrs :: [(SrcSpan,Message)] -> TcRn ()
531 addErrs msgs = mapM_ add msgs
533 add (loc,msg) = addErrAt loc msg
535 addWarn :: Message -> TcRn ()
536 addWarn msg = addReport (ptext (sLit "Warning:") <+> msg) empty
538 addWarnAt :: SrcSpan -> Message -> TcRn ()
539 addWarnAt loc msg = addReportAt loc (ptext (sLit "Warning:") <+> msg) empty
541 checkErr :: Bool -> Message -> TcRn ()
542 -- Add the error if the bool is False
543 checkErr ok msg = unless ok (addErr msg)
545 warnIf :: Bool -> Message -> TcRn ()
546 warnIf True msg = addWarn msg
547 warnIf False _ = return ()
549 addMessages :: Messages -> TcRn ()
550 addMessages (m_warns, m_errs)
551 = do { errs_var <- getErrsVar ;
552 (warns, errs) <- readTcRef errs_var ;
553 writeTcRef errs_var (warns `unionBags` m_warns,
554 errs `unionBags` m_errs) }
556 discardWarnings :: TcRn a -> TcRn a
557 -- Ignore warnings inside the thing inside;
558 -- used to ignore-unused-variable warnings inside derived code
559 -- With -dppr-debug, the effects is switched off, so you can still see
560 -- what warnings derived code would give
561 discardWarnings thing_inside
562 | opt_PprStyle_Debug = thing_inside
564 = do { errs_var <- newTcRef emptyMessages
565 ; result <- setErrsVar errs_var thing_inside
566 ; (_warns, errs) <- readTcRef errs_var
567 ; addMessages (emptyBag, errs)
572 %************************************************************************
574 Shared error message stuff: renamer and typechecker
576 %************************************************************************
579 addReport :: Message -> Message -> TcRn ()
580 addReport msg extra_info = do loc <- getSrcSpanM; addReportAt loc msg extra_info
582 addReportAt :: SrcSpan -> Message -> Message -> TcRn ()
583 addReportAt loc msg extra_info
584 = do { errs_var <- getErrsVar ;
585 rdr_env <- getGlobalRdrEnv ;
587 let { warn = mkLongWarnMsg loc (mkPrintUnqualified dflags rdr_env)
589 (warns, errs) <- readTcRef errs_var ;
590 writeTcRef errs_var (warns `snocBag` warn, errs) }
592 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
593 addLongErrAt loc msg extra
594 = do { traceTc "Adding error:" (mkLocMessage loc (msg $$ extra)) ;
595 errs_var <- getErrsVar ;
596 rdr_env <- getGlobalRdrEnv ;
598 let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
599 (warns, errs) <- readTcRef errs_var ;
600 writeTcRef errs_var (warns, errs `snocBag` err) }
605 try_m :: TcRn r -> TcRn (Either IOEnvFailure r)
606 -- Does try_m, with a debug-trace on failure
608 = do { mb_r <- tryM thing ;
610 Left exn -> do { traceTc "tryTc/recoverM recovering from" $
611 text (showException exn)
613 Right _ -> return mb_r }
615 -----------------------
616 recoverM :: TcRn r -- Recovery action; do this if the main one fails
617 -> TcRn r -- Main action: do this first
619 -- Errors in 'thing' are retained
620 recoverM recover thing
621 = do { mb_res <- try_m thing ;
624 Right res -> return res }
627 -----------------------
628 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
629 -- Drop elements of the input that fail, so the result
630 -- list can be shorter than the argument list
631 mapAndRecoverM _ [] = return []
632 mapAndRecoverM f (x:xs) = do { mb_r <- try_m (f x)
633 ; rs <- mapAndRecoverM f xs
634 ; return (case mb_r of
639 -----------------------
640 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
641 -- (tryTc m) executes m, and returns
642 -- Just r, if m succeeds (returning r)
643 -- Nothing, if m fails
644 -- It also returns all the errors and warnings accumulated by m
645 -- It always succeeds (never raises an exception)
647 = do { errs_var <- newTcRef emptyMessages ;
648 res <- try_m (setErrsVar errs_var m) ;
649 msgs <- readTcRef errs_var ;
650 return (msgs, case res of
652 Right val -> Just val)
653 -- The exception is always the IOEnv built-in
654 -- in exception; see IOEnv.failM
657 -----------------------
658 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
659 -- Run the thing, returning
660 -- Just r, if m succceeds with no error messages
661 -- Nothing, if m fails, or if it succeeds but has error messages
662 -- Either way, the messages are returned; even in the Just case
663 -- there might be warnings
665 = do { (msgs, res) <- tryTc thing
667 ; let errs_found = errorsFound dflags msgs
668 ; return (msgs, case res of
670 Just val | errs_found -> Nothing
671 | otherwise -> Just val)
674 -----------------------
675 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
676 -- Just like tryTcErrs, except that it ensures that the LIE
677 -- for the thing is propagated only if there are no errors
678 -- Hence it's restricted to the type-check monad
679 tryTcLIE thing_inside
680 = do { ((msgs, mb_res), lie) <- getConstraints (tryTcErrs thing_inside) ;
682 Nothing -> return (msgs, Nothing)
683 Just val -> do { emitConstraints lie; return (msgs, Just val) }
686 -----------------------
687 tryTcLIE_ :: TcM r -> TcM r -> TcM r
688 -- (tryTcLIE_ r m) tries m;
689 -- if m succeeds with no error messages, it's the answer
690 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
691 tryTcLIE_ recover main
692 = do { (msgs, mb_res) <- tryTcLIE main
694 Just val -> do { addMessages msgs -- There might be warnings
696 Nothing -> recover -- Discard all msgs
699 -----------------------
700 checkNoErrs :: TcM r -> TcM r
701 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
702 -- If m fails then (checkNoErrsTc m) fails.
703 -- If m succeeds, it checks whether m generated any errors messages
704 -- (it might have recovered internally)
705 -- If so, it fails too.
706 -- Regardless, any errors generated by m are propagated to the enclosing context.
708 = do { (msgs, mb_res) <- tryTcLIE main
712 Just val -> return val
715 ifErrsM :: TcRn r -> TcRn r -> TcRn r
716 -- ifErrsM bale_out main
717 -- does 'bale_out' if there are errors in errors collection
718 -- otherwise does 'main'
719 ifErrsM bale_out normal
720 = do { errs_var <- getErrsVar ;
721 msgs <- readTcRef errs_var ;
723 if errorsFound dflags msgs then
728 failIfErrsM :: TcRn ()
729 -- Useful to avoid error cascades
730 failIfErrsM = ifErrsM failM (return ())
734 %************************************************************************
736 Context management for the type checker
738 %************************************************************************
741 getErrCtxt :: TcM [ErrCtxt]
742 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
744 setErrCtxt :: [ErrCtxt] -> TcM a -> TcM a
745 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
747 addErrCtxt :: Message -> TcM a -> TcM a
748 addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
750 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
751 addErrCtxtM ctxt = updCtxt (\ ctxts -> (False, ctxt) : ctxts)
753 addLandmarkErrCtxt :: Message -> TcM a -> TcM a
754 addLandmarkErrCtxt msg = updCtxt (\ctxts -> (True, \env -> return (env,msg)) : ctxts)
756 -- Helper function for the above
757 updCtxt :: ([ErrCtxt] -> [ErrCtxt]) -> TcM a -> TcM a
758 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
759 env { tcl_ctxt = upd ctxt })
761 -- Conditionally add an error context
762 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
763 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
764 maybeAddErrCtxt Nothing thing_inside = thing_inside
766 popErrCtxt :: TcM a -> TcM a
767 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
769 getCtLoc :: orig -> TcM (CtLoc orig)
771 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
772 return (CtLoc origin loc (tcl_ctxt env)) }
774 setCtLoc :: CtLoc orig -> TcM a -> TcM a
775 setCtLoc (CtLoc _ src_loc ctxt) thing_inside
776 = setSrcSpan src_loc (setErrCtxt ctxt thing_inside)
779 %************************************************************************
781 Error message generation (type checker)
783 %************************************************************************
785 The addErrTc functions add an error message, but do not cause failure.
786 The 'M' variants pass a TidyEnv that has already been used to
787 tidy up the message; we then use it to tidy the context messages
790 addErrTc :: Message -> TcM ()
791 addErrTc err_msg = do { env0 <- tcInitTidyEnv
792 ; addErrTcM (env0, err_msg) }
794 addErrsTc :: [Message] -> TcM ()
795 addErrsTc err_msgs = mapM_ addErrTc err_msgs
797 addErrTcM :: (TidyEnv, Message) -> TcM ()
798 addErrTcM (tidy_env, err_msg)
799 = do { ctxt <- getErrCtxt ;
801 add_err_tcm tidy_env err_msg loc ctxt }
804 The failWith functions add an error message and cause failure
807 failWithTc :: Message -> TcM a -- Add an error message and fail
809 = addErrTc err_msg >> failM
811 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
812 failWithTcM local_and_msg
813 = addErrTcM local_and_msg >> failM
815 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
816 checkTc True _ = return ()
817 checkTc False err = failWithTc err
820 Warnings have no 'M' variant, nor failure
823 addWarnTc :: Message -> TcM ()
824 addWarnTc msg = do { env0 <- tcInitTidyEnv
825 ; addWarnTcM (env0, msg) }
827 addWarnTcM :: (TidyEnv, Message) -> TcM ()
828 addWarnTcM (env0, msg)
829 = do { ctxt <- getErrCtxt ;
830 err_info <- mkErrInfo env0 ctxt ;
831 addReport (ptext (sLit "Warning:") <+> msg) err_info }
833 warnTc :: Bool -> Message -> TcM ()
834 warnTc warn_if_true warn_msg
835 | warn_if_true = addWarnTc warn_msg
836 | otherwise = return ()
839 -----------------------------------
842 We initialise the "tidy-env", used for tidying types before printing,
843 by building a reverse map from the in-scope type variables to the
844 OccName that the programmer originally used for them
847 tcInitTidyEnv :: TcM TidyEnv
849 = do { lcl_env <- getLclEnv
850 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
851 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
853 ; return (foldl add emptyTidyEnv nm_tv_prs) }
855 add (env,subst) (name, tyvar)
856 = case tidyOccName env (nameOccName name) of
857 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
859 tyvar' = setTyVarName tyvar name'
860 name' = tidyNameOcc name occ'
863 -----------------------------------
864 Other helper functions
867 add_err_tcm :: TidyEnv -> Message -> SrcSpan
870 add_err_tcm tidy_env err_msg loc ctxt
871 = do { err_info <- mkErrInfo tidy_env ctxt ;
872 addLongErrAt loc err_msg err_info }
874 mkErrInfo :: TidyEnv -> [ErrCtxt] -> TcM SDoc
875 -- Tidy the error info, trimming excessive contexts
879 go :: Int -> TidyEnv -> [ErrCtxt] -> TcM SDoc
880 go _ _ [] = return empty
881 go n env ((is_landmark, ctxt) : ctxts)
882 | is_landmark || n < mAX_CONTEXTS -- Too verbose || opt_PprStyle_Debug
883 = do { (env', msg) <- ctxt env
884 ; let n' = if is_landmark then n else n+1
885 ; rest <- go n' env' ctxts
886 ; return (msg $$ rest) }
890 mAX_CONTEXTS :: Int -- No more than this number of non-landmark contexts
894 debugTc is useful for monadic debugging code
897 debugTc :: TcM () -> TcM ()
900 | otherwise = return ()
903 %************************************************************************
907 %************************************************************************
910 newTcEvBinds :: TcM EvBindsVar
911 newTcEvBinds = do { ref <- newTcRef emptyEvBindMap
913 ; return (EvBindsVar ref uniq) }
915 extendTcEvBinds :: TcEvBinds -> EvVar -> EvTerm -> TcM TcEvBinds
916 extendTcEvBinds binds@(TcEvBinds binds_var) var rhs
917 = do { addTcEvBind binds_var var rhs
919 extendTcEvBinds (EvBinds bnds) var rhs
920 = return (EvBinds (bnds `snocBag` EvBind var rhs))
922 addTcEvBind :: EvBindsVar -> EvVar -> EvTerm -> TcM ()
923 -- Add a binding to the TcEvBinds by side effect
924 addTcEvBind (EvBindsVar ev_ref _) var rhs
925 = do { bnds <- readTcRef ev_ref
926 ; writeTcRef ev_ref (extendEvBinds bnds var rhs) }
928 chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
929 chooseUniqueOccTc fn =
930 do { env <- getGblEnv
931 ; let dfun_n_var = tcg_dfun_n env
932 ; set <- readTcRef dfun_n_var
934 ; writeTcRef dfun_n_var (extendOccSet set occ)
937 getConstraintVar :: TcM (TcRef WantedConstraints)
938 getConstraintVar = do { env <- getLclEnv; return (tcl_lie env) }
940 setConstraintVar :: TcRef WantedConstraints -> TcM a -> TcM a
941 setConstraintVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
943 emitConstraints :: WantedConstraints -> TcM ()
945 = do { lie_var <- getConstraintVar ;
946 updTcRef lie_var (`andWanteds` ct) }
948 emitConstraint :: WantedConstraint -> TcM ()
950 = do { lie_var <- getConstraintVar ;
951 updTcRef lie_var (`extendWanteds` ct) }
953 getConstraints :: TcM a -> TcM (a, WantedConstraints)
954 -- (getConstraints m) runs m, and returns the type constraints it generates
955 getConstraints thing_inside
956 = do { lie_var <- newTcRef emptyWanteds ;
957 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
959 lie <- readTcRef lie_var ;
962 setUntouchables :: TcTyVarSet -> TcM a -> TcM a
963 setUntouchables untch_tvs thing_inside
964 = updLclEnv (\ env -> env { tcl_untch = untch_tvs }) thing_inside
966 getUntouchables :: TcM TcTyVarSet
968 = do { env <- getLclEnv; return (tcl_untch env) }
970 isUntouchable :: TcTyVar -> TcM Bool
971 isUntouchable tv = do { env <- getLclEnv; return (tv `elemVarSet` tcl_untch env) }
973 getLclTypeEnv :: TcM (NameEnv TcTyThing)
974 getLclTypeEnv = do { env <- getLclEnv; return (tcl_env env) }
976 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
977 -- Set the local type envt, but do *not* disturb other fields,
978 -- notably the lie_var
979 setLclTypeEnv lcl_env thing_inside
980 = updLclEnv upd thing_inside
982 upd env = env { tcl_env = tcl_env lcl_env,
983 tcl_tyvars = tcl_tyvars lcl_env }
987 %************************************************************************
989 Template Haskell context
991 %************************************************************************
994 recordThUse :: TcM ()
995 recordThUse = do { env <- getGblEnv; writeTcRef (tcg_th_used env) True }
997 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
999 | isLocalId id = do { env <- getGblEnv;
1000 ; updTcRef (tcg_keep env) (`addOneToNameSet` idName id) }
1001 | otherwise = return ()
1003 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
1004 keepAliveSetTc ns = do { env <- getGblEnv;
1005 ; updTcRef (tcg_keep env) (`unionNameSets` ns) }
1007 getStage :: TcM ThStage
1008 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
1010 setStage :: ThStage -> TcM a -> TcM a
1011 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
1015 %************************************************************************
1017 Stuff for the renamer's local env
1019 %************************************************************************
1022 getLocalRdrEnv :: RnM LocalRdrEnv
1023 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
1025 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
1026 setLocalRdrEnv rdr_env thing_inside
1027 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
1031 %************************************************************************
1033 Stuff for interface decls
1035 %************************************************************************
1038 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
1039 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
1041 if_tv_env = emptyUFM,
1042 if_id_env = emptyUFM }
1044 initIfaceTcRn :: IfG a -> TcRn a
1045 initIfaceTcRn thing_inside
1046 = do { tcg_env <- getGblEnv
1047 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
1048 ; get_type_env = readTcRef (tcg_type_env_var tcg_env) }
1049 ; setEnvs (if_env, ()) thing_inside }
1051 initIfaceExtCore :: IfL a -> TcRn a
1052 initIfaceExtCore thing_inside
1053 = do { tcg_env <- getGblEnv
1054 ; let { mod = tcg_mod tcg_env
1055 ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
1056 ; if_env = IfGblEnv {
1057 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
1058 ; if_lenv = mkIfLclEnv mod doc
1060 ; setEnvs (if_env, if_lenv) thing_inside }
1062 initIfaceCheck :: HscEnv -> IfG a -> IO a
1063 -- Used when checking the up-to-date-ness of the old Iface
1064 -- Initialise the environment with no useful info at all
1065 initIfaceCheck hsc_env do_this
1066 = do let rec_types = case hsc_type_env_var hsc_env of
1067 Just (mod,var) -> Just (mod, readTcRef var)
1069 gbl_env = IfGblEnv { if_rec_types = rec_types }
1070 initTcRnIf 'i' hsc_env gbl_env () do_this
1072 initIfaceTc :: ModIface
1073 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
1074 -- Used when type-checking checking an up-to-date interface file
1075 -- No type envt from the current module, but we do know the module dependencies
1076 initIfaceTc iface do_this
1077 = do { tc_env_var <- newTcRef emptyTypeEnv
1078 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readTcRef tc_env_var) } ;
1079 ; if_lenv = mkIfLclEnv mod doc
1081 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
1084 mod = mi_module iface
1085 doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
1087 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
1088 -- Used when sucking in new Rules in SimplCore
1089 -- We have available the type envt of the module being compiled, and we must use it
1090 initIfaceRules hsc_env guts do_this
1092 type_info = (mg_module guts, return (mg_types guts))
1093 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
1096 -- Run the thing; any exceptions just bubble out from here
1097 ; initTcRnIf 'i' hsc_env gbl_env () do_this
1100 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
1101 initIfaceLcl mod loc_doc thing_inside
1102 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1104 getIfModule :: IfL Module
1105 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1107 --------------------
1108 failIfM :: Message -> IfL a
1109 -- The Iface monad doesn't have a place to accumulate errors, so we
1110 -- just fall over fast if one happens; it "shouldnt happen".
1111 -- We use IfL here so that we can get context info out of the local env
1113 = do { env <- getLclEnv
1114 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1115 ; liftIO (printErrs (full_msg defaultErrStyle))
1118 --------------------
1119 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1120 -- Run thing_inside in an interleaved thread.
1121 -- It shares everything with the parent thread, so this is DANGEROUS.
1123 -- It returns Nothing if the computation fails
1125 -- It's used for lazily type-checking interface
1126 -- signatures, which is pretty benign
1128 forkM_maybe doc thing_inside
1129 = do { unsafeInterleaveM $
1130 do { traceIf (text "Starting fork {" <+> doc)
1132 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1135 Right r -> do { traceIf (text "} ending fork" <+> doc)
1139 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1140 -- Otherwise we silently discard errors. Errors can legitimately
1141 -- happen when compiling interface signatures (see tcInterfaceSigs)
1142 ifDOptM Opt_D_dump_if_trace
1143 (print_errs (hang (text "forkM failed:" <+> doc)
1144 2 (text (show exn))))
1146 ; traceIf (text "} ending fork (badly)" <+> doc)
1150 print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1152 forkM :: SDoc -> IfL a -> IfL a
1153 forkM doc thing_inside
1154 = do { mb_res <- forkM_maybe doc thing_inside
1155 ; return (case mb_res of
1156 Nothing -> pgmError "Cannot continue after interface file error"
1157 -- pprPanic "forkM" doc