2 % (c) The University of Glasgow 2006
7 -- The above warning supression flag is a temporary kludge.
8 -- While working on this module you are encouraged to remove it and fix
9 -- any warnings in the module. See
10 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
19 import TcRnTypes -- Re-export all
20 import IOEnv -- Re-export all
22 import HsSyn hiding (LIE)
54 import Control.Exception
60 %************************************************************************
64 %************************************************************************
70 -> Bool -- True <=> retain renamed syntax trees
73 -> IO (Messages, Maybe r)
74 -- Nothing => error thrown by the thing inside
75 -- (error messages should have been printed already)
77 initTc hsc_env hsc_src keep_rn_syntax mod do_this
78 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
79 tvs_var <- newIORef emptyVarSet ;
80 type_env_var <- newIORef emptyNameEnv ;
81 dfuns_var <- newIORef emptyNameSet ;
82 keep_var <- newIORef emptyNameSet ;
83 th_var <- newIORef False ;
84 dfun_n_var <- newIORef 1 ;
86 maybe_rn_syntax empty_val
87 | keep_rn_syntax = Just empty_val
88 | otherwise = Nothing ;
93 tcg_rdr_env = hsc_global_rdr_env hsc_env,
94 tcg_fix_env = emptyNameEnv,
95 tcg_field_env = emptyNameEnv,
96 tcg_default = Nothing,
97 tcg_type_env = hsc_global_type_env hsc_env,
98 tcg_type_env_var = type_env_var,
99 tcg_inst_env = emptyInstEnv,
100 tcg_fam_inst_env = emptyFamInstEnv,
101 tcg_inst_uses = dfuns_var,
102 tcg_th_used = th_var,
104 tcg_imports = emptyImportAvails,
107 tcg_rn_imports = maybe_rn_syntax [],
108 tcg_rn_exports = maybe_rn_syntax [],
109 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
111 tcg_binds = emptyLHsBinds,
112 tcg_deprecs = NoDeprecs,
117 tcg_dfun_n = dfun_n_var,
120 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing,
125 tcl_loc = mkGeneralSrcSpan (fsLit "Top level"),
127 tcl_rdr = emptyLocalRdrEnv,
128 tcl_th_ctxt = topStage,
129 tcl_arrow_ctxt = NoArrowCtxt,
130 tcl_env = emptyNameEnv,
131 tcl_tyvars = tvs_var,
132 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
136 -- OK, here's the business end!
137 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
138 do { r <- tryM do_this
140 Right res -> return (Just res)
141 Left _ -> return Nothing } ;
143 -- Collect any error messages
144 msgs <- readIORef errs_var ;
146 let { dflags = hsc_dflags hsc_env
147 ; final_res | errorsFound dflags msgs = Nothing
148 | otherwise = maybe_res } ;
150 return (msgs, final_res)
153 initTcPrintErrors -- Used from the interactive loop only
158 initTcPrintErrors env mod todo = do
159 (msgs, res) <- initTc env HsSrcFile False mod todo
160 printErrorsAndWarnings (hsc_dflags env) msgs
164 %************************************************************************
168 %************************************************************************
172 initTcRnIf :: Char -- Tag for unique supply
177 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
178 = do { us <- mkSplitUniqSupply uniq_tag ;
179 ; us_var <- newIORef us ;
181 ; let { env = Env { env_top = hsc_env,
186 ; runIOEnv env thing_inside
190 %************************************************************************
194 %************************************************************************
197 getTopEnv :: TcRnIf gbl lcl HscEnv
198 getTopEnv = do { env <- getEnv; return (env_top env) }
200 getGblEnv :: TcRnIf gbl lcl gbl
201 getGblEnv = do { env <- getEnv; return (env_gbl env) }
203 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
204 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
205 env { env_gbl = upd gbl })
207 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
208 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
210 getLclEnv :: TcRnIf gbl lcl lcl
211 getLclEnv = do { env <- getEnv; return (env_lcl env) }
213 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
214 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
215 env { env_lcl = upd lcl })
217 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
218 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
220 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
221 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
223 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
224 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
231 getDOpts :: TcRnIf gbl lcl DynFlags
232 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
234 doptM :: DynFlag -> TcRnIf gbl lcl Bool
235 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
237 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
238 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
239 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
241 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
242 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
243 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
245 -- | Do it flag is true
246 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
247 ifOptM flag thing_inside = do { b <- doptM flag;
248 if b then thing_inside else return () }
250 getGhcMode :: TcRnIf gbl lcl GhcMode
251 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
255 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
256 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
258 getEps :: TcRnIf gbl lcl ExternalPackageState
259 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
261 -- Updating the EPS. This should be an atomic operation.
262 -- Note the delicate 'seq' which forces the EPS before putting it in the
263 -- variable. Otherwise what happens is that we get
264 -- write eps_var (....(unsafeRead eps_var)....)
265 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
266 -- we make the unsafeRead happen before we update the variable.
268 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
270 updateEps upd_fn = do { traceIf (text "updating EPS")
271 ; eps_var <- getEpsVar
272 ; eps <- readMutVar eps_var
273 ; let { (eps', val) = upd_fn eps }
274 ; seq eps' (writeMutVar eps_var eps')
277 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
279 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
280 ; eps_var <- getEpsVar
281 ; eps <- readMutVar eps_var
282 ; let { eps' = upd_fn eps }
283 ; seq eps' (writeMutVar eps_var eps') }
285 getHpt :: TcRnIf gbl lcl HomePackageTable
286 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
288 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
289 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
290 ; return (eps, hsc_HPT env) }
293 %************************************************************************
297 %************************************************************************
300 newUnique :: TcRnIf gbl lcl Unique
302 = do { env <- getEnv ;
303 let { u_var = env_us env } ;
304 us <- readMutVar u_var ;
305 case splitUniqSupply us of { (us1,_) -> do {
306 writeMutVar u_var us1 ;
307 return $! uniqFromSupply us }}}
308 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
309 -- a chain of unevaluated supplies behind.
310 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
311 -- throw away one half of the new split supply. This is safe because this
312 -- is the only place we use that unique. Using the other half of the split
313 -- supply is safer, but slower.
315 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
317 = do { env <- getEnv ;
318 let { u_var = env_us env } ;
319 us <- readMutVar u_var ;
320 case splitUniqSupply us of { (us1,us2) -> do {
321 writeMutVar u_var us1 ;
324 newLocalName :: Name -> TcRnIf gbl lcl Name
325 newLocalName name -- Make a clone
326 = do { uniq <- newUnique
327 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
329 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
330 newSysLocalIds fs tys
331 = do { us <- newUniqueSupply
332 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
336 %************************************************************************
340 %************************************************************************
343 traceTc, traceRn :: SDoc -> TcRn ()
344 traceRn = traceOptTcRn Opt_D_dump_rn_trace
345 traceTc = traceOptTcRn Opt_D_dump_tc_trace
346 traceSplice = traceOptTcRn Opt_D_dump_splices
349 traceIf :: SDoc -> TcRnIf m n ()
350 traceIf = traceOptIf Opt_D_dump_if_trace
351 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
354 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
355 traceOptIf flag doc = ifOptM flag $
356 liftIO (printForUser stderr alwaysQualify doc)
358 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
359 traceOptTcRn flag doc = ifOptM flag $ do
362 ; env0 <- tcInitTidyEnv
363 ; ctxt_msgs <- do_ctxt env0 ctxt
364 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
365 ; dumpTcRn real_doc }
367 dumpTcRn :: SDoc -> TcRn ()
368 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
370 liftIO (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
372 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
373 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
377 %************************************************************************
379 Typechecker global environment
381 %************************************************************************
384 getModule :: TcRn Module
385 getModule = do { env <- getGblEnv; return (tcg_mod env) }
387 setModule :: Module -> TcRn a -> TcRn a
388 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
390 tcIsHsBoot :: TcRn Bool
391 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
393 getGlobalRdrEnv :: TcRn GlobalRdrEnv
394 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
396 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
397 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
399 getImports :: TcRn ImportAvails
400 getImports = do { env <- getGblEnv; return (tcg_imports env) }
402 getFixityEnv :: TcRn FixityEnv
403 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
405 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
406 extendFixityEnv new_bit
407 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
408 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
410 getRecFieldEnv :: TcRn RecFieldEnv
411 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
413 extendRecFieldEnv :: RecFieldEnv -> RnM a -> RnM a
414 extendRecFieldEnv new_bit
415 = updGblEnv (\env@(TcGblEnv { tcg_field_env = old_env }) ->
416 env {tcg_field_env = old_env `plusNameEnv` new_bit})
418 getDeclaredDefaultTys :: TcRn (Maybe [Type])
419 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
422 %************************************************************************
426 %************************************************************************
429 getSrcSpanM :: TcRn SrcSpan
430 -- Avoid clash with Name.getSrcLoc
431 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
433 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
434 setSrcSpan loc thing_inside
435 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
436 | otherwise = thing_inside -- Don't overwrite useful info with useless
438 addLocM :: (a -> TcM b) -> Located a -> TcM b
439 addLocM fn (L loc a) = setSrcSpan loc $ fn a
441 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
442 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
444 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
445 wrapLocFstM fn (L loc a) =
450 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
451 wrapLocSndM fn (L loc a) =
459 getErrsVar :: TcRn (TcRef Messages)
460 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
462 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
463 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
465 addErr :: Message -> TcRn ()
466 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
468 addLocErr :: Located e -> (e -> Message) -> TcRn ()
469 addLocErr (L loc e) fn = addErrAt loc (fn e)
471 addErrAt :: SrcSpan -> Message -> TcRn ()
472 addErrAt loc msg = addLongErrAt loc msg empty
474 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
475 addLongErrAt loc msg extra
476 = do { traceTc (ptext (sLit "Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
477 errs_var <- getErrsVar ;
478 rdr_env <- getGlobalRdrEnv ;
480 let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
481 (warns, errs) <- readMutVar errs_var ;
482 writeMutVar errs_var (warns, errs `snocBag` err) }
484 addErrs :: [(SrcSpan,Message)] -> TcRn ()
485 addErrs msgs = mapM_ add msgs
487 add (loc,msg) = addErrAt loc msg
489 addReport :: Message -> TcRn ()
490 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
492 addReportAt :: SrcSpan -> Message -> TcRn ()
494 = do { errs_var <- getErrsVar ;
495 rdr_env <- getGlobalRdrEnv ;
497 let { warn = mkWarnMsg loc (mkPrintUnqualified dflags rdr_env) msg } ;
498 (warns, errs) <- readMutVar errs_var ;
499 writeMutVar errs_var (warns `snocBag` warn, errs) }
501 addWarn :: Message -> TcRn ()
502 addWarn msg = addReport (ptext (sLit "Warning:") <+> msg)
504 addWarnAt :: SrcSpan -> Message -> TcRn ()
505 addWarnAt loc msg = addReportAt loc (ptext (sLit "Warning:") <+> msg)
507 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
508 addLocWarn (L loc e) fn = addReportAt loc (fn e)
510 checkErr :: Bool -> Message -> TcRn ()
511 -- Add the error if the bool is False
512 checkErr ok msg = unless ok (addErr msg)
514 warnIf :: Bool -> Message -> TcRn ()
515 warnIf True msg = addWarn msg
516 warnIf False msg = return ()
518 addMessages :: Messages -> TcRn ()
519 addMessages (m_warns, m_errs)
520 = do { errs_var <- getErrsVar ;
521 (warns, errs) <- readMutVar errs_var ;
522 writeMutVar errs_var (warns `unionBags` m_warns,
523 errs `unionBags` m_errs) }
525 discardWarnings :: TcRn a -> TcRn a
526 -- Ignore warnings inside the thing inside;
527 -- used to ignore-unused-variable warnings inside derived code
528 -- With -dppr-debug, the effects is switched off, so you can still see
529 -- what warnings derived code would give
530 discardWarnings thing_inside
531 | opt_PprStyle_Debug = thing_inside
533 = do { errs_var <- newMutVar emptyMessages
534 ; result <- setErrsVar errs_var thing_inside
535 ; (_warns, errs) <- readMutVar errs_var
536 ; addMessages (emptyBag, errs)
542 try_m :: TcRn r -> TcRn (Either Exception r)
543 -- Does try_m, with a debug-trace on failure
545 = do { mb_r <- tryM thing ;
547 Left exn -> do { traceTc (exn_msg exn); return mb_r }
548 Right r -> return mb_r }
550 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
552 -----------------------
553 recoverM :: TcRn r -- Recovery action; do this if the main one fails
554 -> TcRn r -- Main action: do this first
556 -- Errors in 'thing' are retained
557 recoverM recover thing
558 = do { mb_res <- try_m thing ;
561 Right res -> return res }
564 -----------------------
565 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
566 -- Drop elements of the input that fail, so the result
567 -- list can be shorter than the argument list
568 mapAndRecoverM f [] = return []
569 mapAndRecoverM f (x:xs) = do { mb_r <- tryM (f x)
570 ; rs <- mapAndRecoverM f xs
571 ; return (case mb_r of
576 -----------------------
577 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
578 -- (tryTc m) executes m, and returns
579 -- Just r, if m succeeds (returning r)
580 -- Nothing, if m fails
581 -- It also returns all the errors and warnings accumulated by m
582 -- It always succeeds (never raises an exception)
584 = do { errs_var <- newMutVar emptyMessages ;
585 res <- try_m (setErrsVar errs_var m) ;
586 msgs <- readMutVar errs_var ;
587 return (msgs, case res of
589 Right val -> Just val)
590 -- The exception is always the IOEnv built-in
591 -- in exception; see IOEnv.failM
594 -----------------------
595 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
596 -- Run the thing, returning
597 -- Just r, if m succceeds with no error messages
598 -- Nothing, if m fails, or if it succeeds but has error messages
599 -- Either way, the messages are returned; even in the Just case
600 -- there might be warnings
602 = do { (msgs, res) <- tryTc thing
604 ; let errs_found = errorsFound dflags msgs
605 ; return (msgs, case res of
607 Just val | errs_found -> Nothing
608 | otherwise -> Just val)
611 -----------------------
612 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
613 -- Just like tryTcErrs, except that it ensures that the LIE
614 -- for the thing is propagated only if there are no errors
615 -- Hence it's restricted to the type-check monad
616 tryTcLIE thing_inside
617 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
619 Nothing -> return (msgs, Nothing)
620 Just val -> do { extendLIEs lie; return (msgs, Just val) }
623 -----------------------
624 tryTcLIE_ :: TcM r -> TcM r -> TcM r
625 -- (tryTcLIE_ r m) tries m;
626 -- if m succeeds with no error messages, it's the answer
627 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
628 tryTcLIE_ recover main
629 = do { (msgs, mb_res) <- tryTcLIE main
631 Just val -> do { addMessages msgs -- There might be warnings
633 Nothing -> recover -- Discard all msgs
636 -----------------------
637 checkNoErrs :: TcM r -> TcM r
638 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
639 -- If m fails then (checkNoErrsTc m) fails.
640 -- If m succeeds, it checks whether m generated any errors messages
641 -- (it might have recovered internally)
642 -- If so, it fails too.
643 -- Regardless, any errors generated by m are propagated to the enclosing context.
645 = do { (msgs, mb_res) <- tryTcLIE main
649 Just val -> return val
652 ifErrsM :: TcRn r -> TcRn r -> TcRn r
653 -- ifErrsM bale_out main
654 -- does 'bale_out' if there are errors in errors collection
655 -- otherwise does 'main'
656 ifErrsM bale_out normal
657 = do { errs_var <- getErrsVar ;
658 msgs <- readMutVar errs_var ;
660 if errorsFound dflags msgs then
665 failIfErrsM :: TcRn ()
666 -- Useful to avoid error cascades
667 failIfErrsM = ifErrsM failM (return ())
671 %************************************************************************
673 Context management and error message generation
676 %************************************************************************
679 getErrCtxt :: TcM ErrCtxt
680 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
682 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
683 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
685 addErrCtxt :: Message -> TcM a -> TcM a
686 addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
688 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
689 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
691 -- Helper function for the above
692 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
693 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
694 env { tcl_ctxt = upd ctxt })
696 -- Conditionally add an error context
697 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
698 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
699 maybeAddErrCtxt Nothing thing_inside = thing_inside
701 popErrCtxt :: TcM a -> TcM a
702 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
704 getInstLoc :: InstOrigin -> TcM InstLoc
706 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
707 return (InstLoc origin loc (tcl_ctxt env)) }
709 addInstCtxt :: InstLoc -> TcM a -> TcM a
710 -- Add the SrcSpan and context from the first Inst in the list
711 -- (they all have similar locations)
712 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
713 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
716 The addErrTc functions add an error message, but do not cause failure.
717 The 'M' variants pass a TidyEnv that has already been used to
718 tidy up the message; we then use it to tidy the context messages
721 addErrTc :: Message -> TcM ()
722 addErrTc err_msg = do { env0 <- tcInitTidyEnv
723 ; addErrTcM (env0, err_msg) }
725 addErrsTc :: [Message] -> TcM ()
726 addErrsTc err_msgs = mapM_ addErrTc err_msgs
728 addErrTcM :: (TidyEnv, Message) -> TcM ()
729 addErrTcM (tidy_env, err_msg)
730 = do { ctxt <- getErrCtxt ;
732 add_err_tcm tidy_env err_msg loc ctxt }
735 The failWith functions add an error message and cause failure
738 failWithTc :: Message -> TcM a -- Add an error message and fail
740 = addErrTc err_msg >> failM
742 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
743 failWithTcM local_and_msg
744 = addErrTcM local_and_msg >> failM
746 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
747 checkTc True err = return ()
748 checkTc False err = failWithTc err
751 Warnings have no 'M' variant, nor failure
754 addWarnTc :: Message -> TcM ()
755 addWarnTc msg = do { env0 <- tcInitTidyEnv
756 ; addWarnTcM (env0, msg) }
758 addWarnTcM :: (TidyEnv, Message) -> TcM ()
759 addWarnTcM (env0, msg)
760 = do { ctxt <- getErrCtxt ;
761 ctxt_msgs <- do_ctxt env0 ctxt ;
762 addReport (vcat (ptext (sLit "Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
764 warnTc :: Bool -> Message -> TcM ()
765 warnTc warn_if_true warn_msg
766 | warn_if_true = addWarnTc warn_msg
767 | otherwise = return ()
770 -----------------------------------
773 We initialise the "tidy-env", used for tidying types before printing,
774 by building a reverse map from the in-scope type variables to the
775 OccName that the programmer originally used for them
778 tcInitTidyEnv :: TcM TidyEnv
780 = do { lcl_env <- getLclEnv
781 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
782 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
784 ; return (foldl add emptyTidyEnv nm_tv_prs) }
786 add (env,subst) (name, tyvar)
787 = case tidyOccName env (nameOccName name) of
788 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
790 tyvar' = setTyVarName tyvar name'
791 name' = tidyNameOcc name occ'
794 -----------------------------------
795 Other helper functions
798 add_err_tcm tidy_env err_msg loc ctxt
799 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
800 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
804 do_ctxt tidy_env (c:cs)
805 = do { (tidy_env', m) <- c tidy_env ;
806 ms <- do_ctxt tidy_env' cs ;
809 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
810 | otherwise = take 3 ctxt
813 debugTc is useful for monadic debugging code
816 debugTc :: TcM () -> TcM ()
819 | otherwise = return ()
822 %************************************************************************
824 Type constraints (the so-called LIE)
826 %************************************************************************
829 nextDFunIndex :: TcM Int -- Get the next dfun index
830 nextDFunIndex = do { env <- getGblEnv
831 ; let dfun_n_var = tcg_dfun_n env
832 ; n <- readMutVar dfun_n_var
833 ; writeMutVar dfun_n_var (n+1)
836 getLIEVar :: TcM (TcRef LIE)
837 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
839 setLIEVar :: TcRef LIE -> TcM a -> TcM a
840 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
842 getLIE :: TcM a -> TcM (a, [Inst])
843 -- (getLIE m) runs m, and returns the type constraints it generates
845 = do { lie_var <- newMutVar emptyLIE ;
846 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
848 lie <- readMutVar lie_var ;
849 return (res, lieToList lie) }
851 extendLIE :: Inst -> TcM ()
853 = do { lie_var <- getLIEVar ;
854 lie <- readMutVar lie_var ;
855 writeMutVar lie_var (inst `consLIE` lie) }
857 extendLIEs :: [Inst] -> TcM ()
861 = do { lie_var <- getLIEVar ;
862 lie <- readMutVar lie_var ;
863 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
867 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
868 -- Set the local type envt, but do *not* disturb other fields,
869 -- notably the lie_var
870 setLclTypeEnv lcl_env thing_inside
871 = updLclEnv upd thing_inside
873 upd env = env { tcl_env = tcl_env lcl_env,
874 tcl_tyvars = tcl_tyvars lcl_env }
878 %************************************************************************
880 Template Haskell context
882 %************************************************************************
885 recordThUse :: TcM ()
886 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
888 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
890 | isLocalId id = do { env <- getGblEnv;
891 ; updMutVar (tcg_keep env) (`addOneToNameSet` idName id) }
892 | otherwise = return ()
894 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
895 keepAliveSetTc ns = do { env <- getGblEnv;
896 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
898 getStage :: TcM ThStage
899 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
901 setStage :: ThStage -> TcM a -> TcM a
902 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
906 %************************************************************************
908 Stuff for the renamer's local env
910 %************************************************************************
913 getLocalRdrEnv :: RnM LocalRdrEnv
914 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
916 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
917 setLocalRdrEnv rdr_env thing_inside
918 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
922 %************************************************************************
924 Stuff for interface decls
926 %************************************************************************
929 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
930 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
932 if_tv_env = emptyUFM,
933 if_id_env = emptyUFM }
935 initIfaceTcRn :: IfG a -> TcRn a
936 initIfaceTcRn thing_inside
937 = do { tcg_env <- getGblEnv
938 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
939 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
940 ; setEnvs (if_env, ()) thing_inside }
942 initIfaceExtCore :: IfL a -> TcRn a
943 initIfaceExtCore thing_inside
944 = do { tcg_env <- getGblEnv
945 ; let { mod = tcg_mod tcg_env
946 ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
947 ; if_env = IfGblEnv {
948 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
949 ; if_lenv = mkIfLclEnv mod doc
951 ; setEnvs (if_env, if_lenv) thing_inside }
953 initIfaceCheck :: HscEnv -> IfG a -> IO a
954 -- Used when checking the up-to-date-ness of the old Iface
955 -- Initialise the environment with no useful info at all
956 initIfaceCheck hsc_env do_this
957 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
958 ; initTcRnIf 'i' hsc_env gbl_env () do_this
961 initIfaceTc :: ModIface
962 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
963 -- Used when type-checking checking an up-to-date interface file
964 -- No type envt from the current module, but we do know the module dependencies
965 initIfaceTc iface do_this
966 = do { tc_env_var <- newMutVar emptyTypeEnv
967 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
968 ; if_lenv = mkIfLclEnv mod doc
970 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
973 mod = mi_module iface
974 doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
976 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
977 -- Used when sucking in new Rules in SimplCore
978 -- We have available the type envt of the module being compiled, and we must use it
979 initIfaceRules hsc_env guts do_this
981 type_info = (mg_module guts, return (mg_types guts))
982 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
985 -- Run the thing; any exceptions just bubble out from here
986 ; initTcRnIf 'i' hsc_env gbl_env () do_this
989 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
990 initIfaceLcl mod loc_doc thing_inside
991 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
993 getIfModule :: IfL Module
994 getIfModule = do { env <- getLclEnv; return (if_mod env) }
997 failIfM :: Message -> IfL a
998 -- The Iface monad doesn't have a place to accumulate errors, so we
999 -- just fall over fast if one happens; it "shouldnt happen".
1000 -- We use IfL here so that we can get context info out of the local env
1002 = do { env <- getLclEnv
1003 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1004 ; liftIO (printErrs (full_msg defaultErrStyle))
1007 --------------------
1008 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1009 -- Run thing_inside in an interleaved thread.
1010 -- It shares everything with the parent thread, so this is DANGEROUS.
1012 -- It returns Nothing if the computation fails
1014 -- It's used for lazily type-checking interface
1015 -- signatures, which is pretty benign
1017 forkM_maybe doc thing_inside
1018 = do { unsafeInterleaveM $
1019 do { traceIf (text "Starting fork {" <+> doc)
1021 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1024 Right r -> do { traceIf (text "} ending fork" <+> doc)
1028 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1029 -- Otherwise we silently discard errors. Errors can legitimately
1030 -- happen when compiling interface signatures (see tcInterfaceSigs)
1031 ifOptM Opt_D_dump_if_trace
1032 (print_errs (hang (text "forkM failed:" <+> doc)
1033 4 (text (show exn))))
1035 ; traceIf (text "} ending fork (badly)" <+> doc)
1039 print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1041 forkM :: SDoc -> IfL a -> IfL a
1042 forkM doc thing_inside
1043 = do { mb_res <- forkM_maybe doc thing_inside
1044 ; return (case mb_res of
1045 Nothing -> pgmError "Cannot continue after interface file error"
1046 -- pprPanic "forkM" doc