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 #include "HsVersions.h"
21 import TcRnTypes -- Re-export all
22 import IOEnv -- Re-export all
24 import HsSyn hiding (LIE)
55 import Control.Exception
60 %************************************************************************
64 %************************************************************************
67 ioToTcRn :: IO r -> TcRn r
75 -> Bool -- True <=> retain renamed syntax trees
78 -> IO (Messages, Maybe r)
79 -- Nothing => error thrown by the thing inside
80 -- (error messages should have been printed already)
82 initTc hsc_env hsc_src keep_rn_syntax mod do_this
83 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
84 tvs_var <- newIORef emptyVarSet ;
85 type_env_var <- newIORef emptyNameEnv ;
86 dfuns_var <- newIORef emptyNameSet ;
87 keep_var <- newIORef emptyNameSet ;
88 th_var <- newIORef False ;
89 dfun_n_var <- newIORef 1 ;
91 maybe_rn_syntax empty_val
92 | keep_rn_syntax = Just empty_val
93 | otherwise = Nothing ;
98 tcg_rdr_env = hsc_global_rdr_env hsc_env,
99 tcg_fix_env = emptyNameEnv,
100 tcg_field_env = emptyNameEnv,
101 tcg_default = Nothing,
102 tcg_type_env = hsc_global_type_env hsc_env,
103 tcg_type_env_var = type_env_var,
104 tcg_inst_env = emptyInstEnv,
105 tcg_fam_inst_env = emptyFamInstEnv,
106 tcg_inst_uses = dfuns_var,
107 tcg_th_used = th_var,
109 tcg_imports = emptyImportAvails,
112 tcg_rn_imports = maybe_rn_syntax [],
113 tcg_rn_exports = maybe_rn_syntax [],
114 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
116 tcg_binds = emptyLHsBinds,
117 tcg_deprecs = NoDeprecs,
122 tcg_dfun_n = dfun_n_var,
125 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing,
130 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
132 tcl_rdr = emptyLocalRdrEnv,
133 tcl_th_ctxt = topStage,
134 tcl_arrow_ctxt = NoArrowCtxt,
135 tcl_env = emptyNameEnv,
136 tcl_tyvars = tvs_var,
137 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
141 -- OK, here's the business end!
142 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
143 do { r <- tryM do_this
145 Right res -> return (Just res)
146 Left _ -> return Nothing } ;
148 -- Collect any error messages
149 msgs <- readIORef errs_var ;
151 let { dflags = hsc_dflags hsc_env
152 ; final_res | errorsFound dflags msgs = Nothing
153 | otherwise = maybe_res } ;
155 return (msgs, final_res)
158 initTcPrintErrors -- Used from the interactive loop only
163 initTcPrintErrors env mod todo = do
164 (msgs, res) <- initTc env HsSrcFile False mod todo
165 printErrorsAndWarnings (hsc_dflags env) msgs
169 %************************************************************************
173 %************************************************************************
177 initTcRnIf :: Char -- Tag for unique supply
182 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
183 = do { us <- mkSplitUniqSupply uniq_tag ;
184 ; us_var <- newIORef us ;
186 ; let { env = Env { env_top = hsc_env,
191 ; runIOEnv env thing_inside
195 %************************************************************************
199 %************************************************************************
202 getTopEnv :: TcRnIf gbl lcl HscEnv
203 getTopEnv = do { env <- getEnv; return (env_top env) }
205 getGblEnv :: TcRnIf gbl lcl gbl
206 getGblEnv = do { env <- getEnv; return (env_gbl env) }
208 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
209 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
210 env { env_gbl = upd gbl })
212 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
213 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
215 getLclEnv :: TcRnIf gbl lcl lcl
216 getLclEnv = do { env <- getEnv; return (env_lcl env) }
218 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
219 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
220 env { env_lcl = upd lcl })
222 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
223 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
225 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
226 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
228 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
229 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
236 getDOpts :: TcRnIf gbl lcl DynFlags
237 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
239 doptM :: DynFlag -> TcRnIf gbl lcl Bool
240 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
242 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
243 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
244 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
246 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
247 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
248 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
250 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
251 ifOptM flag thing_inside = do { b <- doptM flag;
252 if b then thing_inside else return () }
254 getGhcMode :: TcRnIf gbl lcl GhcMode
255 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
259 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
260 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
262 getEps :: TcRnIf gbl lcl ExternalPackageState
263 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
265 -- Updating the EPS. This should be an atomic operation.
266 -- Note the delicate 'seq' which forces the EPS before putting it in the
267 -- variable. Otherwise what happens is that we get
268 -- write eps_var (....(unsafeRead eps_var)....)
269 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
270 -- we make the unsafeRead happen before we update the variable.
272 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
274 updateEps upd_fn = do { traceIf (text "updating EPS")
275 ; eps_var <- getEpsVar
276 ; eps <- readMutVar eps_var
277 ; let { (eps', val) = upd_fn eps }
278 ; seq eps' (writeMutVar eps_var eps')
281 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
283 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
284 ; eps_var <- getEpsVar
285 ; eps <- readMutVar eps_var
286 ; let { eps' = upd_fn eps }
287 ; seq eps' (writeMutVar eps_var eps') }
289 getHpt :: TcRnIf gbl lcl HomePackageTable
290 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
292 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
293 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
294 ; return (eps, hsc_HPT env) }
297 %************************************************************************
301 %************************************************************************
304 newUnique :: TcRnIf gbl lcl Unique
306 = do { env <- getEnv ;
307 let { u_var = env_us env } ;
308 us <- readMutVar u_var ;
309 case splitUniqSupply us of { (us1,_) -> do {
310 writeMutVar u_var us1 ;
311 return $! uniqFromSupply us }}}
312 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
313 -- a chain of unevaluated supplies behind.
314 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
315 -- throw away one half of the new split supply. This is safe because this
316 -- is the only place we use that unique. Using the other half of the split
317 -- supply is safer, but slower.
319 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
321 = do { env <- getEnv ;
322 let { u_var = env_us env } ;
323 us <- readMutVar u_var ;
324 case splitUniqSupply us of { (us1,us2) -> do {
325 writeMutVar u_var us1 ;
328 newLocalName :: Name -> TcRnIf gbl lcl Name
329 newLocalName name -- Make a clone
330 = do { uniq <- newUnique
331 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
333 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
334 newSysLocalIds fs tys
335 = do { us <- newUniqueSupply
336 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
340 %************************************************************************
344 %************************************************************************
347 traceTc, traceRn :: SDoc -> TcRn ()
348 traceRn = traceOptTcRn Opt_D_dump_rn_trace
349 traceTc = traceOptTcRn Opt_D_dump_tc_trace
350 traceSplice = traceOptTcRn Opt_D_dump_splices
353 traceIf :: SDoc -> TcRnIf m n ()
354 traceIf = traceOptIf Opt_D_dump_if_trace
355 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
358 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
359 traceOptIf flag doc = ifOptM flag $
360 ioToIOEnv (printForUser stderr alwaysQualify doc)
362 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
363 traceOptTcRn flag doc = ifOptM flag $ do
366 ; env0 <- tcInitTidyEnv
367 ; ctxt_msgs <- do_ctxt env0 ctxt
368 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
369 ; dumpTcRn real_doc }
371 dumpTcRn :: SDoc -> TcRn ()
372 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
374 ioToTcRn (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
376 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
377 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
381 %************************************************************************
383 Typechecker global environment
385 %************************************************************************
388 getModule :: TcRn Module
389 getModule = do { env <- getGblEnv; return (tcg_mod env) }
391 setModule :: Module -> TcRn a -> TcRn a
392 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
394 tcIsHsBoot :: TcRn Bool
395 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
397 getGlobalRdrEnv :: TcRn GlobalRdrEnv
398 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
400 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
401 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
403 getImports :: TcRn ImportAvails
404 getImports = do { env <- getGblEnv; return (tcg_imports env) }
406 getFixityEnv :: TcRn FixityEnv
407 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
409 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
410 extendFixityEnv new_bit
411 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
412 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
414 getRecFieldEnv :: TcRn RecFieldEnv
415 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
417 extendRecFieldEnv :: RecFieldEnv -> RnM a -> RnM a
418 extendRecFieldEnv new_bit
419 = updGblEnv (\env@(TcGblEnv { tcg_field_env = old_env }) ->
420 env {tcg_field_env = old_env `plusNameEnv` new_bit})
422 getDeclaredDefaultTys :: TcRn (Maybe [Type])
423 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
426 %************************************************************************
430 %************************************************************************
433 getSrcSpanM :: TcRn SrcSpan
434 -- Avoid clash with Name.getSrcLoc
435 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
437 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
438 setSrcSpan loc thing_inside
439 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
440 | otherwise = thing_inside -- Don't overwrite useful info with useless
442 addLocM :: (a -> TcM b) -> Located a -> TcM b
443 addLocM fn (L loc a) = setSrcSpan loc $ fn a
445 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
446 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
448 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
449 wrapLocFstM fn (L loc a) =
454 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
455 wrapLocSndM fn (L loc a) =
463 getErrsVar :: TcRn (TcRef Messages)
464 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
466 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
467 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
469 addErr :: Message -> TcRn ()
470 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
472 addLocErr :: Located e -> (e -> Message) -> TcRn ()
473 addLocErr (L loc e) fn = addErrAt loc (fn e)
475 addErrAt :: SrcSpan -> Message -> TcRn ()
476 addErrAt loc msg = addLongErrAt loc msg empty
478 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
479 addLongErrAt loc msg extra
480 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
481 errs_var <- getErrsVar ;
482 rdr_env <- getGlobalRdrEnv ;
484 let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
485 (warns, errs) <- readMutVar errs_var ;
486 writeMutVar errs_var (warns, errs `snocBag` err) }
488 addErrs :: [(SrcSpan,Message)] -> TcRn ()
489 addErrs msgs = mappM_ add msgs
491 add (loc,msg) = addErrAt loc msg
493 addReport :: Message -> TcRn ()
494 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
496 addReportAt :: SrcSpan -> Message -> TcRn ()
498 = do { errs_var <- getErrsVar ;
499 rdr_env <- getGlobalRdrEnv ;
501 let { warn = mkWarnMsg loc (mkPrintUnqualified dflags rdr_env) msg } ;
502 (warns, errs) <- readMutVar errs_var ;
503 writeMutVar errs_var (warns `snocBag` warn, errs) }
505 addWarn :: Message -> TcRn ()
506 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
508 addWarnAt :: SrcSpan -> Message -> TcRn ()
509 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
511 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
512 addLocWarn (L loc e) fn = addReportAt loc (fn e)
514 checkErr :: Bool -> Message -> TcRn ()
515 -- Add the error if the bool is False
516 checkErr ok msg = checkM ok (addErr msg)
518 warnIf :: Bool -> Message -> TcRn ()
519 warnIf True msg = addWarn msg
520 warnIf False msg = return ()
522 addMessages :: Messages -> TcRn ()
523 addMessages (m_warns, m_errs)
524 = do { errs_var <- getErrsVar ;
525 (warns, errs) <- readMutVar errs_var ;
526 writeMutVar errs_var (warns `unionBags` m_warns,
527 errs `unionBags` m_errs) }
529 discardWarnings :: TcRn a -> TcRn a
530 -- Ignore warnings inside the thing inside;
531 -- used to ignore-unused-variable warnings inside derived code
532 -- With -dppr-debug, the effects is switched off, so you can still see
533 -- what warnings derived code would give
534 discardWarnings thing_inside
535 | opt_PprStyle_Debug = thing_inside
537 = do { errs_var <- newMutVar emptyMessages
538 ; result <- setErrsVar errs_var thing_inside
539 ; (_warns, errs) <- readMutVar errs_var
540 ; addMessages (emptyBag, errs)
546 try_m :: TcRn r -> TcRn (Either Exception r)
547 -- Does try_m, with a debug-trace on failure
549 = do { mb_r <- tryM thing ;
551 Left exn -> do { traceTc (exn_msg exn); return mb_r }
552 Right r -> return mb_r }
554 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
556 -----------------------
557 recoverM :: TcRn r -- Recovery action; do this if the main one fails
558 -> TcRn r -- Main action: do this first
560 -- Errors in 'thing' are retained
561 recoverM recover thing
562 = do { mb_res <- try_m thing ;
565 Right res -> returnM res }
568 -----------------------
569 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
570 -- Drop elements of the input that fail, so the result
571 -- list can be shorter than the argument list
572 mapAndRecoverM f [] = return []
573 mapAndRecoverM f (x:xs) = do { mb_r <- tryM (f x)
574 ; rs <- mapAndRecoverM f xs
575 ; return (case mb_r of
580 -----------------------
581 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
582 -- (tryTc m) executes m, and returns
583 -- Just r, if m succeeds (returning r)
584 -- Nothing, if m fails
585 -- It also returns all the errors and warnings accumulated by m
586 -- It always succeeds (never raises an exception)
588 = do { errs_var <- newMutVar emptyMessages ;
589 res <- try_m (setErrsVar errs_var m) ;
590 msgs <- readMutVar errs_var ;
591 return (msgs, case res of
593 Right val -> Just val)
594 -- The exception is always the IOEnv built-in
595 -- in exception; see IOEnv.failM
598 -----------------------
599 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
600 -- Run the thing, returning
601 -- Just r, if m succceeds with no error messages
602 -- Nothing, if m fails, or if it succeeds but has error messages
603 -- Either way, the messages are returned; even in the Just case
604 -- there might be warnings
606 = do { (msgs, res) <- tryTc thing
608 ; let errs_found = errorsFound dflags msgs
609 ; return (msgs, case res of
611 Just val | errs_found -> Nothing
612 | otherwise -> Just val)
615 -----------------------
616 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
617 -- Just like tryTcErrs, except that it ensures that the LIE
618 -- for the thing is propagated only if there are no errors
619 -- Hence it's restricted to the type-check monad
620 tryTcLIE thing_inside
621 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
623 Nothing -> return (msgs, Nothing)
624 Just val -> do { extendLIEs lie; return (msgs, Just val) }
627 -----------------------
628 tryTcLIE_ :: TcM r -> TcM r -> TcM r
629 -- (tryTcLIE_ r m) tries m;
630 -- if m succeeds with no error messages, it's the answer
631 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
632 tryTcLIE_ recover main
633 = do { (msgs, mb_res) <- tryTcLIE main
635 Just val -> do { addMessages msgs -- There might be warnings
637 Nothing -> recover -- Discard all msgs
640 -----------------------
641 checkNoErrs :: TcM r -> TcM r
642 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
643 -- If m fails then (checkNoErrsTc m) fails.
644 -- If m succeeds, it checks whether m generated any errors messages
645 -- (it might have recovered internally)
646 -- If so, it fails too.
647 -- Regardless, any errors generated by m are propagated to the enclosing context.
649 = do { (msgs, mb_res) <- tryTcLIE main
653 Just val -> return val
656 ifErrsM :: TcRn r -> TcRn r -> TcRn r
657 -- ifErrsM bale_out main
658 -- does 'bale_out' if there are errors in errors collection
659 -- otherwise does 'main'
660 ifErrsM bale_out normal
661 = do { errs_var <- getErrsVar ;
662 msgs <- readMutVar errs_var ;
664 if errorsFound dflags msgs then
669 failIfErrsM :: TcRn ()
670 -- Useful to avoid error cascades
671 failIfErrsM = ifErrsM failM (return ())
675 %************************************************************************
677 Context management and error message generation
680 %************************************************************************
683 getErrCtxt :: TcM ErrCtxt
684 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
686 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
687 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
689 addErrCtxt :: Message -> TcM a -> TcM a
690 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
692 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
693 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
695 -- Helper function for the above
696 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
697 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
698 env { tcl_ctxt = upd ctxt })
700 -- Conditionally add an error context
701 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
702 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
703 maybeAddErrCtxt Nothing thing_inside = thing_inside
705 popErrCtxt :: TcM a -> TcM a
706 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
708 getInstLoc :: InstOrigin -> TcM InstLoc
710 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
711 return (InstLoc origin loc (tcl_ctxt env)) }
713 addInstCtxt :: InstLoc -> TcM a -> TcM a
714 -- Add the SrcSpan and context from the first Inst in the list
715 -- (they all have similar locations)
716 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
717 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
720 The addErrTc functions add an error message, but do not cause failure.
721 The 'M' variants pass a TidyEnv that has already been used to
722 tidy up the message; we then use it to tidy the context messages
725 addErrTc :: Message -> TcM ()
726 addErrTc err_msg = do { env0 <- tcInitTidyEnv
727 ; addErrTcM (env0, err_msg) }
729 addErrsTc :: [Message] -> TcM ()
730 addErrsTc err_msgs = mappM_ addErrTc err_msgs
732 addErrTcM :: (TidyEnv, Message) -> TcM ()
733 addErrTcM (tidy_env, err_msg)
734 = do { ctxt <- getErrCtxt ;
736 add_err_tcm tidy_env err_msg loc ctxt }
739 The failWith functions add an error message and cause failure
742 failWithTc :: Message -> TcM a -- Add an error message and fail
744 = addErrTc err_msg >> failM
746 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
747 failWithTcM local_and_msg
748 = addErrTcM local_and_msg >> failM
750 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
751 checkTc True err = returnM ()
752 checkTc False err = failWithTc err
755 Warnings have no 'M' variant, nor failure
758 addWarnTc :: Message -> TcM ()
759 addWarnTc msg = do { env0 <- tcInitTidyEnv
760 ; addWarnTcM (env0, msg) }
762 addWarnTcM :: (TidyEnv, Message) -> TcM ()
763 addWarnTcM (env0, msg)
764 = do { ctxt <- getErrCtxt ;
765 ctxt_msgs <- do_ctxt env0 ctxt ;
766 addReport (vcat (ptext SLIT("Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
768 warnTc :: Bool -> Message -> TcM ()
769 warnTc warn_if_true warn_msg
770 | warn_if_true = addWarnTc warn_msg
771 | otherwise = return ()
774 -----------------------------------
777 We initialise the "tidy-env", used for tidying types before printing,
778 by building a reverse map from the in-scope type variables to the
779 OccName that the programmer originally used for them
782 tcInitTidyEnv :: TcM TidyEnv
784 = do { lcl_env <- getLclEnv
785 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
786 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
788 ; return (foldl add emptyTidyEnv nm_tv_prs) }
790 add (env,subst) (name, tyvar)
791 = case tidyOccName env (nameOccName name) of
792 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
794 tyvar' = setTyVarName tyvar name'
795 name' = tidyNameOcc name occ'
798 -----------------------------------
799 Other helper functions
802 add_err_tcm tidy_env err_msg loc ctxt
803 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
804 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
808 do_ctxt tidy_env (c:cs)
809 = do { (tidy_env', m) <- c tidy_env ;
810 ms <- do_ctxt tidy_env' cs ;
813 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
814 | otherwise = take 3 ctxt
817 debugTc is useful for monadic debugging code
820 debugTc :: TcM () -> TcM ()
822 debugTc thing = thing
824 debugTc thing = return ()
828 %************************************************************************
830 Type constraints (the so-called LIE)
832 %************************************************************************
835 nextDFunIndex :: TcM Int -- Get the next dfun index
836 nextDFunIndex = do { env <- getGblEnv
837 ; let dfun_n_var = tcg_dfun_n env
838 ; n <- readMutVar dfun_n_var
839 ; writeMutVar dfun_n_var (n+1)
842 getLIEVar :: TcM (TcRef LIE)
843 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
845 setLIEVar :: TcRef LIE -> TcM a -> TcM a
846 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
848 getLIE :: TcM a -> TcM (a, [Inst])
849 -- (getLIE m) runs m, and returns the type constraints it generates
851 = do { lie_var <- newMutVar emptyLIE ;
852 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
854 lie <- readMutVar lie_var ;
855 return (res, lieToList lie) }
857 extendLIE :: Inst -> TcM ()
859 = do { lie_var <- getLIEVar ;
860 lie <- readMutVar lie_var ;
861 writeMutVar lie_var (inst `consLIE` lie) }
863 extendLIEs :: [Inst] -> TcM ()
867 = do { lie_var <- getLIEVar ;
868 lie <- readMutVar lie_var ;
869 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
873 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
874 -- Set the local type envt, but do *not* disturb other fields,
875 -- notably the lie_var
876 setLclTypeEnv lcl_env thing_inside
877 = updLclEnv upd thing_inside
879 upd env = env { tcl_env = tcl_env lcl_env,
880 tcl_tyvars = tcl_tyvars lcl_env }
884 %************************************************************************
886 Template Haskell context
888 %************************************************************************
891 recordThUse :: TcM ()
892 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
894 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
896 | isLocalId id = do { env <- getGblEnv;
897 ; updMutVar (tcg_keep env) (`addOneToNameSet` idName id) }
898 | otherwise = return ()
900 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
901 keepAliveSetTc ns = do { env <- getGblEnv;
902 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
904 getStage :: TcM ThStage
905 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
907 setStage :: ThStage -> TcM a -> TcM a
908 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
912 %************************************************************************
914 Stuff for the renamer's local env
916 %************************************************************************
919 getLocalRdrEnv :: RnM LocalRdrEnv
920 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
922 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
923 setLocalRdrEnv rdr_env thing_inside
924 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
928 %************************************************************************
930 Stuff for interface decls
932 %************************************************************************
935 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
936 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
938 if_tv_env = emptyUFM,
939 if_id_env = emptyUFM }
941 initIfaceTcRn :: IfG a -> TcRn a
942 initIfaceTcRn thing_inside
943 = do { tcg_env <- getGblEnv
944 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
945 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
946 ; setEnvs (if_env, ()) thing_inside }
948 initIfaceExtCore :: IfL a -> TcRn a
949 initIfaceExtCore thing_inside
950 = do { tcg_env <- getGblEnv
951 ; let { mod = tcg_mod tcg_env
952 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
953 ; if_env = IfGblEnv {
954 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
955 ; if_lenv = mkIfLclEnv mod doc
957 ; setEnvs (if_env, if_lenv) thing_inside }
959 initIfaceCheck :: HscEnv -> IfG a -> IO a
960 -- Used when checking the up-to-date-ness of the old Iface
961 -- Initialise the environment with no useful info at all
962 initIfaceCheck hsc_env do_this
963 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
964 ; initTcRnIf 'i' hsc_env gbl_env () do_this
967 initIfaceTc :: ModIface
968 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
969 -- Used when type-checking checking an up-to-date interface file
970 -- No type envt from the current module, but we do know the module dependencies
971 initIfaceTc iface do_this
972 = do { tc_env_var <- newMutVar emptyTypeEnv
973 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
974 ; if_lenv = mkIfLclEnv mod doc
976 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
979 mod = mi_module iface
980 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
982 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
983 -- Used when sucking in new Rules in SimplCore
984 -- We have available the type envt of the module being compiled, and we must use it
985 initIfaceRules hsc_env guts do_this
987 type_info = (mg_module guts, return (mg_types guts))
988 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
991 -- Run the thing; any exceptions just bubble out from here
992 ; initTcRnIf 'i' hsc_env gbl_env () do_this
995 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
996 initIfaceLcl mod loc_doc thing_inside
997 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
999 getIfModule :: IfL Module
1000 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1002 --------------------
1003 failIfM :: Message -> IfL a
1004 -- The Iface monad doesn't have a place to accumulate errors, so we
1005 -- just fall over fast if one happens; it "shouldnt happen".
1006 -- We use IfL here so that we can get context info out of the local env
1008 = do { env <- getLclEnv
1009 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1010 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
1013 --------------------
1014 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1015 -- Run thing_inside in an interleaved thread.
1016 -- It shares everything with the parent thread, so this is DANGEROUS.
1018 -- It returns Nothing if the computation fails
1020 -- It's used for lazily type-checking interface
1021 -- signatures, which is pretty benign
1023 forkM_maybe doc thing_inside
1024 = do { unsafeInterleaveM $
1025 do { traceIf (text "Starting fork {" <+> doc)
1027 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1030 Right r -> do { traceIf (text "} ending fork" <+> doc)
1034 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1035 -- Otherwise we silently discard errors. Errors can legitimately
1036 -- happen when compiling interface signatures (see tcInterfaceSigs)
1037 ifOptM Opt_D_dump_if_trace
1038 (print_errs (hang (text "forkM failed:" <+> doc)
1039 4 (text (show exn))))
1041 ; traceIf (text "} ending fork (badly)" <+> doc)
1045 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1047 forkM :: SDoc -> IfL a -> IfL a
1048 forkM doc thing_inside
1049 = do { mb_res <- forkM_maybe doc thing_inside
1050 ; return (case mb_res of
1051 Nothing -> pgmError "Cannot continue after interface file error"
1052 -- pprPanic "forkM" doc