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 Control.Exception
52 %************************************************************************
56 %************************************************************************
59 ioToTcRn :: IO r -> TcRn r
67 -> Bool -- True <=> retain renamed syntax trees
70 -> IO (Messages, Maybe r)
71 -- Nothing => error thrown by the thing inside
72 -- (error messages should have been printed already)
74 initTc hsc_env hsc_src keep_rn_syntax mod do_this
75 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
76 tvs_var <- newIORef emptyVarSet ;
77 type_env_var <- newIORef emptyNameEnv ;
78 dfuns_var <- newIORef emptyNameSet ;
79 keep_var <- newIORef emptyNameSet ;
80 th_var <- newIORef False ;
81 dfun_n_var <- newIORef 1 ;
83 maybe_rn_syntax empty_val
84 | keep_rn_syntax = Just empty_val
85 | otherwise = Nothing ;
90 tcg_rdr_env = hsc_global_rdr_env hsc_env,
91 tcg_fix_env = emptyNameEnv,
92 tcg_field_env = emptyNameEnv,
93 tcg_default = Nothing,
94 tcg_type_env = hsc_global_type_env hsc_env,
95 tcg_type_env_var = type_env_var,
96 tcg_inst_env = emptyInstEnv,
97 tcg_fam_inst_env = emptyFamInstEnv,
98 tcg_inst_uses = dfuns_var,
101 tcg_imports = emptyImportAvails,
104 tcg_rn_imports = maybe_rn_syntax [],
105 tcg_rn_exports = maybe_rn_syntax [],
106 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
108 tcg_binds = emptyLHsBinds,
109 tcg_deprecs = NoDeprecs,
114 tcg_dfun_n = dfun_n_var,
117 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing,
122 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
124 tcl_rdr = emptyLocalRdrEnv,
125 tcl_th_ctxt = topStage,
126 tcl_arrow_ctxt = NoArrowCtxt,
127 tcl_env = emptyNameEnv,
128 tcl_tyvars = tvs_var,
129 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
133 -- OK, here's the business end!
134 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
135 do { r <- tryM do_this
137 Right res -> return (Just res)
138 Left _ -> return Nothing } ;
140 -- Collect any error messages
141 msgs <- readIORef errs_var ;
143 let { dflags = hsc_dflags hsc_env
144 ; final_res | errorsFound dflags msgs = Nothing
145 | otherwise = maybe_res } ;
147 return (msgs, final_res)
150 initTcPrintErrors -- Used from the interactive loop only
155 initTcPrintErrors env mod todo = do
156 (msgs, res) <- initTc env HsSrcFile False mod todo
157 printErrorsAndWarnings (hsc_dflags env) msgs
161 %************************************************************************
165 %************************************************************************
169 initTcRnIf :: Char -- Tag for unique supply
174 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
175 = do { us <- mkSplitUniqSupply uniq_tag ;
176 ; us_var <- newIORef us ;
178 ; let { env = Env { env_top = hsc_env,
183 ; runIOEnv env thing_inside
187 %************************************************************************
191 %************************************************************************
194 getTopEnv :: TcRnIf gbl lcl HscEnv
195 getTopEnv = do { env <- getEnv; return (env_top env) }
197 getGblEnv :: TcRnIf gbl lcl gbl
198 getGblEnv = do { env <- getEnv; return (env_gbl env) }
200 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
201 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
202 env { env_gbl = upd gbl })
204 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
205 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
207 getLclEnv :: TcRnIf gbl lcl lcl
208 getLclEnv = do { env <- getEnv; return (env_lcl env) }
210 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
211 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
212 env { env_lcl = upd lcl })
214 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
215 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
217 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
218 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
220 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
221 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
228 getDOpts :: TcRnIf gbl lcl DynFlags
229 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
231 doptM :: DynFlag -> TcRnIf gbl lcl Bool
232 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
234 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
235 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
236 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
238 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
239 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
240 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
242 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
243 ifOptM flag thing_inside = do { b <- doptM flag;
244 if b then thing_inside else return () }
246 getGhcMode :: TcRnIf gbl lcl GhcMode
247 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
251 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
252 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
254 getEps :: TcRnIf gbl lcl ExternalPackageState
255 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
257 -- Updating the EPS. This should be an atomic operation.
258 -- Note the delicate 'seq' which forces the EPS before putting it in the
259 -- variable. Otherwise what happens is that we get
260 -- write eps_var (....(unsafeRead eps_var)....)
261 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
262 -- we make the unsafeRead happen before we update the variable.
264 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
266 updateEps upd_fn = do { traceIf (text "updating EPS")
267 ; eps_var <- getEpsVar
268 ; eps <- readMutVar eps_var
269 ; let { (eps', val) = upd_fn eps }
270 ; seq eps' (writeMutVar eps_var eps')
273 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
275 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
276 ; eps_var <- getEpsVar
277 ; eps <- readMutVar eps_var
278 ; let { eps' = upd_fn eps }
279 ; seq eps' (writeMutVar eps_var eps') }
281 getHpt :: TcRnIf gbl lcl HomePackageTable
282 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
284 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
285 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
286 ; return (eps, hsc_HPT env) }
289 %************************************************************************
293 %************************************************************************
296 newUnique :: TcRnIf gbl lcl Unique
298 = do { env <- getEnv ;
299 let { u_var = env_us env } ;
300 us <- readMutVar u_var ;
301 case splitUniqSupply us of { (us1,_) -> do {
302 writeMutVar u_var us1 ;
303 return $! uniqFromSupply us }}}
304 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
305 -- a chain of unevaluated supplies behind.
306 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
307 -- throw away one half of the new split supply. This is safe because this
308 -- is the only place we use that unique. Using the other half of the split
309 -- supply is safer, but slower.
311 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
313 = do { env <- getEnv ;
314 let { u_var = env_us env } ;
315 us <- readMutVar u_var ;
316 case splitUniqSupply us of { (us1,us2) -> do {
317 writeMutVar u_var us1 ;
320 newLocalName :: Name -> TcRnIf gbl lcl Name
321 newLocalName name -- Make a clone
322 = do { uniq <- newUnique
323 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
325 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
326 newSysLocalIds fs tys
327 = do { us <- newUniqueSupply
328 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
332 %************************************************************************
336 %************************************************************************
339 traceTc, traceRn :: SDoc -> TcRn ()
340 traceRn = traceOptTcRn Opt_D_dump_rn_trace
341 traceTc = traceOptTcRn Opt_D_dump_tc_trace
342 traceSplice = traceOptTcRn Opt_D_dump_splices
345 traceIf :: SDoc -> TcRnIf m n ()
346 traceIf = traceOptIf Opt_D_dump_if_trace
347 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
350 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
351 traceOptIf flag doc = ifOptM flag $
352 ioToIOEnv (printForUser stderr alwaysQualify doc)
354 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
355 traceOptTcRn flag doc = ifOptM flag $ do
358 ; env0 <- tcInitTidyEnv
359 ; ctxt_msgs <- do_ctxt env0 ctxt
360 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
361 ; dumpTcRn real_doc }
363 dumpTcRn :: SDoc -> TcRn ()
364 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
365 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
367 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
368 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
372 %************************************************************************
374 Typechecker global environment
376 %************************************************************************
379 getModule :: TcRn Module
380 getModule = do { env <- getGblEnv; return (tcg_mod env) }
382 setModule :: Module -> TcRn a -> TcRn a
383 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
385 tcIsHsBoot :: TcRn Bool
386 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
388 getGlobalRdrEnv :: TcRn GlobalRdrEnv
389 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
391 getImports :: TcRn ImportAvails
392 getImports = do { env <- getGblEnv; return (tcg_imports env) }
394 getFixityEnv :: TcRn FixityEnv
395 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
397 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
398 extendFixityEnv new_bit
399 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
400 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
402 getRecFieldEnv :: TcRn RecFieldEnv
403 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
405 extendRecFieldEnv :: RecFieldEnv -> RnM a -> RnM a
406 extendRecFieldEnv new_bit
407 = updGblEnv (\env@(TcGblEnv { tcg_field_env = old_env }) ->
408 env {tcg_field_env = old_env `plusNameEnv` new_bit})
410 getDeclaredDefaultTys :: TcRn (Maybe [Type])
411 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
414 %************************************************************************
418 %************************************************************************
421 getSrcSpanM :: TcRn SrcSpan
422 -- Avoid clash with Name.getSrcLoc
423 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
425 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
426 setSrcSpan loc thing_inside
427 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
428 | otherwise = thing_inside -- Don't overwrite useful info with useless
430 addLocM :: (a -> TcM b) -> Located a -> TcM b
431 addLocM fn (L loc a) = setSrcSpan loc $ fn a
433 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
434 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
436 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
437 wrapLocFstM fn (L loc a) =
442 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
443 wrapLocSndM fn (L loc a) =
451 getErrsVar :: TcRn (TcRef Messages)
452 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
454 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
455 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
457 addErr :: Message -> TcRn ()
458 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
460 addLocErr :: Located e -> (e -> Message) -> TcRn ()
461 addLocErr (L loc e) fn = addErrAt loc (fn e)
463 addErrAt :: SrcSpan -> Message -> TcRn ()
464 addErrAt loc msg = addLongErrAt loc msg empty
466 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
467 addLongErrAt loc msg extra
468 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
469 errs_var <- getErrsVar ;
470 rdr_env <- getGlobalRdrEnv ;
471 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
472 (warns, errs) <- readMutVar errs_var ;
473 writeMutVar errs_var (warns, errs `snocBag` err) }
475 addErrs :: [(SrcSpan,Message)] -> TcRn ()
476 addErrs msgs = mappM_ add msgs
478 add (loc,msg) = addErrAt loc msg
480 addReport :: Message -> TcRn ()
481 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
483 addReportAt :: SrcSpan -> Message -> TcRn ()
485 = do { errs_var <- getErrsVar ;
486 rdr_env <- getGlobalRdrEnv ;
487 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
488 (warns, errs) <- readMutVar errs_var ;
489 writeMutVar errs_var (warns `snocBag` warn, errs) }
491 addWarn :: Message -> TcRn ()
492 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
494 addWarnAt :: SrcSpan -> Message -> TcRn ()
495 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
497 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
498 addLocWarn (L loc e) fn = addReportAt loc (fn e)
500 checkErr :: Bool -> Message -> TcRn ()
501 -- Add the error if the bool is False
502 checkErr ok msg = checkM ok (addErr msg)
504 warnIf :: Bool -> Message -> TcRn ()
505 warnIf True msg = addWarn msg
506 warnIf False msg = return ()
508 addMessages :: Messages -> TcRn ()
509 addMessages (m_warns, m_errs)
510 = do { errs_var <- getErrsVar ;
511 (warns, errs) <- readMutVar errs_var ;
512 writeMutVar errs_var (warns `unionBags` m_warns,
513 errs `unionBags` m_errs) }
515 discardWarnings :: TcRn a -> TcRn a
516 -- Ignore warnings inside the thing inside;
517 -- used to ignore-unused-variable warnings inside derived code
518 -- With -dppr-debug, the effects is switched off, so you can still see
519 -- what warnings derived code would give
520 discardWarnings thing_inside
521 | opt_PprStyle_Debug = thing_inside
523 = do { errs_var <- newMutVar emptyMessages
524 ; result <- setErrsVar errs_var thing_inside
525 ; (_warns, errs) <- readMutVar errs_var
526 ; addMessages (emptyBag, errs)
532 try_m :: TcRn r -> TcRn (Either Exception r)
533 -- Does try_m, with a debug-trace on failure
535 = do { mb_r <- tryM thing ;
537 Left exn -> do { traceTc (exn_msg exn); return mb_r }
538 Right r -> return mb_r }
540 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
542 -----------------------
543 recoverM :: TcRn r -- Recovery action; do this if the main one fails
544 -> TcRn r -- Main action: do this first
546 -- Errors in 'thing' are retained
547 recoverM recover thing
548 = do { mb_res <- try_m thing ;
551 Right res -> returnM res }
553 -----------------------
554 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
555 -- (tryTc m) executes m, and returns
556 -- Just r, if m succeeds (returning r)
557 -- Nothing, if m fails
558 -- It also returns all the errors and warnings accumulated by m
559 -- It always succeeds (never raises an exception)
561 = do { errs_var <- newMutVar emptyMessages ;
562 res <- try_m (setErrsVar errs_var m) ;
563 msgs <- readMutVar errs_var ;
564 return (msgs, case res of
566 Right val -> Just val)
567 -- The exception is always the IOEnv built-in
568 -- in exception; see IOEnv.failM
571 -----------------------
572 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
573 -- Run the thing, returning
574 -- Just r, if m succceeds with no error messages
575 -- Nothing, if m fails, or if it succeeds but has error messages
576 -- Either way, the messages are returned; even in the Just case
577 -- there might be warnings
579 = do { (msgs, res) <- tryTc thing
581 ; let errs_found = errorsFound dflags msgs
582 ; return (msgs, case res of
584 Just val | errs_found -> Nothing
585 | otherwise -> Just val)
588 -----------------------
589 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
590 -- Just like tryTcErrs, except that it ensures that the LIE
591 -- for the thing is propagated only if there are no errors
592 -- Hence it's restricted to the type-check monad
593 tryTcLIE thing_inside
594 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
596 Nothing -> return (msgs, Nothing)
597 Just val -> do { extendLIEs lie; return (msgs, Just val) }
600 -----------------------
601 tryTcLIE_ :: TcM r -> TcM r -> TcM r
602 -- (tryTcLIE_ r m) tries m;
603 -- if m succeeds with no error messages, it's the answer
604 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
605 tryTcLIE_ recover main
606 = do { (msgs, mb_res) <- tryTcLIE main
608 Just val -> do { addMessages msgs -- There might be warnings
610 Nothing -> recover -- Discard all msgs
613 -----------------------
614 checkNoErrs :: TcM r -> TcM r
615 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
616 -- If m fails then (checkNoErrsTc m) fails.
617 -- If m succeeds, it checks whether m generated any errors messages
618 -- (it might have recovered internally)
619 -- If so, it fails too.
620 -- Regardless, any errors generated by m are propagated to the enclosing context.
622 = do { (msgs, mb_res) <- tryTcLIE main
626 Just val -> return val
629 ifErrsM :: TcRn r -> TcRn r -> TcRn r
630 -- ifErrsM bale_out main
631 -- does 'bale_out' if there are errors in errors collection
632 -- otherwise does 'main'
633 ifErrsM bale_out normal
634 = do { errs_var <- getErrsVar ;
635 msgs <- readMutVar errs_var ;
637 if errorsFound dflags msgs then
642 failIfErrsM :: TcRn ()
643 -- Useful to avoid error cascades
644 failIfErrsM = ifErrsM failM (return ())
648 %************************************************************************
650 Context management and error message generation
653 %************************************************************************
656 getErrCtxt :: TcM ErrCtxt
657 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
659 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
660 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
662 addErrCtxt :: Message -> TcM a -> TcM a
663 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
665 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
666 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
668 -- Helper function for the above
669 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
670 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
671 env { tcl_ctxt = upd ctxt })
673 -- Conditionally add an error context
674 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
675 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
676 maybeAddErrCtxt Nothing thing_inside = thing_inside
678 popErrCtxt :: TcM a -> TcM a
679 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
681 getInstLoc :: InstOrigin -> TcM InstLoc
683 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
684 return (InstLoc origin loc (tcl_ctxt env)) }
686 addInstCtxt :: InstLoc -> TcM a -> TcM a
687 -- Add the SrcSpan and context from the first Inst in the list
688 -- (they all have similar locations)
689 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
690 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
693 The addErrTc functions add an error message, but do not cause failure.
694 The 'M' variants pass a TidyEnv that has already been used to
695 tidy up the message; we then use it to tidy the context messages
698 addErrTc :: Message -> TcM ()
699 addErrTc err_msg = do { env0 <- tcInitTidyEnv
700 ; addErrTcM (env0, err_msg) }
702 addErrsTc :: [Message] -> TcM ()
703 addErrsTc err_msgs = mappM_ addErrTc err_msgs
705 addErrTcM :: (TidyEnv, Message) -> TcM ()
706 addErrTcM (tidy_env, err_msg)
707 = do { ctxt <- getErrCtxt ;
709 add_err_tcm tidy_env err_msg loc ctxt }
712 The failWith functions add an error message and cause failure
715 failWithTc :: Message -> TcM a -- Add an error message and fail
717 = addErrTc err_msg >> failM
719 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
720 failWithTcM local_and_msg
721 = addErrTcM local_and_msg >> failM
723 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
724 checkTc True err = returnM ()
725 checkTc False err = failWithTc err
728 Warnings have no 'M' variant, nor failure
731 addWarnTc :: Message -> TcM ()
732 addWarnTc msg = do { env0 <- tcInitTidyEnv
733 ; addWarnTcM (env0, msg) }
735 addWarnTcM :: (TidyEnv, Message) -> TcM ()
736 addWarnTcM (env0, msg)
737 = do { ctxt <- getErrCtxt ;
738 ctxt_msgs <- do_ctxt env0 ctxt ;
739 addReport (vcat (ptext SLIT("Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
741 warnTc :: Bool -> Message -> TcM ()
742 warnTc warn_if_true warn_msg
743 | warn_if_true = addWarnTc warn_msg
744 | otherwise = return ()
747 -----------------------------------
750 We initialise the "tidy-env", used for tidying types before printing,
751 by building a reverse map from the in-scope type variables to the
752 OccName that the programmer originally used for them
755 tcInitTidyEnv :: TcM TidyEnv
757 = do { lcl_env <- getLclEnv
758 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
759 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
761 ; return (foldl add emptyTidyEnv nm_tv_prs) }
763 add (env,subst) (name, tyvar)
764 = case tidyOccName env (nameOccName name) of
765 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
767 tyvar' = setTyVarName tyvar name'
768 name' = tidyNameOcc name occ'
771 -----------------------------------
772 Other helper functions
775 add_err_tcm tidy_env err_msg loc ctxt
776 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
777 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
781 do_ctxt tidy_env (c:cs)
782 = do { (tidy_env', m) <- c tidy_env ;
783 ms <- do_ctxt tidy_env' cs ;
786 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
787 | otherwise = take 3 ctxt
790 debugTc is useful for monadic debugging code
793 debugTc :: TcM () -> TcM ()
795 debugTc thing = thing
797 debugTc thing = return ()
801 %************************************************************************
803 Type constraints (the so-called LIE)
805 %************************************************************************
808 nextDFunIndex :: TcM Int -- Get the next dfun index
809 nextDFunIndex = do { env <- getGblEnv
810 ; let dfun_n_var = tcg_dfun_n env
811 ; n <- readMutVar dfun_n_var
812 ; writeMutVar dfun_n_var (n+1)
815 getLIEVar :: TcM (TcRef LIE)
816 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
818 setLIEVar :: TcRef LIE -> TcM a -> TcM a
819 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
821 getLIE :: TcM a -> TcM (a, [Inst])
822 -- (getLIE m) runs m, and returns the type constraints it generates
824 = do { lie_var <- newMutVar emptyLIE ;
825 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
827 lie <- readMutVar lie_var ;
828 return (res, lieToList lie) }
830 extendLIE :: Inst -> TcM ()
832 = do { lie_var <- getLIEVar ;
833 lie <- readMutVar lie_var ;
834 writeMutVar lie_var (inst `consLIE` lie) }
836 extendLIEs :: [Inst] -> TcM ()
840 = do { lie_var <- getLIEVar ;
841 lie <- readMutVar lie_var ;
842 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
846 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
847 -- Set the local type envt, but do *not* disturb other fields,
848 -- notably the lie_var
849 setLclTypeEnv lcl_env thing_inside
850 = updLclEnv upd thing_inside
852 upd env = env { tcl_env = tcl_env lcl_env,
853 tcl_tyvars = tcl_tyvars lcl_env }
857 %************************************************************************
859 Template Haskell context
861 %************************************************************************
864 recordThUse :: TcM ()
865 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
867 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
868 keepAliveTc n = do { env <- getGblEnv;
869 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
871 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
872 keepAliveSetTc ns = do { env <- getGblEnv;
873 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
875 getStage :: TcM ThStage
876 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
878 setStage :: ThStage -> TcM a -> TcM a
879 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
883 %************************************************************************
885 Stuff for the renamer's local env
887 %************************************************************************
890 getLocalRdrEnv :: RnM LocalRdrEnv
891 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
893 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
894 setLocalRdrEnv rdr_env thing_inside
895 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
899 %************************************************************************
901 Stuff for interface decls
903 %************************************************************************
906 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
907 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
909 if_tv_env = emptyOccEnv,
910 if_id_env = emptyOccEnv }
912 initIfaceTcRn :: IfG a -> TcRn a
913 initIfaceTcRn thing_inside
914 = do { tcg_env <- getGblEnv
915 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
916 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
917 ; setEnvs (if_env, ()) thing_inside }
919 initIfaceExtCore :: IfL a -> TcRn a
920 initIfaceExtCore thing_inside
921 = do { tcg_env <- getGblEnv
922 ; let { mod = tcg_mod tcg_env
923 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
924 ; if_env = IfGblEnv {
925 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
926 ; if_lenv = mkIfLclEnv mod doc
928 ; setEnvs (if_env, if_lenv) thing_inside }
930 initIfaceCheck :: HscEnv -> IfG a -> IO a
931 -- Used when checking the up-to-date-ness of the old Iface
932 -- Initialise the environment with no useful info at all
933 initIfaceCheck hsc_env do_this
934 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
935 ; initTcRnIf 'i' hsc_env gbl_env () do_this
938 initIfaceTc :: ModIface
939 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
940 -- Used when type-checking checking an up-to-date interface file
941 -- No type envt from the current module, but we do know the module dependencies
942 initIfaceTc iface do_this
943 = do { tc_env_var <- newMutVar emptyTypeEnv
944 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
945 ; if_lenv = mkIfLclEnv mod doc
947 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
950 mod = mi_module iface
951 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
953 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
954 -- Used when sucking in new Rules in SimplCore
955 -- We have available the type envt of the module being compiled, and we must use it
956 initIfaceRules hsc_env guts do_this
958 type_info = (mg_module guts, return (mg_types guts))
959 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
962 -- Run the thing; any exceptions just bubble out from here
963 ; initTcRnIf 'i' hsc_env gbl_env () do_this
966 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
967 initIfaceLcl mod loc_doc thing_inside
968 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
970 getIfModule :: IfL Module
971 getIfModule = do { env <- getLclEnv; return (if_mod env) }
974 failIfM :: Message -> IfL a
975 -- The Iface monad doesn't have a place to accumulate errors, so we
976 -- just fall over fast if one happens; it "shouldnt happen".
977 -- We use IfL here so that we can get context info out of the local env
979 = do { env <- getLclEnv
980 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
981 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
985 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
986 -- Run thing_inside in an interleaved thread.
987 -- It shares everything with the parent thread, so this is DANGEROUS.
989 -- It returns Nothing if the computation fails
991 -- It's used for lazily type-checking interface
992 -- signatures, which is pretty benign
994 forkM_maybe doc thing_inside
995 = do { unsafeInterleaveM $
996 do { traceIf (text "Starting fork {" <+> doc)
998 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1001 Right r -> do { traceIf (text "} ending fork" <+> doc)
1005 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1006 -- Otherwise we silently discard errors. Errors can legitimately
1007 -- happen when compiling interface signatures (see tcInterfaceSigs)
1008 ifOptM Opt_D_dump_if_trace
1009 (print_errs (hang (text "forkM failed:" <+> doc)
1010 4 (text (show exn))))
1012 ; traceIf (text "} ending fork (badly)" <+> doc)
1016 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1018 forkM :: SDoc -> IfL a -> IfL a
1019 forkM doc thing_inside
1020 = do { mb_res <- forkM_maybe doc thing_inside
1021 ; return (case mb_res of
1022 Nothing -> pgmError "Cannot continue after interface file error"
1023 -- pprPanic "forkM" doc