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 meta_var <- newIORef initTyVarUnique ;
73 tvs_var <- newIORef emptyVarSet ;
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 = emptyGlobalRdrEnv,
92 tcg_fix_env = emptyNameEnv,
93 tcg_field_env = RecFields emptyNameEnv emptyNameSet,
94 tcg_default = Nothing,
95 tcg_type_env = emptyNameEnv,
96 tcg_type_env_var = type_env_var,
97 tcg_inst_env = emptyInstEnv,
98 tcg_fam_inst_env = emptyFamInstEnv,
101 tcg_imports = emptyImportAvails,
102 tcg_used_rdrnames = used_rdr_var,
106 tcg_rn_exports = maybe_rn_syntax [],
107 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
109 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,
136 tcl_untch = initTyVarUnique
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)
170 initTcPrintErrors env mod todo = 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 (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 newMetaUnique :: TcM Unique
318 -- The uniques for TcMetaTyVars are allocated specially
319 -- in guaranteed linear order, starting at zero for each module
321 = do { env <- getLclEnv
322 ; let meta_var = tcl_meta env
323 ; uniq <- readMutVar meta_var
324 ; writeMutVar meta_var (incrUnique uniq)
327 newUnique :: TcRnIf gbl lcl Unique
329 = do { env <- getEnv ;
330 let { u_var = env_us env } ;
331 us <- readMutVar u_var ;
332 case takeUniqFromSupply us of { (uniq, us') -> do {
333 writeMutVar u_var us' ;
335 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
336 -- a chain of unevaluated supplies behind.
337 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
338 -- throw away one half of the new split supply. This is safe because this
339 -- is the only place we use that unique. Using the other half of the split
340 -- supply is safer, but slower.
342 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
344 = do { env <- getEnv ;
345 let { u_var = env_us env } ;
346 us <- readMutVar u_var ;
347 case splitUniqSupply us of { (us1,us2) -> do {
348 writeMutVar u_var us1 ;
351 newLocalName :: Name -> TcRnIf gbl lcl Name
352 newLocalName name -- Make a clone
353 = do { uniq <- newUnique
354 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
356 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
357 newSysLocalIds fs tys
358 = do { us <- newUniqueSupply
359 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
361 instance MonadUnique (IOEnv (Env gbl lcl)) where
362 getUniqueM = newUnique
363 getUniqueSupplyM = newUniqueSupply
367 %************************************************************************
371 %************************************************************************
374 newTcRef :: a -> TcRnIf gbl lcl (TcRef a)
377 readTcRef :: TcRef a -> TcRnIf gbl lcl a
378 readTcRef = readMutVar
380 writeTcRef :: TcRef a -> a -> TcRnIf gbl lcl ()
381 writeTcRef = writeMutVar
383 updTcRef :: TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
387 %************************************************************************
391 %************************************************************************
394 traceTc :: String -> SDoc -> TcRn ()
397 traceTcN :: Int -> String -> SDoc -> TcRn ()
398 traceTcN level herald doc
399 | level <= opt_TraceLevel = traceOptTcRn Opt_D_dump_tc_trace $
400 hang (text herald) 2 doc
401 | otherwise = return ()
403 traceRn, traceSplice :: SDoc -> TcRn ()
404 traceRn = traceOptTcRn Opt_D_dump_rn_trace
405 traceSplice = traceOptTcRn Opt_D_dump_splices
408 traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()
409 traceIf = traceOptIf Opt_D_dump_if_trace
410 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
413 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
414 traceOptIf flag doc = ifDOptM flag $
415 liftIO (printForUser stderr alwaysQualify doc)
417 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
418 -- Output the message, with current location if opt_PprStyle_Debug
419 traceOptTcRn flag doc = ifDOptM flag $ do
422 | opt_PprStyle_Debug = mkLocMessage loc doc
423 | otherwise = doc -- The full location is
424 -- usually way too much
425 ; dumpTcRn real_doc }
427 dumpTcRn :: SDoc -> TcRn ()
428 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv
430 ; liftIO (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
432 debugDumpTcRn :: SDoc -> TcRn ()
433 debugDumpTcRn doc | opt_NoDebugOutput = return ()
434 | otherwise = dumpTcRn doc
436 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
437 dumpOptTcRn flag doc = ifDOptM flag (dumpTcRn doc)
441 %************************************************************************
443 Typechecker global environment
445 %************************************************************************
448 getModule :: TcRn Module
449 getModule = do { env <- getGblEnv; return (tcg_mod env) }
451 setModule :: Module -> TcRn a -> TcRn a
452 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
454 tcIsHsBoot :: TcRn Bool
455 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
457 getGlobalRdrEnv :: TcRn GlobalRdrEnv
458 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
460 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
461 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
463 getImports :: TcRn ImportAvails
464 getImports = do { env <- getGblEnv; return (tcg_imports env) }
466 getFixityEnv :: TcRn FixityEnv
467 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
469 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
470 extendFixityEnv new_bit
471 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
472 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
474 getRecFieldEnv :: TcRn RecFieldEnv
475 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
477 getDeclaredDefaultTys :: TcRn (Maybe [Type])
478 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
481 %************************************************************************
485 %************************************************************************
488 getSrcSpanM :: TcRn SrcSpan
489 -- Avoid clash with Name.getSrcLoc
490 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
492 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
493 setSrcSpan loc thing_inside
494 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
495 | otherwise = thing_inside -- Don't overwrite useful info with useless
497 addLocM :: (a -> TcM b) -> Located a -> TcM b
498 addLocM fn (L loc a) = setSrcSpan loc $ fn a
500 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
501 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
503 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
504 wrapLocFstM fn (L loc a) =
509 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
510 wrapLocSndM fn (L loc a) =
519 getErrsVar :: TcRn (TcRef Messages)
520 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
522 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
523 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
525 addErr :: Message -> TcRn () -- Ignores the context stack
526 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
528 failWith :: Message -> TcRn a
529 failWith msg = addErr msg >> failM
531 addErrAt :: SrcSpan -> Message -> TcRn ()
532 -- addErrAt is mainly (exclusively?) used by the renamer, where
533 -- tidying is not an issue, but it's all lazy so the extra
534 -- work doesn't matter
535 addErrAt loc msg = do { ctxt <- getErrCtxt
536 ; tidy_env <- tcInitTidyEnv
537 ; err_info <- mkErrInfo tidy_env ctxt
538 ; addLongErrAt loc msg err_info }
540 addErrs :: [(SrcSpan,Message)] -> TcRn ()
541 addErrs msgs = mapM_ add msgs
543 add (loc,msg) = addErrAt loc msg
545 addWarn :: Message -> TcRn ()
546 addWarn msg = addReport (ptext (sLit "Warning:") <+> msg) empty
548 addWarnAt :: SrcSpan -> Message -> TcRn ()
549 addWarnAt loc msg = addReportAt loc (ptext (sLit "Warning:") <+> msg) empty
551 checkErr :: Bool -> Message -> TcRn ()
552 -- Add the error if the bool is False
553 checkErr ok msg = unless ok (addErr msg)
555 warnIf :: Bool -> Message -> TcRn ()
556 warnIf True msg = addWarn msg
557 warnIf False _ = return ()
559 addMessages :: Messages -> TcRn ()
560 addMessages (m_warns, m_errs)
561 = do { errs_var <- getErrsVar ;
562 (warns, errs) <- readTcRef errs_var ;
563 writeTcRef errs_var (warns `unionBags` m_warns,
564 errs `unionBags` m_errs) }
566 discardWarnings :: TcRn a -> TcRn a
567 -- Ignore warnings inside the thing inside;
568 -- used to ignore-unused-variable warnings inside derived code
569 -- With -dppr-debug, the effects is switched off, so you can still see
570 -- what warnings derived code would give
571 discardWarnings thing_inside
572 | opt_PprStyle_Debug = thing_inside
574 = do { errs_var <- newTcRef emptyMessages
575 ; result <- setErrsVar errs_var thing_inside
576 ; (_warns, errs) <- readTcRef errs_var
577 ; addMessages (emptyBag, errs)
582 %************************************************************************
584 Shared error message stuff: renamer and typechecker
586 %************************************************************************
589 addReport :: Message -> Message -> TcRn ()
590 addReport msg extra_info = do loc <- getSrcSpanM; addReportAt loc msg extra_info
592 addReportAt :: SrcSpan -> Message -> Message -> TcRn ()
593 addReportAt loc msg extra_info
594 = do { errs_var <- getErrsVar ;
595 rdr_env <- getGlobalRdrEnv ;
597 let { warn = mkLongWarnMsg loc (mkPrintUnqualified dflags rdr_env)
599 (warns, errs) <- readTcRef errs_var ;
600 writeTcRef errs_var (warns `snocBag` warn, errs) }
602 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
603 addLongErrAt loc msg extra
604 = do { traceTc "Adding error:" (mkLocMessage loc (msg $$ extra)) ;
605 errs_var <- getErrsVar ;
606 rdr_env <- getGlobalRdrEnv ;
608 let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
609 (warns, errs) <- readTcRef errs_var ;
610 writeTcRef errs_var (warns, errs `snocBag` err) }
612 dumpDerivingInfo :: SDoc -> TcM ()
614 = do { dflags <- getDOpts
615 ; when (dopt Opt_D_dump_deriv dflags) $ do
616 { rdr_env <- getGlobalRdrEnv
617 ; let unqual = mkPrintUnqualified dflags rdr_env
618 ; liftIO (putMsgWith dflags unqual doc) } }
623 try_m :: TcRn r -> TcRn (Either IOEnvFailure r)
624 -- Does try_m, with a debug-trace on failure
626 = do { mb_r <- tryM thing ;
628 Left exn -> do { traceTc "tryTc/recoverM recovering from" $
629 text (showException exn)
631 Right _ -> return mb_r }
633 -----------------------
634 recoverM :: TcRn r -- Recovery action; do this if the main one fails
635 -> TcRn r -- Main action: do this first
637 -- Errors in 'thing' are retained
638 recoverM recover thing
639 = do { mb_res <- try_m thing ;
642 Right res -> return res }
645 -----------------------
646 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
647 -- Drop elements of the input that fail, so the result
648 -- list can be shorter than the argument list
649 mapAndRecoverM _ [] = return []
650 mapAndRecoverM f (x:xs) = do { mb_r <- try_m (f x)
651 ; rs <- mapAndRecoverM f xs
652 ; return (case mb_r of
657 -----------------------
658 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
659 -- (tryTc m) executes m, and returns
660 -- Just r, if m succeeds (returning r)
661 -- Nothing, if m fails
662 -- It also returns all the errors and warnings accumulated by m
663 -- It always succeeds (never raises an exception)
665 = do { errs_var <- newTcRef emptyMessages ;
666 res <- try_m (setErrsVar errs_var m) ;
667 msgs <- readTcRef errs_var ;
668 return (msgs, case res of
670 Right val -> Just val)
671 -- The exception is always the IOEnv built-in
672 -- in exception; see IOEnv.failM
675 -----------------------
676 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
677 -- Run the thing, returning
678 -- Just r, if m succceeds with no error messages
679 -- Nothing, if m fails, or if it succeeds but has error messages
680 -- Either way, the messages are returned; even in the Just case
681 -- there might be warnings
683 = do { (msgs, res) <- tryTc thing
685 ; let errs_found = errorsFound dflags msgs
686 ; return (msgs, case res of
688 Just val | errs_found -> Nothing
689 | otherwise -> Just val)
692 -----------------------
693 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
694 -- Just like tryTcErrs, except that it ensures that the LIE
695 -- for the thing is propagated only if there are no errors
696 -- Hence it's restricted to the type-check monad
697 tryTcLIE thing_inside
698 = do { ((msgs, mb_res), lie) <- captureConstraints (tryTcErrs thing_inside) ;
700 Nothing -> return (msgs, Nothing)
701 Just val -> do { emitConstraints lie; return (msgs, Just val) }
704 -----------------------
705 tryTcLIE_ :: TcM r -> TcM r -> TcM r
706 -- (tryTcLIE_ r m) tries m;
707 -- if m succeeds with no error messages, it's the answer
708 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
709 tryTcLIE_ recover main
710 = do { (msgs, mb_res) <- tryTcLIE main
712 Just val -> do { addMessages msgs -- There might be warnings
714 Nothing -> recover -- Discard all msgs
717 -----------------------
718 checkNoErrs :: TcM r -> TcM r
719 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
720 -- If m fails then (checkNoErrsTc m) fails.
721 -- If m succeeds, it checks whether m generated any errors messages
722 -- (it might have recovered internally)
723 -- If so, it fails too.
724 -- Regardless, any errors generated by m are propagated to the enclosing context.
726 = do { (msgs, mb_res) <- tryTcLIE main
730 Just val -> return val
733 ifErrsM :: TcRn r -> TcRn r -> TcRn r
734 -- ifErrsM bale_out main
735 -- does 'bale_out' if there are errors in errors collection
736 -- otherwise does 'main'
737 ifErrsM bale_out normal
738 = do { errs_var <- getErrsVar ;
739 msgs <- readTcRef errs_var ;
741 if errorsFound dflags msgs then
746 failIfErrsM :: TcRn ()
747 -- Useful to avoid error cascades
748 failIfErrsM = ifErrsM failM (return ())
752 %************************************************************************
754 Context management for the type checker
756 %************************************************************************
759 getErrCtxt :: TcM [ErrCtxt]
760 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
762 setErrCtxt :: [ErrCtxt] -> TcM a -> TcM a
763 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
765 addErrCtxt :: Message -> TcM a -> TcM a
766 addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
768 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
769 addErrCtxtM ctxt = updCtxt (\ ctxts -> (False, ctxt) : ctxts)
771 addLandmarkErrCtxt :: Message -> TcM a -> TcM a
772 addLandmarkErrCtxt msg = updCtxt (\ctxts -> (True, \env -> return (env,msg)) : ctxts)
774 -- Helper function for the above
775 updCtxt :: ([ErrCtxt] -> [ErrCtxt]) -> TcM a -> TcM a
776 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
777 env { tcl_ctxt = upd ctxt })
779 -- Conditionally add an error context
780 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
781 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
782 maybeAddErrCtxt Nothing thing_inside = thing_inside
784 popErrCtxt :: TcM a -> TcM a
785 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
787 getCtLoc :: orig -> TcM (CtLoc orig)
789 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
790 return (CtLoc origin loc (tcl_ctxt env)) }
792 setCtLoc :: CtLoc orig -> TcM a -> TcM a
793 setCtLoc (CtLoc _ src_loc ctxt) thing_inside
794 = setSrcSpan src_loc (setErrCtxt ctxt thing_inside)
797 %************************************************************************
799 Error message generation (type checker)
801 %************************************************************************
803 The addErrTc functions add an error message, but do not cause failure.
804 The 'M' variants pass a TidyEnv that has already been used to
805 tidy up the message; we then use it to tidy the context messages
808 addErrTc :: Message -> TcM ()
809 addErrTc err_msg = do { env0 <- tcInitTidyEnv
810 ; addErrTcM (env0, err_msg) }
812 addErrsTc :: [Message] -> TcM ()
813 addErrsTc err_msgs = mapM_ addErrTc err_msgs
815 addErrTcM :: (TidyEnv, Message) -> TcM ()
816 addErrTcM (tidy_env, err_msg)
817 = do { ctxt <- getErrCtxt ;
819 add_err_tcm tidy_env err_msg loc ctxt }
822 The failWith functions add an error message and cause failure
825 failWithTc :: Message -> TcM a -- Add an error message and fail
827 = addErrTc err_msg >> failM
829 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
830 failWithTcM local_and_msg
831 = addErrTcM local_and_msg >> failM
833 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
834 checkTc True _ = return ()
835 checkTc False err = failWithTc err
838 Warnings have no 'M' variant, nor failure
841 addWarnTc :: Message -> TcM ()
842 addWarnTc msg = do { env0 <- tcInitTidyEnv
843 ; addWarnTcM (env0, msg) }
845 addWarnTcM :: (TidyEnv, Message) -> TcM ()
846 addWarnTcM (env0, msg)
847 = do { ctxt <- getErrCtxt ;
848 err_info <- mkErrInfo env0 ctxt ;
849 addReport (ptext (sLit "Warning:") <+> msg) err_info }
851 warnTc :: Bool -> Message -> TcM ()
852 warnTc warn_if_true warn_msg
853 | warn_if_true = addWarnTc warn_msg
854 | otherwise = return ()
857 -----------------------------------
860 We initialise the "tidy-env", used for tidying types before printing,
861 by building a reverse map from the in-scope type variables to the
862 OccName that the programmer originally used for them
865 tcInitTidyEnv :: TcM TidyEnv
867 = do { lcl_env <- getLclEnv
868 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
869 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
871 ; return (foldl add emptyTidyEnv nm_tv_prs) }
873 add (env,subst) (name, tyvar)
874 = case tidyOccName env (nameOccName name) of
875 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
877 tyvar' = setTyVarName tyvar name'
878 name' = tidyNameOcc name occ'
881 -----------------------------------
882 Other helper functions
885 add_err_tcm :: TidyEnv -> Message -> SrcSpan
888 add_err_tcm tidy_env err_msg loc ctxt
889 = do { err_info <- mkErrInfo tidy_env ctxt ;
890 addLongErrAt loc err_msg err_info }
892 mkErrInfo :: TidyEnv -> [ErrCtxt] -> TcM SDoc
893 -- Tidy the error info, trimming excessive contexts
897 go :: Int -> TidyEnv -> [ErrCtxt] -> TcM SDoc
898 go _ _ [] = return empty
899 go n env ((is_landmark, ctxt) : ctxts)
900 | is_landmark || n < mAX_CONTEXTS -- Too verbose || opt_PprStyle_Debug
901 = do { (env', msg) <- ctxt env
902 ; let n' = if is_landmark then n else n+1
903 ; rest <- go n' env' ctxts
904 ; return (msg $$ rest) }
908 mAX_CONTEXTS :: Int -- No more than this number of non-landmark contexts
912 debugTc is useful for monadic debugging code
915 debugTc :: TcM () -> TcM ()
918 | otherwise = return ()
921 %************************************************************************
925 %************************************************************************
928 newTcEvBinds :: TcM EvBindsVar
929 newTcEvBinds = do { ref <- newTcRef emptyEvBindMap
931 ; return (EvBindsVar ref uniq) }
933 extendTcEvBinds :: TcEvBinds -> EvVar -> EvTerm -> TcM TcEvBinds
934 extendTcEvBinds binds@(TcEvBinds binds_var) var rhs
935 = do { addTcEvBind binds_var var rhs
937 extendTcEvBinds (EvBinds bnds) var rhs
938 = return (EvBinds (bnds `snocBag` EvBind var rhs))
940 addTcEvBind :: EvBindsVar -> EvVar -> EvTerm -> TcM ()
941 -- Add a binding to the TcEvBinds by side effect
942 addTcEvBind (EvBindsVar ev_ref _) var rhs
943 = do { bnds <- readTcRef ev_ref
944 ; writeTcRef ev_ref (extendEvBinds bnds var rhs) }
946 chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
947 chooseUniqueOccTc fn =
948 do { env <- getGblEnv
949 ; let dfun_n_var = tcg_dfun_n env
950 ; set <- readTcRef dfun_n_var
952 ; writeTcRef dfun_n_var (extendOccSet set occ)
955 getConstraintVar :: TcM (TcRef WantedConstraints)
956 getConstraintVar = do { env <- getLclEnv; return (tcl_lie env) }
958 setConstraintVar :: TcRef WantedConstraints -> TcM a -> TcM a
959 setConstraintVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
961 emitConstraints :: WantedConstraints -> TcM ()
963 = do { lie_var <- getConstraintVar ;
964 updTcRef lie_var (`andWanteds` ct) }
966 emitConstraint :: WantedConstraint -> TcM ()
968 = do { lie_var <- getConstraintVar ;
969 updTcRef lie_var (`extendWanteds` ct) }
971 captureConstraints :: TcM a -> TcM (a, WantedConstraints)
972 -- (captureConstraints m) runs m, and returns the type constraints it generates
973 captureConstraints thing_inside
974 = do { lie_var <- newTcRef emptyWanteds ;
975 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
977 lie <- readTcRef lie_var ;
980 captureUntouchables :: TcM a -> TcM (a, Untouchables)
981 captureUntouchables thing_inside
982 = do { env <- getLclEnv
983 ; low_meta <- readTcRef (tcl_meta env)
984 ; res <- setLclEnv (env { tcl_untch = low_meta })
986 ; high_meta <- readTcRef (tcl_meta env)
987 ; return (res, TouchableRange low_meta high_meta) }
989 isUntouchable :: TcTyVar -> TcM Bool
990 isUntouchable tv = do { env <- getLclEnv
991 ; return (varUnique tv < tcl_untch env) }
993 getLclTypeEnv :: TcM (NameEnv TcTyThing)
994 getLclTypeEnv = do { env <- getLclEnv; return (tcl_env env) }
996 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
997 -- Set the local type envt, but do *not* disturb other fields,
998 -- notably the lie_var
999 setLclTypeEnv lcl_env thing_inside
1000 = updLclEnv upd thing_inside
1002 upd env = env { tcl_env = tcl_env lcl_env,
1003 tcl_tyvars = tcl_tyvars lcl_env }
1007 %************************************************************************
1009 Template Haskell context
1011 %************************************************************************
1014 recordThUse :: TcM ()
1015 recordThUse = do { env <- getGblEnv; writeTcRef (tcg_th_used env) True }
1017 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
1019 | isLocalId id = do { env <- getGblEnv;
1020 ; updTcRef (tcg_keep env) (`addOneToNameSet` idName id) }
1021 | otherwise = return ()
1023 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
1024 keepAliveSetTc ns = do { env <- getGblEnv;
1025 ; updTcRef (tcg_keep env) (`unionNameSets` ns) }
1027 getStage :: TcM ThStage
1028 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
1030 setStage :: ThStage -> TcM a -> TcM a
1031 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
1035 %************************************************************************
1037 Stuff for the renamer's local env
1039 %************************************************************************
1042 getLocalRdrEnv :: RnM LocalRdrEnv
1043 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
1045 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
1046 setLocalRdrEnv rdr_env thing_inside
1047 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
1051 %************************************************************************
1053 Stuff for interface decls
1055 %************************************************************************
1058 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
1059 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
1061 if_tv_env = emptyUFM,
1062 if_id_env = emptyUFM }
1064 initIfaceTcRn :: IfG a -> TcRn a
1065 initIfaceTcRn thing_inside
1066 = do { tcg_env <- getGblEnv
1067 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
1068 ; get_type_env = readTcRef (tcg_type_env_var tcg_env) }
1069 ; setEnvs (if_env, ()) thing_inside }
1071 initIfaceExtCore :: IfL a -> TcRn a
1072 initIfaceExtCore thing_inside
1073 = do { tcg_env <- getGblEnv
1074 ; let { mod = tcg_mod tcg_env
1075 ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
1076 ; if_env = IfGblEnv {
1077 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
1078 ; if_lenv = mkIfLclEnv mod doc
1080 ; setEnvs (if_env, if_lenv) thing_inside }
1082 initIfaceCheck :: HscEnv -> IfG a -> IO a
1083 -- Used when checking the up-to-date-ness of the old Iface
1084 -- Initialise the environment with no useful info at all
1085 initIfaceCheck hsc_env do_this
1086 = do let rec_types = case hsc_type_env_var hsc_env of
1087 Just (mod,var) -> Just (mod, readTcRef var)
1089 gbl_env = IfGblEnv { if_rec_types = rec_types }
1090 initTcRnIf 'i' hsc_env gbl_env () do_this
1092 initIfaceTc :: ModIface
1093 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
1094 -- Used when type-checking checking an up-to-date interface file
1095 -- No type envt from the current module, but we do know the module dependencies
1096 initIfaceTc iface do_this
1097 = do { tc_env_var <- newTcRef emptyTypeEnv
1098 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readTcRef tc_env_var) } ;
1099 ; if_lenv = mkIfLclEnv mod doc
1101 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
1104 mod = mi_module iface
1105 doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
1107 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
1108 -- Used when sucking in new Rules in SimplCore
1109 -- We have available the type envt of the module being compiled, and we must use it
1110 initIfaceRules hsc_env guts do_this
1112 type_info = (mg_module guts, return (mg_types guts))
1113 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
1116 -- Run the thing; any exceptions just bubble out from here
1117 ; initTcRnIf 'i' hsc_env gbl_env () do_this
1120 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
1121 initIfaceLcl mod loc_doc thing_inside
1122 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1124 getIfModule :: IfL Module
1125 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1127 --------------------
1128 failIfM :: Message -> IfL a
1129 -- The Iface monad doesn't have a place to accumulate errors, so we
1130 -- just fall over fast if one happens; it "shouldnt happen".
1131 -- We use IfL here so that we can get context info out of the local env
1133 = do { env <- getLclEnv
1134 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1135 ; liftIO (printErrs (full_msg defaultErrStyle))
1138 --------------------
1139 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1140 -- Run thing_inside in an interleaved thread.
1141 -- It shares everything with the parent thread, so this is DANGEROUS.
1143 -- It returns Nothing if the computation fails
1145 -- It's used for lazily type-checking interface
1146 -- signatures, which is pretty benign
1148 forkM_maybe doc thing_inside
1149 = do { unsafeInterleaveM $
1150 do { traceIf (text "Starting fork {" <+> doc)
1152 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1155 Right r -> do { traceIf (text "} ending fork" <+> doc)
1159 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1160 -- Otherwise we silently discard errors. Errors can legitimately
1161 -- happen when compiling interface signatures (see tcInterfaceSigs)
1162 ifDOptM Opt_D_dump_if_trace
1163 (print_errs (hang (text "forkM failed:" <+> doc)
1164 2 (text (show exn))))
1166 ; traceIf (text "} ending fork (badly)" <+> doc)
1170 print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1172 forkM :: SDoc -> IfL a -> IfL a
1173 forkM doc thing_inside
1174 = do { mb_res <- forkM_maybe doc thing_inside
1175 ; return (case mb_res of
1176 Nothing -> pgmError "Cannot continue after interface file error"
1177 -- pprPanic "forkM" doc