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,
112 tcg_sigs = emptyNameSet,
113 tcg_ev_binds = emptyBag,
114 tcg_warns = NoWarnings,
120 tcg_dfun_n = dfun_n_var,
122 tcg_doc_hdr = Nothing,
128 tcl_loc = mkGeneralSrcSpan (fsLit "Top level"),
130 tcl_rdr = emptyLocalRdrEnv,
131 tcl_th_ctxt = topStage,
132 tcl_arrow_ctxt = NoArrowCtxt,
133 tcl_env = emptyNameEnv,
134 tcl_tyvars = tvs_var,
136 tcl_untch = emptyVarSet
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 -- Check for unsolved constraints
148 lie <- readIORef lie_var ;
151 else pprPanic "initTc: unsolved constraints"
152 (pprWantedsWithLocs lie) ;
154 -- Collect any error messages
155 msgs <- readIORef errs_var ;
157 let { dflags = hsc_dflags hsc_env
158 ; final_res | errorsFound dflags msgs = Nothing
159 | otherwise = maybe_res } ;
161 return (msgs, final_res)
164 initTcPrintErrors -- Used from the interactive loop only
168 -> IO (Messages, Maybe r)
169 initTcPrintErrors env mod todo = do
170 (msgs, res) <- initTc env HsSrcFile False mod todo
174 %************************************************************************
178 %************************************************************************
182 initTcRnIf :: Char -- Tag for unique supply
187 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
188 = do { us <- mkSplitUniqSupply uniq_tag ;
189 ; us_var <- newIORef us ;
191 ; let { env = Env { env_top = hsc_env,
196 ; runIOEnv env thing_inside
200 %************************************************************************
204 %************************************************************************
207 getTopEnv :: TcRnIf gbl lcl HscEnv
208 getTopEnv = do { env <- getEnv; return (env_top env) }
210 getGblEnv :: TcRnIf gbl lcl gbl
211 getGblEnv = do { env <- getEnv; return (env_gbl env) }
213 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
214 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
215 env { env_gbl = upd gbl })
217 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
218 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
220 getLclEnv :: TcRnIf gbl lcl lcl
221 getLclEnv = do { env <- getEnv; return (env_lcl env) }
223 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
224 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
225 env { env_lcl = upd lcl })
227 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
228 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
230 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
231 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
233 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
234 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
241 getDOpts :: TcRnIf gbl lcl DynFlags
242 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
244 xoptM :: ExtensionFlag -> TcRnIf gbl lcl Bool
245 xoptM flag = do { dflags <- getDOpts; return (xopt flag dflags) }
247 doptM :: DynFlag -> TcRnIf gbl lcl Bool
248 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
250 -- XXX setOptM and unsetOptM operate on different types. One should be renamed.
252 setOptM :: ExtensionFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
253 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
254 env { env_top = top { hsc_dflags = xopt_set_flattened (hsc_dflags top) flag}} )
256 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
257 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
258 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
260 -- | Do it flag is true
261 ifDOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
262 ifDOptM flag thing_inside = do { b <- doptM flag;
263 if b then thing_inside else return () }
265 ifXOptM :: ExtensionFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
266 ifXOptM flag thing_inside = do { b <- xoptM flag;
267 if b then thing_inside else return () }
269 getGhcMode :: TcRnIf gbl lcl GhcMode
270 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
274 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
275 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
277 getEps :: TcRnIf gbl lcl ExternalPackageState
278 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
280 -- | Update the external package state. Returns the second result of the
281 -- modifier function.
283 -- This is an atomic operation and forces evaluation of the modified EPS in
284 -- order to avoid space leaks.
285 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
287 updateEps upd_fn = do
288 traceIf (text "updating EPS")
290 atomicUpdMutVar' eps_var upd_fn
292 -- | Update the external package state.
294 -- This is an atomic operation and forces evaluation of the modified EPS in
295 -- order to avoid space leaks.
296 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
298 updateEps_ upd_fn = do
299 traceIf (text "updating EPS_")
301 atomicUpdMutVar' eps_var (\eps -> (upd_fn eps, ()))
303 getHpt :: TcRnIf gbl lcl HomePackageTable
304 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
306 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
307 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
308 ; return (eps, hsc_HPT env) }
311 %************************************************************************
315 %************************************************************************
318 newUnique :: TcRnIf gbl lcl Unique
320 = do { env <- getEnv ;
321 let { u_var = env_us env } ;
322 us <- readMutVar u_var ;
323 case splitUniqSupply us of { (us1,_) -> do {
324 writeMutVar u_var us1 ;
325 return $! uniqFromSupply us }}}
326 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
327 -- a chain of unevaluated supplies behind.
328 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
329 -- throw away one half of the new split supply. This is safe because this
330 -- is the only place we use that unique. Using the other half of the split
331 -- supply is safer, but slower.
333 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
335 = do { env <- getEnv ;
336 let { u_var = env_us env } ;
337 us <- readMutVar u_var ;
338 case splitUniqSupply us of { (us1,us2) -> do {
339 writeMutVar u_var us1 ;
342 newLocalName :: Name -> TcRnIf gbl lcl Name
343 newLocalName name -- Make a clone
344 = do { uniq <- newUnique
345 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
347 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
348 newSysLocalIds fs tys
349 = do { us <- newUniqueSupply
350 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
352 instance MonadUnique (IOEnv (Env gbl lcl)) where
353 getUniqueM = newUnique
354 getUniqueSupplyM = newUniqueSupply
358 %************************************************************************
362 %************************************************************************
365 newTcRef :: a -> TcRnIf gbl lcl (TcRef a)
368 readTcRef :: TcRef a -> TcRnIf gbl lcl a
369 readTcRef = readMutVar
371 writeTcRef :: TcRef a -> a -> TcRnIf gbl lcl ()
372 writeTcRef = writeMutVar
374 updTcRef :: TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
378 %************************************************************************
382 %************************************************************************
385 traceTc :: String -> SDoc -> TcRn ()
388 traceTcN :: Int -> String -> SDoc -> TcRn ()
389 traceTcN level herald doc
390 | level <= opt_TraceLevel = traceOptTcRn Opt_D_dump_tc_trace $
391 hang (text herald) 2 doc
392 | otherwise = return ()
394 traceRn, traceSplice :: SDoc -> TcRn ()
395 traceRn = traceOptTcRn Opt_D_dump_rn_trace
396 traceSplice = traceOptTcRn Opt_D_dump_splices
399 traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()
400 traceIf = traceOptIf Opt_D_dump_if_trace
401 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
404 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
405 traceOptIf flag doc = ifDOptM flag $
406 liftIO (printForUser stderr alwaysQualify doc)
408 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
409 -- Output the message, with current location if opt_PprStyle_Debug
410 traceOptTcRn flag doc = ifDOptM flag $ do
413 | opt_PprStyle_Debug = mkLocMessage loc doc
414 | otherwise = doc -- The full location is
415 -- usually way too much
416 ; dumpTcRn real_doc }
418 dumpTcRn :: SDoc -> TcRn ()
419 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv
421 ; liftIO (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
423 debugDumpTcRn :: SDoc -> TcRn ()
424 debugDumpTcRn doc | opt_NoDebugOutput = return ()
425 | otherwise = dumpTcRn doc
427 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
428 dumpOptTcRn flag doc = ifDOptM flag (dumpTcRn doc)
432 %************************************************************************
434 Typechecker global environment
436 %************************************************************************
439 getModule :: TcRn Module
440 getModule = do { env <- getGblEnv; return (tcg_mod env) }
442 setModule :: Module -> TcRn a -> TcRn a
443 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
445 tcIsHsBoot :: TcRn Bool
446 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
448 getGlobalRdrEnv :: TcRn GlobalRdrEnv
449 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
451 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
452 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
454 getImports :: TcRn ImportAvails
455 getImports = do { env <- getGblEnv; return (tcg_imports env) }
457 getFixityEnv :: TcRn FixityEnv
458 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
460 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
461 extendFixityEnv new_bit
462 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
463 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
465 getRecFieldEnv :: TcRn RecFieldEnv
466 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
468 getDeclaredDefaultTys :: TcRn (Maybe [Type])
469 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
472 %************************************************************************
476 %************************************************************************
479 getSrcSpanM :: TcRn SrcSpan
480 -- Avoid clash with Name.getSrcLoc
481 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
483 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
484 setSrcSpan loc thing_inside
485 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
486 | otherwise = thing_inside -- Don't overwrite useful info with useless
488 addLocM :: (a -> TcM b) -> Located a -> TcM b
489 addLocM fn (L loc a) = setSrcSpan loc $ fn a
491 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
492 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
494 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
495 wrapLocFstM fn (L loc a) =
500 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
501 wrapLocSndM fn (L loc a) =
510 getErrsVar :: TcRn (TcRef Messages)
511 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
513 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
514 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
516 addErr :: Message -> TcRn () -- Ignores the context stack
517 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
519 failWith :: Message -> TcRn a
520 failWith msg = addErr msg >> failM
522 addErrAt :: SrcSpan -> Message -> TcRn ()
523 -- addErrAt is mainly (exclusively?) used by the renamer, where
524 -- tidying is not an issue, but it's all lazy so the extra
525 -- work doesn't matter
526 addErrAt loc msg = do { ctxt <- getErrCtxt
527 ; tidy_env <- tcInitTidyEnv
528 ; err_info <- mkErrInfo tidy_env ctxt
529 ; addLongErrAt loc msg err_info }
531 addErrs :: [(SrcSpan,Message)] -> TcRn ()
532 addErrs msgs = mapM_ add msgs
534 add (loc,msg) = addErrAt loc msg
536 addWarn :: Message -> TcRn ()
537 addWarn msg = addReport (ptext (sLit "Warning:") <+> msg) empty
539 addWarnAt :: SrcSpan -> Message -> TcRn ()
540 addWarnAt loc msg = addReportAt loc (ptext (sLit "Warning:") <+> msg) empty
542 checkErr :: Bool -> Message -> TcRn ()
543 -- Add the error if the bool is False
544 checkErr ok msg = unless ok (addErr msg)
546 warnIf :: Bool -> Message -> TcRn ()
547 warnIf True msg = addWarn msg
548 warnIf False _ = return ()
550 addMessages :: Messages -> TcRn ()
551 addMessages (m_warns, m_errs)
552 = do { errs_var <- getErrsVar ;
553 (warns, errs) <- readTcRef errs_var ;
554 writeTcRef errs_var (warns `unionBags` m_warns,
555 errs `unionBags` m_errs) }
557 discardWarnings :: TcRn a -> TcRn a
558 -- Ignore warnings inside the thing inside;
559 -- used to ignore-unused-variable warnings inside derived code
560 -- With -dppr-debug, the effects is switched off, so you can still see
561 -- what warnings derived code would give
562 discardWarnings thing_inside
563 | opt_PprStyle_Debug = thing_inside
565 = do { errs_var <- newTcRef emptyMessages
566 ; result <- setErrsVar errs_var thing_inside
567 ; (_warns, errs) <- readTcRef errs_var
568 ; addMessages (emptyBag, errs)
573 %************************************************************************
575 Shared error message stuff: renamer and typechecker
577 %************************************************************************
580 addReport :: Message -> Message -> TcRn ()
581 addReport msg extra_info = do loc <- getSrcSpanM; addReportAt loc msg extra_info
583 addReportAt :: SrcSpan -> Message -> Message -> TcRn ()
584 addReportAt loc msg extra_info
585 = do { errs_var <- getErrsVar ;
586 rdr_env <- getGlobalRdrEnv ;
588 let { warn = mkLongWarnMsg loc (mkPrintUnqualified dflags rdr_env)
590 (warns, errs) <- readTcRef errs_var ;
591 writeTcRef errs_var (warns `snocBag` warn, errs) }
593 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
594 addLongErrAt loc msg extra
595 = do { traceTc "Adding error:" (mkLocMessage loc (msg $$ extra)) ;
596 errs_var <- getErrsVar ;
597 rdr_env <- getGlobalRdrEnv ;
599 let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
600 (warns, errs) <- readTcRef errs_var ;
601 writeTcRef errs_var (warns, errs `snocBag` err) }
606 try_m :: TcRn r -> TcRn (Either IOEnvFailure r)
607 -- Does try_m, with a debug-trace on failure
609 = do { mb_r <- tryM thing ;
611 Left exn -> do { traceTc "tryTc/recoverM recovering from" $
612 text (showException exn)
614 Right _ -> return mb_r }
616 -----------------------
617 recoverM :: TcRn r -- Recovery action; do this if the main one fails
618 -> TcRn r -- Main action: do this first
620 -- Errors in 'thing' are retained
621 recoverM recover thing
622 = do { mb_res <- try_m thing ;
625 Right res -> return res }
628 -----------------------
629 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
630 -- Drop elements of the input that fail, so the result
631 -- list can be shorter than the argument list
632 mapAndRecoverM _ [] = return []
633 mapAndRecoverM f (x:xs) = do { mb_r <- try_m (f x)
634 ; rs <- mapAndRecoverM f xs
635 ; return (case mb_r of
640 -----------------------
641 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
642 -- (tryTc m) executes m, and returns
643 -- Just r, if m succeeds (returning r)
644 -- Nothing, if m fails
645 -- It also returns all the errors and warnings accumulated by m
646 -- It always succeeds (never raises an exception)
648 = do { errs_var <- newTcRef emptyMessages ;
649 res <- try_m (setErrsVar errs_var m) ;
650 msgs <- readTcRef errs_var ;
651 return (msgs, case res of
653 Right val -> Just val)
654 -- The exception is always the IOEnv built-in
655 -- in exception; see IOEnv.failM
658 -----------------------
659 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
660 -- Run the thing, returning
661 -- Just r, if m succceeds with no error messages
662 -- Nothing, if m fails, or if it succeeds but has error messages
663 -- Either way, the messages are returned; even in the Just case
664 -- there might be warnings
666 = do { (msgs, res) <- tryTc thing
668 ; let errs_found = errorsFound dflags msgs
669 ; return (msgs, case res of
671 Just val | errs_found -> Nothing
672 | otherwise -> Just val)
675 -----------------------
676 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
677 -- Just like tryTcErrs, except that it ensures that the LIE
678 -- for the thing is propagated only if there are no errors
679 -- Hence it's restricted to the type-check monad
680 tryTcLIE thing_inside
681 = do { ((msgs, mb_res), lie) <- getConstraints (tryTcErrs thing_inside) ;
683 Nothing -> return (msgs, Nothing)
684 Just val -> do { emitConstraints lie; return (msgs, Just val) }
687 -----------------------
688 tryTcLIE_ :: TcM r -> TcM r -> TcM r
689 -- (tryTcLIE_ r m) tries m;
690 -- if m succeeds with no error messages, it's the answer
691 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
692 tryTcLIE_ recover main
693 = do { (msgs, mb_res) <- tryTcLIE main
695 Just val -> do { addMessages msgs -- There might be warnings
697 Nothing -> recover -- Discard all msgs
700 -----------------------
701 checkNoErrs :: TcM r -> TcM r
702 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
703 -- If m fails then (checkNoErrsTc m) fails.
704 -- If m succeeds, it checks whether m generated any errors messages
705 -- (it might have recovered internally)
706 -- If so, it fails too.
707 -- Regardless, any errors generated by m are propagated to the enclosing context.
709 = do { (msgs, mb_res) <- tryTcLIE main
713 Just val -> return val
716 ifErrsM :: TcRn r -> TcRn r -> TcRn r
717 -- ifErrsM bale_out main
718 -- does 'bale_out' if there are errors in errors collection
719 -- otherwise does 'main'
720 ifErrsM bale_out normal
721 = do { errs_var <- getErrsVar ;
722 msgs <- readTcRef errs_var ;
724 if errorsFound dflags msgs then
729 failIfErrsM :: TcRn ()
730 -- Useful to avoid error cascades
731 failIfErrsM = ifErrsM failM (return ())
735 %************************************************************************
737 Context management for the type checker
739 %************************************************************************
742 getErrCtxt :: TcM [ErrCtxt]
743 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
745 setErrCtxt :: [ErrCtxt] -> TcM a -> TcM a
746 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
748 addErrCtxt :: Message -> TcM a -> TcM a
749 addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
751 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
752 addErrCtxtM ctxt = updCtxt (\ ctxts -> (False, ctxt) : ctxts)
754 addLandmarkErrCtxt :: Message -> TcM a -> TcM a
755 addLandmarkErrCtxt msg = updCtxt (\ctxts -> (True, \env -> return (env,msg)) : ctxts)
757 -- Helper function for the above
758 updCtxt :: ([ErrCtxt] -> [ErrCtxt]) -> TcM a -> TcM a
759 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
760 env { tcl_ctxt = upd ctxt })
762 -- Conditionally add an error context
763 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
764 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
765 maybeAddErrCtxt Nothing thing_inside = thing_inside
767 popErrCtxt :: TcM a -> TcM a
768 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
770 getCtLoc :: orig -> TcM (CtLoc orig)
772 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
773 return (CtLoc origin loc (tcl_ctxt env)) }
775 setCtLoc :: CtLoc orig -> TcM a -> TcM a
776 setCtLoc (CtLoc _ src_loc ctxt) thing_inside
777 = setSrcSpan src_loc (setErrCtxt ctxt thing_inside)
780 %************************************************************************
782 Error message generation (type checker)
784 %************************************************************************
786 The addErrTc functions add an error message, but do not cause failure.
787 The 'M' variants pass a TidyEnv that has already been used to
788 tidy up the message; we then use it to tidy the context messages
791 addErrTc :: Message -> TcM ()
792 addErrTc err_msg = do { env0 <- tcInitTidyEnv
793 ; addErrTcM (env0, err_msg) }
795 addErrsTc :: [Message] -> TcM ()
796 addErrsTc err_msgs = mapM_ addErrTc err_msgs
798 addErrTcM :: (TidyEnv, Message) -> TcM ()
799 addErrTcM (tidy_env, err_msg)
800 = do { ctxt <- getErrCtxt ;
802 add_err_tcm tidy_env err_msg loc ctxt }
805 The failWith functions add an error message and cause failure
808 failWithTc :: Message -> TcM a -- Add an error message and fail
810 = addErrTc err_msg >> failM
812 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
813 failWithTcM local_and_msg
814 = addErrTcM local_and_msg >> failM
816 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
817 checkTc True _ = return ()
818 checkTc False err = failWithTc err
821 Warnings have no 'M' variant, nor failure
824 addWarnTc :: Message -> TcM ()
825 addWarnTc msg = do { env0 <- tcInitTidyEnv
826 ; addWarnTcM (env0, msg) }
828 addWarnTcM :: (TidyEnv, Message) -> TcM ()
829 addWarnTcM (env0, msg)
830 = do { ctxt <- getErrCtxt ;
831 err_info <- mkErrInfo env0 ctxt ;
832 addReport (ptext (sLit "Warning:") <+> msg) err_info }
834 warnTc :: Bool -> Message -> TcM ()
835 warnTc warn_if_true warn_msg
836 | warn_if_true = addWarnTc warn_msg
837 | otherwise = return ()
840 -----------------------------------
843 We initialise the "tidy-env", used for tidying types before printing,
844 by building a reverse map from the in-scope type variables to the
845 OccName that the programmer originally used for them
848 tcInitTidyEnv :: TcM TidyEnv
850 = do { lcl_env <- getLclEnv
851 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
852 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
854 ; return (foldl add emptyTidyEnv nm_tv_prs) }
856 add (env,subst) (name, tyvar)
857 = case tidyOccName env (nameOccName name) of
858 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
860 tyvar' = setTyVarName tyvar name'
861 name' = tidyNameOcc name occ'
864 -----------------------------------
865 Other helper functions
868 add_err_tcm :: TidyEnv -> Message -> SrcSpan
871 add_err_tcm tidy_env err_msg loc ctxt
872 = do { err_info <- mkErrInfo tidy_env ctxt ;
873 addLongErrAt loc err_msg err_info }
875 mkErrInfo :: TidyEnv -> [ErrCtxt] -> TcM SDoc
876 -- Tidy the error info, trimming excessive contexts
880 go :: Int -> TidyEnv -> [ErrCtxt] -> TcM SDoc
881 go _ _ [] = return empty
882 go n env ((is_landmark, ctxt) : ctxts)
883 | is_landmark || n < mAX_CONTEXTS -- Too verbose || opt_PprStyle_Debug
884 = do { (env', msg) <- ctxt env
885 ; let n' = if is_landmark then n else n+1
886 ; rest <- go n' env' ctxts
887 ; return (msg $$ rest) }
891 mAX_CONTEXTS :: Int -- No more than this number of non-landmark contexts
895 debugTc is useful for monadic debugging code
898 debugTc :: TcM () -> TcM ()
901 | otherwise = return ()
904 %************************************************************************
908 %************************************************************************
911 newTcEvBinds :: TcM EvBindsVar
912 newTcEvBinds = do { ref <- newTcRef emptyEvBindMap
914 ; return (EvBindsVar ref uniq) }
916 extendTcEvBinds :: TcEvBinds -> EvVar -> EvTerm -> TcM TcEvBinds
917 extendTcEvBinds binds@(TcEvBinds binds_var) var rhs
918 = do { addTcEvBind binds_var var rhs
920 extendTcEvBinds (EvBinds bnds) var rhs
921 = return (EvBinds (bnds `snocBag` EvBind var rhs))
923 addTcEvBind :: EvBindsVar -> EvVar -> EvTerm -> TcM ()
924 -- Add a binding to the TcEvBinds by side effect
925 addTcEvBind (EvBindsVar ev_ref _) var rhs
926 = do { bnds <- readTcRef ev_ref
927 ; writeTcRef ev_ref (extendEvBinds bnds var rhs) }
929 chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
930 chooseUniqueOccTc fn =
931 do { env <- getGblEnv
932 ; let dfun_n_var = tcg_dfun_n env
933 ; set <- readTcRef dfun_n_var
935 ; writeTcRef dfun_n_var (extendOccSet set occ)
938 getConstraintVar :: TcM (TcRef WantedConstraints)
939 getConstraintVar = do { env <- getLclEnv; return (tcl_lie env) }
941 setConstraintVar :: TcRef WantedConstraints -> TcM a -> TcM a
942 setConstraintVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
944 emitConstraints :: WantedConstraints -> TcM ()
946 = do { lie_var <- getConstraintVar ;
947 updTcRef lie_var (`andWanteds` ct) }
949 emitConstraint :: WantedConstraint -> TcM ()
951 = do { lie_var <- getConstraintVar ;
952 updTcRef lie_var (`extendWanteds` ct) }
954 getConstraints :: TcM a -> TcM (a, WantedConstraints)
955 -- (getConstraints m) runs m, and returns the type constraints it generates
956 getConstraints thing_inside
957 = do { lie_var <- newTcRef emptyWanteds ;
958 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
960 lie <- readTcRef lie_var ;
963 setUntouchables :: TcTyVarSet -> TcM a -> TcM a
964 setUntouchables untch_tvs thing_inside
965 = updLclEnv (\ env -> env { tcl_untch = untch_tvs }) thing_inside
967 getUntouchables :: TcM TcTyVarSet
968 getUntouchables = do { env <- getLclEnv; return (tcl_untch env) }
969 -- NB: no need to zonk this TcTyVarSet: they are, after all, untouchable!
971 isUntouchable :: TcTyVar -> TcM Bool
972 isUntouchable tv = do { env <- getLclEnv; return (tv `elemVarSet` tcl_untch env) }
974 getLclTypeEnv :: TcM (NameEnv TcTyThing)
975 getLclTypeEnv = do { env <- getLclEnv; return (tcl_env env) }
977 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
978 -- Set the local type envt, but do *not* disturb other fields,
979 -- notably the lie_var
980 setLclTypeEnv lcl_env thing_inside
981 = updLclEnv upd thing_inside
983 upd env = env { tcl_env = tcl_env lcl_env,
984 tcl_tyvars = tcl_tyvars lcl_env }
988 %************************************************************************
990 Template Haskell context
992 %************************************************************************
995 recordThUse :: TcM ()
996 recordThUse = do { env <- getGblEnv; writeTcRef (tcg_th_used env) True }
998 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
1000 | isLocalId id = do { env <- getGblEnv;
1001 ; updTcRef (tcg_keep env) (`addOneToNameSet` idName id) }
1002 | otherwise = return ()
1004 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
1005 keepAliveSetTc ns = do { env <- getGblEnv;
1006 ; updTcRef (tcg_keep env) (`unionNameSets` ns) }
1008 getStage :: TcM ThStage
1009 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
1011 setStage :: ThStage -> TcM a -> TcM a
1012 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
1016 %************************************************************************
1018 Stuff for the renamer's local env
1020 %************************************************************************
1023 getLocalRdrEnv :: RnM LocalRdrEnv
1024 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
1026 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
1027 setLocalRdrEnv rdr_env thing_inside
1028 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
1032 %************************************************************************
1034 Stuff for interface decls
1036 %************************************************************************
1039 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
1040 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
1042 if_tv_env = emptyUFM,
1043 if_id_env = emptyUFM }
1045 initIfaceTcRn :: IfG a -> TcRn a
1046 initIfaceTcRn thing_inside
1047 = do { tcg_env <- getGblEnv
1048 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
1049 ; get_type_env = readTcRef (tcg_type_env_var tcg_env) }
1050 ; setEnvs (if_env, ()) thing_inside }
1052 initIfaceExtCore :: IfL a -> TcRn a
1053 initIfaceExtCore thing_inside
1054 = do { tcg_env <- getGblEnv
1055 ; let { mod = tcg_mod tcg_env
1056 ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
1057 ; if_env = IfGblEnv {
1058 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
1059 ; if_lenv = mkIfLclEnv mod doc
1061 ; setEnvs (if_env, if_lenv) thing_inside }
1063 initIfaceCheck :: HscEnv -> IfG a -> IO a
1064 -- Used when checking the up-to-date-ness of the old Iface
1065 -- Initialise the environment with no useful info at all
1066 initIfaceCheck hsc_env do_this
1067 = do let rec_types = case hsc_type_env_var hsc_env of
1068 Just (mod,var) -> Just (mod, readTcRef var)
1070 gbl_env = IfGblEnv { if_rec_types = rec_types }
1071 initTcRnIf 'i' hsc_env gbl_env () do_this
1073 initIfaceTc :: ModIface
1074 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
1075 -- Used when type-checking checking an up-to-date interface file
1076 -- No type envt from the current module, but we do know the module dependencies
1077 initIfaceTc iface do_this
1078 = do { tc_env_var <- newTcRef emptyTypeEnv
1079 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readTcRef tc_env_var) } ;
1080 ; if_lenv = mkIfLclEnv mod doc
1082 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
1085 mod = mi_module iface
1086 doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
1088 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
1089 -- Used when sucking in new Rules in SimplCore
1090 -- We have available the type envt of the module being compiled, and we must use it
1091 initIfaceRules hsc_env guts do_this
1093 type_info = (mg_module guts, return (mg_types guts))
1094 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
1097 -- Run the thing; any exceptions just bubble out from here
1098 ; initTcRnIf 'i' hsc_env gbl_env () do_this
1101 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
1102 initIfaceLcl mod loc_doc thing_inside
1103 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1105 getIfModule :: IfL Module
1106 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1108 --------------------
1109 failIfM :: Message -> IfL a
1110 -- The Iface monad doesn't have a place to accumulate errors, so we
1111 -- just fall over fast if one happens; it "shouldnt happen".
1112 -- We use IfL here so that we can get context info out of the local env
1114 = do { env <- getLclEnv
1115 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1116 ; liftIO (printErrs (full_msg defaultErrStyle))
1119 --------------------
1120 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1121 -- Run thing_inside in an interleaved thread.
1122 -- It shares everything with the parent thread, so this is DANGEROUS.
1124 -- It returns Nothing if the computation fails
1126 -- It's used for lazily type-checking interface
1127 -- signatures, which is pretty benign
1129 forkM_maybe doc thing_inside
1130 = do { unsafeInterleaveM $
1131 do { traceIf (text "Starting fork {" <+> doc)
1133 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1136 Right r -> do { traceIf (text "} ending fork" <+> doc)
1140 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1141 -- Otherwise we silently discard errors. Errors can legitimately
1142 -- happen when compiling interface signatures (see tcInterfaceSigs)
1143 ifDOptM Opt_D_dump_if_trace
1144 (print_errs (hang (text "forkM failed:" <+> doc)
1145 2 (text (show exn))))
1147 ; traceIf (text "} ending fork (badly)" <+> doc)
1151 print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1153 forkM :: SDoc -> IfL a -> IfL a
1154 forkM doc thing_inside
1155 = do { mb_res <- forkM_maybe doc thing_inside
1156 ; return (case mb_res of
1157 Nothing -> pgmError "Cannot continue after interface file error"
1158 -- pprPanic "forkM" doc