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) }
615 try_m :: TcRn r -> TcRn (Either IOEnvFailure r)
616 -- Does try_m, with a debug-trace on failure
618 = do { mb_r <- tryM thing ;
620 Left exn -> do { traceTc "tryTc/recoverM recovering from" $
621 text (showException exn)
623 Right _ -> return mb_r }
625 -----------------------
626 recoverM :: TcRn r -- Recovery action; do this if the main one fails
627 -> TcRn r -- Main action: do this first
629 -- Errors in 'thing' are retained
630 recoverM recover thing
631 = do { mb_res <- try_m thing ;
634 Right res -> return res }
637 -----------------------
638 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
639 -- Drop elements of the input that fail, so the result
640 -- list can be shorter than the argument list
641 mapAndRecoverM _ [] = return []
642 mapAndRecoverM f (x:xs) = do { mb_r <- try_m (f x)
643 ; rs <- mapAndRecoverM f xs
644 ; return (case mb_r of
649 -----------------------
650 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
651 -- (tryTc m) executes m, and returns
652 -- Just r, if m succeeds (returning r)
653 -- Nothing, if m fails
654 -- It also returns all the errors and warnings accumulated by m
655 -- It always succeeds (never raises an exception)
657 = do { errs_var <- newTcRef emptyMessages ;
658 res <- try_m (setErrsVar errs_var m) ;
659 msgs <- readTcRef errs_var ;
660 return (msgs, case res of
662 Right val -> Just val)
663 -- The exception is always the IOEnv built-in
664 -- in exception; see IOEnv.failM
667 -----------------------
668 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
669 -- Run the thing, returning
670 -- Just r, if m succceeds with no error messages
671 -- Nothing, if m fails, or if it succeeds but has error messages
672 -- Either way, the messages are returned; even in the Just case
673 -- there might be warnings
675 = do { (msgs, res) <- tryTc thing
677 ; let errs_found = errorsFound dflags msgs
678 ; return (msgs, case res of
680 Just val | errs_found -> Nothing
681 | otherwise -> Just val)
684 -----------------------
685 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
686 -- Just like tryTcErrs, except that it ensures that the LIE
687 -- for the thing is propagated only if there are no errors
688 -- Hence it's restricted to the type-check monad
689 tryTcLIE thing_inside
690 = do { ((msgs, mb_res), lie) <- captureConstraints (tryTcErrs thing_inside) ;
692 Nothing -> return (msgs, Nothing)
693 Just val -> do { emitConstraints lie; return (msgs, Just val) }
696 -----------------------
697 tryTcLIE_ :: TcM r -> TcM r -> TcM r
698 -- (tryTcLIE_ r m) tries m;
699 -- if m succeeds with no error messages, it's the answer
700 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
701 tryTcLIE_ recover main
702 = do { (msgs, mb_res) <- tryTcLIE main
704 Just val -> do { addMessages msgs -- There might be warnings
706 Nothing -> recover -- Discard all msgs
709 -----------------------
710 checkNoErrs :: TcM r -> TcM r
711 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
712 -- If m fails then (checkNoErrsTc m) fails.
713 -- If m succeeds, it checks whether m generated any errors messages
714 -- (it might have recovered internally)
715 -- If so, it fails too.
716 -- Regardless, any errors generated by m are propagated to the enclosing context.
718 = do { (msgs, mb_res) <- tryTcLIE main
722 Just val -> return val
725 ifErrsM :: TcRn r -> TcRn r -> TcRn r
726 -- ifErrsM bale_out main
727 -- does 'bale_out' if there are errors in errors collection
728 -- otherwise does 'main'
729 ifErrsM bale_out normal
730 = do { errs_var <- getErrsVar ;
731 msgs <- readTcRef errs_var ;
733 if errorsFound dflags msgs then
738 failIfErrsM :: TcRn ()
739 -- Useful to avoid error cascades
740 failIfErrsM = ifErrsM failM (return ())
744 %************************************************************************
746 Context management for the type checker
748 %************************************************************************
751 getErrCtxt :: TcM [ErrCtxt]
752 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
754 setErrCtxt :: [ErrCtxt] -> TcM a -> TcM a
755 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
757 addErrCtxt :: Message -> TcM a -> TcM a
758 addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
760 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
761 addErrCtxtM ctxt = updCtxt (\ ctxts -> (False, ctxt) : ctxts)
763 addLandmarkErrCtxt :: Message -> TcM a -> TcM a
764 addLandmarkErrCtxt msg = updCtxt (\ctxts -> (True, \env -> return (env,msg)) : ctxts)
766 -- Helper function for the above
767 updCtxt :: ([ErrCtxt] -> [ErrCtxt]) -> TcM a -> TcM a
768 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
769 env { tcl_ctxt = upd ctxt })
771 -- Conditionally add an error context
772 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
773 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
774 maybeAddErrCtxt Nothing thing_inside = thing_inside
776 popErrCtxt :: TcM a -> TcM a
777 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
779 getCtLoc :: orig -> TcM (CtLoc orig)
781 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
782 return (CtLoc origin loc (tcl_ctxt env)) }
784 setCtLoc :: CtLoc orig -> TcM a -> TcM a
785 setCtLoc (CtLoc _ src_loc ctxt) thing_inside
786 = setSrcSpan src_loc (setErrCtxt ctxt thing_inside)
789 %************************************************************************
791 Error message generation (type checker)
793 %************************************************************************
795 The addErrTc functions add an error message, but do not cause failure.
796 The 'M' variants pass a TidyEnv that has already been used to
797 tidy up the message; we then use it to tidy the context messages
800 addErrTc :: Message -> TcM ()
801 addErrTc err_msg = do { env0 <- tcInitTidyEnv
802 ; addErrTcM (env0, err_msg) }
804 addErrsTc :: [Message] -> TcM ()
805 addErrsTc err_msgs = mapM_ addErrTc err_msgs
807 addErrTcM :: (TidyEnv, Message) -> TcM ()
808 addErrTcM (tidy_env, err_msg)
809 = do { ctxt <- getErrCtxt ;
811 add_err_tcm tidy_env err_msg loc ctxt }
814 The failWith functions add an error message and cause failure
817 failWithTc :: Message -> TcM a -- Add an error message and fail
819 = addErrTc err_msg >> failM
821 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
822 failWithTcM local_and_msg
823 = addErrTcM local_and_msg >> failM
825 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
826 checkTc True _ = return ()
827 checkTc False err = failWithTc err
830 Warnings have no 'M' variant, nor failure
833 addWarnTc :: Message -> TcM ()
834 addWarnTc msg = do { env0 <- tcInitTidyEnv
835 ; addWarnTcM (env0, msg) }
837 addWarnTcM :: (TidyEnv, Message) -> TcM ()
838 addWarnTcM (env0, msg)
839 = do { ctxt <- getErrCtxt ;
840 err_info <- mkErrInfo env0 ctxt ;
841 addReport (ptext (sLit "Warning:") <+> msg) err_info }
843 warnTc :: Bool -> Message -> TcM ()
844 warnTc warn_if_true warn_msg
845 | warn_if_true = addWarnTc warn_msg
846 | otherwise = return ()
849 -----------------------------------
852 We initialise the "tidy-env", used for tidying types before printing,
853 by building a reverse map from the in-scope type variables to the
854 OccName that the programmer originally used for them
857 tcInitTidyEnv :: TcM TidyEnv
859 = do { lcl_env <- getLclEnv
860 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
861 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
863 ; return (foldl add emptyTidyEnv nm_tv_prs) }
865 add (env,subst) (name, tyvar)
866 = case tidyOccName env (nameOccName name) of
867 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
869 tyvar' = setTyVarName tyvar name'
870 name' = tidyNameOcc name occ'
873 -----------------------------------
874 Other helper functions
877 add_err_tcm :: TidyEnv -> Message -> SrcSpan
880 add_err_tcm tidy_env err_msg loc ctxt
881 = do { err_info <- mkErrInfo tidy_env ctxt ;
882 addLongErrAt loc err_msg err_info }
884 mkErrInfo :: TidyEnv -> [ErrCtxt] -> TcM SDoc
885 -- Tidy the error info, trimming excessive contexts
889 go :: Int -> TidyEnv -> [ErrCtxt] -> TcM SDoc
890 go _ _ [] = return empty
891 go n env ((is_landmark, ctxt) : ctxts)
892 | is_landmark || n < mAX_CONTEXTS -- Too verbose || opt_PprStyle_Debug
893 = do { (env', msg) <- ctxt env
894 ; let n' = if is_landmark then n else n+1
895 ; rest <- go n' env' ctxts
896 ; return (msg $$ rest) }
900 mAX_CONTEXTS :: Int -- No more than this number of non-landmark contexts
904 debugTc is useful for monadic debugging code
907 debugTc :: TcM () -> TcM ()
910 | otherwise = return ()
913 %************************************************************************
917 %************************************************************************
920 newTcEvBinds :: TcM EvBindsVar
921 newTcEvBinds = do { ref <- newTcRef emptyEvBindMap
923 ; return (EvBindsVar ref uniq) }
925 extendTcEvBinds :: TcEvBinds -> EvVar -> EvTerm -> TcM TcEvBinds
926 extendTcEvBinds binds@(TcEvBinds binds_var) var rhs
927 = do { addTcEvBind binds_var var rhs
929 extendTcEvBinds (EvBinds bnds) var rhs
930 = return (EvBinds (bnds `snocBag` EvBind var rhs))
932 addTcEvBind :: EvBindsVar -> EvVar -> EvTerm -> TcM ()
933 -- Add a binding to the TcEvBinds by side effect
934 addTcEvBind (EvBindsVar ev_ref _) var rhs
935 = do { bnds <- readTcRef ev_ref
936 ; writeTcRef ev_ref (extendEvBinds bnds var rhs) }
938 chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
939 chooseUniqueOccTc fn =
940 do { env <- getGblEnv
941 ; let dfun_n_var = tcg_dfun_n env
942 ; set <- readTcRef dfun_n_var
944 ; writeTcRef dfun_n_var (extendOccSet set occ)
947 getConstraintVar :: TcM (TcRef WantedConstraints)
948 getConstraintVar = do { env <- getLclEnv; return (tcl_lie env) }
950 setConstraintVar :: TcRef WantedConstraints -> TcM a -> TcM a
951 setConstraintVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
953 emitConstraints :: WantedConstraints -> TcM ()
955 = do { lie_var <- getConstraintVar ;
956 updTcRef lie_var (`andWanteds` ct) }
958 emitConstraint :: WantedConstraint -> TcM ()
960 = do { lie_var <- getConstraintVar ;
961 updTcRef lie_var (`extendWanteds` ct) }
963 captureConstraints :: TcM a -> TcM (a, WantedConstraints)
964 -- (captureConstraints m) runs m, and returns the type constraints it generates
965 captureConstraints thing_inside
966 = do { lie_var <- newTcRef emptyWanteds ;
967 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
969 lie <- readTcRef lie_var ;
972 captureUntouchables :: TcM a -> TcM (a, Untouchables)
973 captureUntouchables thing_inside
974 = do { env <- getLclEnv
975 ; low_meta <- readTcRef (tcl_meta env)
976 ; res <- setLclEnv (env { tcl_untch = low_meta })
978 ; high_meta <- readTcRef (tcl_meta env)
979 ; return (res, TouchableRange low_meta high_meta) }
981 isUntouchable :: TcTyVar -> TcM Bool
982 isUntouchable tv = do { env <- getLclEnv
983 ; return (varUnique tv < tcl_untch env) }
985 getLclTypeEnv :: TcM (NameEnv TcTyThing)
986 getLclTypeEnv = do { env <- getLclEnv; return (tcl_env env) }
988 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
989 -- Set the local type envt, but do *not* disturb other fields,
990 -- notably the lie_var
991 setLclTypeEnv lcl_env thing_inside
992 = updLclEnv upd thing_inside
994 upd env = env { tcl_env = tcl_env lcl_env,
995 tcl_tyvars = tcl_tyvars lcl_env }
999 %************************************************************************
1001 Template Haskell context
1003 %************************************************************************
1006 recordThUse :: TcM ()
1007 recordThUse = do { env <- getGblEnv; writeTcRef (tcg_th_used env) True }
1009 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
1011 | isLocalId id = do { env <- getGblEnv;
1012 ; updTcRef (tcg_keep env) (`addOneToNameSet` idName id) }
1013 | otherwise = return ()
1015 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
1016 keepAliveSetTc ns = do { env <- getGblEnv;
1017 ; updTcRef (tcg_keep env) (`unionNameSets` ns) }
1019 getStage :: TcM ThStage
1020 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
1022 setStage :: ThStage -> TcM a -> TcM a
1023 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
1027 %************************************************************************
1029 Stuff for the renamer's local env
1031 %************************************************************************
1034 getLocalRdrEnv :: RnM LocalRdrEnv
1035 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
1037 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
1038 setLocalRdrEnv rdr_env thing_inside
1039 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
1043 %************************************************************************
1045 Stuff for interface decls
1047 %************************************************************************
1050 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
1051 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
1053 if_tv_env = emptyUFM,
1054 if_id_env = emptyUFM }
1056 initIfaceTcRn :: IfG a -> TcRn a
1057 initIfaceTcRn thing_inside
1058 = do { tcg_env <- getGblEnv
1059 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
1060 ; get_type_env = readTcRef (tcg_type_env_var tcg_env) }
1061 ; setEnvs (if_env, ()) thing_inside }
1063 initIfaceExtCore :: IfL a -> TcRn a
1064 initIfaceExtCore thing_inside
1065 = do { tcg_env <- getGblEnv
1066 ; let { mod = tcg_mod tcg_env
1067 ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
1068 ; if_env = IfGblEnv {
1069 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
1070 ; if_lenv = mkIfLclEnv mod doc
1072 ; setEnvs (if_env, if_lenv) thing_inside }
1074 initIfaceCheck :: HscEnv -> IfG a -> IO a
1075 -- Used when checking the up-to-date-ness of the old Iface
1076 -- Initialise the environment with no useful info at all
1077 initIfaceCheck hsc_env do_this
1078 = do let rec_types = case hsc_type_env_var hsc_env of
1079 Just (mod,var) -> Just (mod, readTcRef var)
1081 gbl_env = IfGblEnv { if_rec_types = rec_types }
1082 initTcRnIf 'i' hsc_env gbl_env () do_this
1084 initIfaceTc :: ModIface
1085 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
1086 -- Used when type-checking checking an up-to-date interface file
1087 -- No type envt from the current module, but we do know the module dependencies
1088 initIfaceTc iface do_this
1089 = do { tc_env_var <- newTcRef emptyTypeEnv
1090 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readTcRef tc_env_var) } ;
1091 ; if_lenv = mkIfLclEnv mod doc
1093 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
1096 mod = mi_module iface
1097 doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
1099 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
1100 -- Used when sucking in new Rules in SimplCore
1101 -- We have available the type envt of the module being compiled, and we must use it
1102 initIfaceRules hsc_env guts do_this
1104 type_info = (mg_module guts, return (mg_types guts))
1105 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
1108 -- Run the thing; any exceptions just bubble out from here
1109 ; initTcRnIf 'i' hsc_env gbl_env () do_this
1112 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
1113 initIfaceLcl mod loc_doc thing_inside
1114 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1116 getIfModule :: IfL Module
1117 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1119 --------------------
1120 failIfM :: Message -> IfL a
1121 -- The Iface monad doesn't have a place to accumulate errors, so we
1122 -- just fall over fast if one happens; it "shouldnt happen".
1123 -- We use IfL here so that we can get context info out of the local env
1125 = do { env <- getLclEnv
1126 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1127 ; liftIO (printErrs (full_msg defaultErrStyle))
1130 --------------------
1131 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1132 -- Run thing_inside in an interleaved thread.
1133 -- It shares everything with the parent thread, so this is DANGEROUS.
1135 -- It returns Nothing if the computation fails
1137 -- It's used for lazily type-checking interface
1138 -- signatures, which is pretty benign
1140 forkM_maybe doc thing_inside
1141 = do { unsafeInterleaveM $
1142 do { traceIf (text "Starting fork {" <+> doc)
1144 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1147 Right r -> do { traceIf (text "} ending fork" <+> doc)
1151 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1152 -- Otherwise we silently discard errors. Errors can legitimately
1153 -- happen when compiling interface signatures (see tcInterfaceSigs)
1154 ifDOptM Opt_D_dump_if_trace
1155 (print_errs (hang (text "forkM failed:" <+> doc)
1156 2 (text (show exn))))
1158 ; traceIf (text "} ending fork (badly)" <+> doc)
1162 print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1164 forkM :: SDoc -> IfL a -> IfL a
1165 forkM doc thing_inside
1166 = do { mb_res <- forkM_maybe doc thing_inside
1167 ; return (case mb_res of
1168 Nothing -> pgmError "Cannot continue after interface file error"
1169 -- pprPanic "forkM" doc