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)
46 import Control.Exception
51 %************************************************************************
55 %************************************************************************
58 ioToTcRn :: IO r -> TcRn r
66 -> Bool -- True <=> retain renamed syntax trees
69 -> IO (Messages, Maybe r)
70 -- Nothing => error thrown by the thing inside
71 -- (error messages should have been printed already)
73 initTc hsc_env hsc_src keep_rn_syntax mod do_this
74 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
75 tvs_var <- newIORef emptyVarSet ;
76 type_env_var <- newIORef emptyNameEnv ;
77 dfuns_var <- newIORef emptyNameSet ;
78 keep_var <- newIORef emptyNameSet ;
79 th_var <- newIORef False ;
80 dfun_n_var <- newIORef 1 ;
82 maybe_rn_syntax empty_val
83 | keep_rn_syntax = Just empty_val
84 | otherwise = Nothing ;
89 tcg_rdr_env = hsc_global_rdr_env hsc_env,
90 tcg_fix_env = emptyNameEnv,
91 tcg_field_env = emptyNameEnv,
92 tcg_default = Nothing,
93 tcg_type_env = hsc_global_type_env hsc_env,
94 tcg_type_env_var = type_env_var,
95 tcg_inst_env = emptyInstEnv,
96 tcg_fam_inst_env = emptyFamInstEnv,
97 tcg_inst_uses = dfuns_var,
100 tcg_imports = emptyImportAvails,
103 tcg_rn_imports = maybe_rn_syntax [],
104 tcg_rn_exports = maybe_rn_syntax [],
105 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
107 tcg_binds = emptyLHsBinds,
108 tcg_deprecs = NoDeprecs,
113 tcg_dfun_n = dfun_n_var,
116 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing
120 tcl_loc = mkGeneralSrcSpan FSLIT("Top level"),
122 tcl_rdr = emptyLocalRdrEnv,
123 tcl_th_ctxt = topStage,
124 tcl_arrow_ctxt = NoArrowCtxt,
125 tcl_env = emptyNameEnv,
126 tcl_tyvars = tvs_var,
127 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
131 -- OK, here's the business end!
132 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
133 do { r <- tryM do_this
135 Right res -> return (Just res)
136 Left _ -> return Nothing } ;
138 -- Collect any error messages
139 msgs <- readIORef errs_var ;
141 let { dflags = hsc_dflags hsc_env
142 ; final_res | errorsFound dflags msgs = Nothing
143 | otherwise = maybe_res } ;
145 return (msgs, final_res)
148 initTcPrintErrors -- Used from the interactive loop only
153 initTcPrintErrors env mod todo = do
154 (msgs, res) <- initTc env HsSrcFile False mod todo
155 printErrorsAndWarnings (hsc_dflags env) msgs
159 %************************************************************************
163 %************************************************************************
167 initTcRnIf :: Char -- Tag for unique supply
172 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
173 = do { us <- mkSplitUniqSupply uniq_tag ;
174 ; us_var <- newIORef us ;
176 ; let { env = Env { env_top = hsc_env,
179 env_lcl = lcl_env } }
181 ; runIOEnv env thing_inside
185 %************************************************************************
189 %************************************************************************
192 getTopEnv :: TcRnIf gbl lcl HscEnv
193 getTopEnv = do { env <- getEnv; return (env_top env) }
195 getGblEnv :: TcRnIf gbl lcl gbl
196 getGblEnv = do { env <- getEnv; return (env_gbl env) }
198 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
199 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
200 env { env_gbl = upd gbl })
202 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
203 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
205 getLclEnv :: TcRnIf gbl lcl lcl
206 getLclEnv = do { env <- getEnv; return (env_lcl env) }
208 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
209 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
210 env { env_lcl = upd lcl })
212 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
213 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
215 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
216 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
218 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
219 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
226 getDOpts :: TcRnIf gbl lcl DynFlags
227 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
229 doptM :: DynFlag -> TcRnIf gbl lcl Bool
230 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
232 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
233 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
234 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
236 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
237 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
238 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
240 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () -- Do it flag is true
241 ifOptM flag thing_inside = do { b <- doptM flag;
242 if b then thing_inside else return () }
244 getGhcMode :: TcRnIf gbl lcl GhcMode
245 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
249 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
250 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
252 getEps :: TcRnIf gbl lcl ExternalPackageState
253 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
255 -- Updating the EPS. This should be an atomic operation.
256 -- Note the delicate 'seq' which forces the EPS before putting it in the
257 -- variable. Otherwise what happens is that we get
258 -- write eps_var (....(unsafeRead eps_var)....)
259 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
260 -- we make the unsafeRead happen before we update the variable.
262 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
264 updateEps upd_fn = do { traceIf (text "updating EPS")
265 ; eps_var <- getEpsVar
266 ; eps <- readMutVar eps_var
267 ; let { (eps', val) = upd_fn eps }
268 ; seq eps' (writeMutVar eps_var eps')
271 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
273 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
274 ; eps_var <- getEpsVar
275 ; eps <- readMutVar eps_var
276 ; let { eps' = upd_fn eps }
277 ; seq eps' (writeMutVar eps_var eps') }
279 getHpt :: TcRnIf gbl lcl HomePackageTable
280 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
282 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
283 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
284 ; return (eps, hsc_HPT env) }
287 %************************************************************************
291 %************************************************************************
294 newUnique :: TcRnIf gbl lcl Unique
296 = do { env <- getEnv ;
297 let { u_var = env_us env } ;
298 us <- readMutVar u_var ;
299 case splitUniqSupply us of { (us1,_) -> do {
300 writeMutVar u_var us1 ;
301 return $! uniqFromSupply us }}}
302 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
303 -- a chain of unevaluated supplies behind.
304 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
305 -- throw away one half of the new split supply. This is safe because this
306 -- is the only place we use that unique. Using the other half of the split
307 -- supply is safer, but slower.
309 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
311 = do { env <- getEnv ;
312 let { u_var = env_us env } ;
313 us <- readMutVar u_var ;
314 case splitUniqSupply us of { (us1,us2) -> do {
315 writeMutVar u_var us1 ;
318 newLocalName :: Name -> TcRnIf gbl lcl Name
319 newLocalName name -- Make a clone
320 = do { uniq <- newUnique
321 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
323 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
324 newSysLocalIds fs tys
325 = do { us <- newUniqueSupply
326 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
330 %************************************************************************
334 %************************************************************************
337 traceTc, traceRn :: SDoc -> TcRn ()
338 traceRn = traceOptTcRn Opt_D_dump_rn_trace
339 traceTc = traceOptTcRn Opt_D_dump_tc_trace
340 traceSplice = traceOptTcRn Opt_D_dump_splices
343 traceIf :: SDoc -> TcRnIf m n ()
344 traceIf = traceOptIf Opt_D_dump_if_trace
345 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
348 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
349 traceOptIf flag doc = ifOptM flag $
350 ioToIOEnv (printForUser stderr alwaysQualify doc)
352 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
353 traceOptTcRn flag doc = ifOptM flag $ do
356 ; env0 <- tcInitTidyEnv
357 ; ctxt_msgs <- do_ctxt env0 ctxt
358 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
359 ; dumpTcRn real_doc }
361 dumpTcRn :: SDoc -> TcRn ()
362 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
363 ioToTcRn (printForUser stderr (mkPrintUnqualified rdr_env) doc) }
365 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
366 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
370 %************************************************************************
372 Typechecker global environment
374 %************************************************************************
377 getModule :: TcRn Module
378 getModule = do { env <- getGblEnv; return (tcg_mod env) }
380 setModule :: Module -> TcRn a -> TcRn a
381 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
383 tcIsHsBoot :: TcRn Bool
384 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
386 getGlobalRdrEnv :: TcRn GlobalRdrEnv
387 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
389 getImports :: TcRn ImportAvails
390 getImports = do { env <- getGblEnv; return (tcg_imports env) }
392 getFixityEnv :: TcRn FixityEnv
393 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
395 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
396 extendFixityEnv new_bit
397 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
398 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
400 getRecFieldEnv :: TcRn RecFieldEnv
401 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
403 extendRecFieldEnv :: RecFieldEnv -> RnM a -> RnM a
404 extendRecFieldEnv new_bit
405 = updGblEnv (\env@(TcGblEnv { tcg_field_env = old_env }) ->
406 env {tcg_field_env = old_env `plusNameEnv` new_bit})
408 getDeclaredDefaultTys :: TcRn (Maybe [Type])
409 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
412 %************************************************************************
416 %************************************************************************
419 getSrcSpanM :: TcRn SrcSpan
420 -- Avoid clash with Name.getSrcLoc
421 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
423 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
424 setSrcSpan loc thing_inside
425 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
426 | otherwise = thing_inside -- Don't overwrite useful info with useless
428 addLocM :: (a -> TcM b) -> Located a -> TcM b
429 addLocM fn (L loc a) = setSrcSpan loc $ fn a
431 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
432 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
434 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
435 wrapLocFstM fn (L loc a) =
440 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
441 wrapLocSndM fn (L loc a) =
449 getErrsVar :: TcRn (TcRef Messages)
450 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
452 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
453 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
455 addErr :: Message -> TcRn ()
456 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
458 addLocErr :: Located e -> (e -> Message) -> TcRn ()
459 addLocErr (L loc e) fn = addErrAt loc (fn e)
461 addErrAt :: SrcSpan -> Message -> TcRn ()
462 addErrAt loc msg = addLongErrAt loc msg empty
464 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
465 addLongErrAt loc msg extra
466 = do { traceTc (ptext SLIT("Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
467 errs_var <- getErrsVar ;
468 rdr_env <- getGlobalRdrEnv ;
469 let { err = mkLongErrMsg loc (mkPrintUnqualified rdr_env) msg extra } ;
470 (warns, errs) <- readMutVar errs_var ;
471 writeMutVar errs_var (warns, errs `snocBag` err) }
473 addErrs :: [(SrcSpan,Message)] -> TcRn ()
474 addErrs msgs = mappM_ add msgs
476 add (loc,msg) = addErrAt loc msg
478 addReport :: Message -> TcRn ()
479 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
481 addReportAt :: SrcSpan -> Message -> TcRn ()
483 = do { errs_var <- getErrsVar ;
484 rdr_env <- getGlobalRdrEnv ;
485 let { warn = mkWarnMsg loc (mkPrintUnqualified rdr_env) msg } ;
486 (warns, errs) <- readMutVar errs_var ;
487 writeMutVar errs_var (warns `snocBag` warn, errs) }
489 addWarn :: Message -> TcRn ()
490 addWarn msg = addReport (ptext SLIT("Warning:") <+> msg)
492 addWarnAt :: SrcSpan -> Message -> TcRn ()
493 addWarnAt loc msg = addReportAt loc (ptext SLIT("Warning:") <+> msg)
495 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
496 addLocWarn (L loc e) fn = addReportAt loc (fn e)
498 checkErr :: Bool -> Message -> TcRn ()
499 -- Add the error if the bool is False
500 checkErr ok msg = checkM ok (addErr msg)
502 warnIf :: Bool -> Message -> TcRn ()
503 warnIf True msg = addWarn msg
504 warnIf False msg = return ()
506 addMessages :: Messages -> TcRn ()
507 addMessages (m_warns, m_errs)
508 = do { errs_var <- getErrsVar ;
509 (warns, errs) <- readMutVar errs_var ;
510 writeMutVar errs_var (warns `unionBags` m_warns,
511 errs `unionBags` m_errs) }
513 discardWarnings :: TcRn a -> TcRn a
514 -- Ignore warnings inside the thing inside;
515 -- used to ignore-unused-variable warnings inside derived code
516 -- With -dppr-debug, the effects is switched off, so you can still see
517 -- what warnings derived code would give
518 discardWarnings thing_inside
519 | opt_PprStyle_Debug = thing_inside
521 = do { errs_var <- newMutVar emptyMessages
522 ; result <- setErrsVar errs_var thing_inside
523 ; (_warns, errs) <- readMutVar errs_var
524 ; addMessages (emptyBag, errs)
530 try_m :: TcRn r -> TcRn (Either Exception r)
531 -- Does try_m, with a debug-trace on failure
533 = do { mb_r <- tryM thing ;
535 Left exn -> do { traceTc (exn_msg exn); return mb_r }
536 Right r -> return mb_r }
538 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
540 -----------------------
541 recoverM :: TcRn r -- Recovery action; do this if the main one fails
542 -> TcRn r -- Main action: do this first
544 -- Errors in 'thing' are retained
545 recoverM recover thing
546 = do { mb_res <- try_m thing ;
549 Right res -> returnM res }
551 -----------------------
552 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
553 -- (tryTc m) executes m, and returns
554 -- Just r, if m succeeds (returning r)
555 -- Nothing, if m fails
556 -- It also returns all the errors and warnings accumulated by m
557 -- It always succeeds (never raises an exception)
559 = do { errs_var <- newMutVar emptyMessages ;
560 res <- try_m (setErrsVar errs_var m) ;
561 msgs <- readMutVar errs_var ;
562 return (msgs, case res of
564 Right val -> Just val)
565 -- The exception is always the IOEnv built-in
566 -- in exception; see IOEnv.failM
569 -----------------------
570 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
571 -- Run the thing, returning
572 -- Just r, if m succceeds with no error messages
573 -- Nothing, if m fails, or if it succeeds but has error messages
574 -- Either way, the messages are returned; even in the Just case
575 -- there might be warnings
577 = do { (msgs, res) <- tryTc thing
579 ; let errs_found = errorsFound dflags msgs
580 ; return (msgs, case res of
582 Just val | errs_found -> Nothing
583 | otherwise -> Just val)
586 -----------------------
587 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
588 -- Just like tryTcErrs, except that it ensures that the LIE
589 -- for the thing is propagated only if there are no errors
590 -- Hence it's restricted to the type-check monad
591 tryTcLIE thing_inside
592 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
594 Nothing -> return (msgs, Nothing)
595 Just val -> do { extendLIEs lie; return (msgs, Just val) }
598 -----------------------
599 tryTcLIE_ :: TcM r -> TcM r -> TcM r
600 -- (tryTcLIE_ r m) tries m;
601 -- if m succeeds with no error messages, it's the answer
602 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
603 tryTcLIE_ recover main
604 = do { (msgs, mb_res) <- tryTcLIE main
606 Just val -> do { addMessages msgs -- There might be warnings
608 Nothing -> recover -- Discard all msgs
611 -----------------------
612 checkNoErrs :: TcM r -> TcM r
613 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
614 -- If m fails then (checkNoErrsTc m) fails.
615 -- If m succeeds, it checks whether m generated any errors messages
616 -- (it might have recovered internally)
617 -- If so, it fails too.
618 -- Regardless, any errors generated by m are propagated to the enclosing context.
620 = do { (msgs, mb_res) <- tryTcLIE main
624 Just val -> return val
627 ifErrsM :: TcRn r -> TcRn r -> TcRn r
628 -- ifErrsM bale_out main
629 -- does 'bale_out' if there are errors in errors collection
630 -- otherwise does 'main'
631 ifErrsM bale_out normal
632 = do { errs_var <- getErrsVar ;
633 msgs <- readMutVar errs_var ;
635 if errorsFound dflags msgs then
640 failIfErrsM :: TcRn ()
641 -- Useful to avoid error cascades
642 failIfErrsM = ifErrsM failM (return ())
646 %************************************************************************
648 Context management and error message generation
651 %************************************************************************
654 getErrCtxt :: TcM ErrCtxt
655 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
657 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
658 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
660 addErrCtxt :: Message -> TcM a -> TcM a
661 addErrCtxt msg = addErrCtxtM (\env -> returnM (env, msg))
663 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
664 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
666 -- Helper function for the above
667 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
668 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
669 env { tcl_ctxt = upd ctxt })
671 -- Conditionally add an error context
672 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
673 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
674 maybeAddErrCtxt Nothing thing_inside = thing_inside
676 popErrCtxt :: TcM a -> TcM a
677 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (m:ms) -> ms })
679 getInstLoc :: InstOrigin -> TcM InstLoc
681 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
682 return (InstLoc origin loc (tcl_ctxt env)) }
684 addInstCtxt :: InstLoc -> TcM a -> TcM a
685 -- Add the SrcSpan and context from the first Inst in the list
686 -- (they all have similar locations)
687 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
688 = setSrcSpan src_loc (updCtxt (\ old_ctxt -> ctxt) thing_inside)
691 The addErrTc functions add an error message, but do not cause failure.
692 The 'M' variants pass a TidyEnv that has already been used to
693 tidy up the message; we then use it to tidy the context messages
696 addErrTc :: Message -> TcM ()
697 addErrTc err_msg = do { env0 <- tcInitTidyEnv
698 ; addErrTcM (env0, err_msg) }
700 addErrsTc :: [Message] -> TcM ()
701 addErrsTc err_msgs = mappM_ addErrTc err_msgs
703 addErrTcM :: (TidyEnv, Message) -> TcM ()
704 addErrTcM (tidy_env, err_msg)
705 = do { ctxt <- getErrCtxt ;
707 add_err_tcm tidy_env err_msg loc ctxt }
710 The failWith functions add an error message and cause failure
713 failWithTc :: Message -> TcM a -- Add an error message and fail
715 = addErrTc err_msg >> failM
717 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
718 failWithTcM local_and_msg
719 = addErrTcM local_and_msg >> failM
721 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
722 checkTc True err = returnM ()
723 checkTc False err = failWithTc err
726 Warnings have no 'M' variant, nor failure
729 addWarnTc :: Message -> TcM ()
730 addWarnTc msg = do { env0 <- tcInitTidyEnv
731 ; addWarnTcM (env0, msg) }
733 addWarnTcM :: (TidyEnv, Message) -> TcM ()
734 addWarnTcM (env0, msg)
735 = do { ctxt <- getErrCtxt ;
736 ctxt_msgs <- do_ctxt env0 ctxt ;
737 addReport (vcat (ptext SLIT("Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
739 warnTc :: Bool -> Message -> TcM ()
740 warnTc warn_if_true warn_msg
741 | warn_if_true = addWarnTc warn_msg
742 | otherwise = return ()
745 -----------------------------------
748 We initialise the "tidy-env", used for tidying types before printing,
749 by building a reverse map from the in-scope type variables to the
750 OccName that the programmer originally used for them
753 tcInitTidyEnv :: TcM TidyEnv
755 = do { lcl_env <- getLclEnv
756 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
757 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
759 ; return (foldl add emptyTidyEnv nm_tv_prs) }
761 add (env,subst) (name, tyvar)
762 = case tidyOccName env (nameOccName name) of
763 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
765 tyvar' = setTyVarName tyvar name'
766 name' = tidyNameOcc name occ'
769 -----------------------------------
770 Other helper functions
773 add_err_tcm tidy_env err_msg loc ctxt
774 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
775 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
779 do_ctxt tidy_env (c:cs)
780 = do { (tidy_env', m) <- c tidy_env ;
781 ms <- do_ctxt tidy_env' cs ;
784 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
785 | otherwise = take 3 ctxt
788 debugTc is useful for monadic debugging code
791 debugTc :: TcM () -> TcM ()
793 debugTc thing = thing
795 debugTc thing = return ()
799 %************************************************************************
801 Type constraints (the so-called LIE)
803 %************************************************************************
806 nextDFunIndex :: TcM Int -- Get the next dfun index
807 nextDFunIndex = do { env <- getGblEnv
808 ; let dfun_n_var = tcg_dfun_n env
809 ; n <- readMutVar dfun_n_var
810 ; writeMutVar dfun_n_var (n+1)
813 getLIEVar :: TcM (TcRef LIE)
814 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
816 setLIEVar :: TcRef LIE -> TcM a -> TcM a
817 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
819 getLIE :: TcM a -> TcM (a, [Inst])
820 -- (getLIE m) runs m, and returns the type constraints it generates
822 = do { lie_var <- newMutVar emptyLIE ;
823 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
825 lie <- readMutVar lie_var ;
826 return (res, lieToList lie) }
828 extendLIE :: Inst -> TcM ()
830 = do { lie_var <- getLIEVar ;
831 lie <- readMutVar lie_var ;
832 writeMutVar lie_var (inst `consLIE` lie) }
834 extendLIEs :: [Inst] -> TcM ()
838 = do { lie_var <- getLIEVar ;
839 lie <- readMutVar lie_var ;
840 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
844 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
845 -- Set the local type envt, but do *not* disturb other fields,
846 -- notably the lie_var
847 setLclTypeEnv lcl_env thing_inside
848 = updLclEnv upd thing_inside
850 upd env = env { tcl_env = tcl_env lcl_env,
851 tcl_tyvars = tcl_tyvars lcl_env }
855 %************************************************************************
857 Template Haskell context
859 %************************************************************************
862 recordThUse :: TcM ()
863 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
865 keepAliveTc :: Name -> TcM () -- Record the name in the keep-alive set
866 keepAliveTc n = do { env <- getGblEnv;
867 ; updMutVar (tcg_keep env) (`addOneToNameSet` n) }
869 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
870 keepAliveSetTc ns = do { env <- getGblEnv;
871 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
873 getStage :: TcM ThStage
874 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
876 setStage :: ThStage -> TcM a -> TcM a
877 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
881 %************************************************************************
883 Stuff for the renamer's local env
885 %************************************************************************
888 getLocalRdrEnv :: RnM LocalRdrEnv
889 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
891 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
892 setLocalRdrEnv rdr_env thing_inside
893 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
897 %************************************************************************
899 Stuff for interface decls
901 %************************************************************************
904 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
905 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
907 if_tv_env = emptyOccEnv,
908 if_id_env = emptyOccEnv }
910 initIfaceTcRn :: IfG a -> TcRn a
911 initIfaceTcRn thing_inside
912 = do { tcg_env <- getGblEnv
913 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
914 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
915 ; setEnvs (if_env, ()) thing_inside }
917 initIfaceExtCore :: IfL a -> TcRn a
918 initIfaceExtCore thing_inside
919 = do { tcg_env <- getGblEnv
920 ; let { mod = tcg_mod tcg_env
921 ; doc = ptext SLIT("External Core file for") <+> quotes (ppr mod)
922 ; if_env = IfGblEnv {
923 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
924 ; if_lenv = mkIfLclEnv mod doc
926 ; setEnvs (if_env, if_lenv) thing_inside }
928 initIfaceCheck :: HscEnv -> IfG a -> IO a
929 -- Used when checking the up-to-date-ness of the old Iface
930 -- Initialise the environment with no useful info at all
931 initIfaceCheck hsc_env do_this
932 = do { let gbl_env = IfGblEnv { if_rec_types = Nothing }
933 ; initTcRnIf 'i' hsc_env gbl_env () do_this
936 initIfaceTc :: ModIface
937 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
938 -- Used when type-checking checking an up-to-date interface file
939 -- No type envt from the current module, but we do know the module dependencies
940 initIfaceTc iface do_this
941 = do { tc_env_var <- newMutVar emptyTypeEnv
942 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
943 ; if_lenv = mkIfLclEnv mod doc
945 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
948 mod = mi_module iface
949 doc = ptext SLIT("The interface for") <+> quotes (ppr mod)
951 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
952 -- Used when sucking in new Rules in SimplCore
953 -- We have available the type envt of the module being compiled, and we must use it
954 initIfaceRules hsc_env guts do_this
956 type_info = (mg_module guts, return (mg_types guts))
957 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
960 -- Run the thing; any exceptions just bubble out from here
961 ; initTcRnIf 'i' hsc_env gbl_env () do_this
964 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
965 initIfaceLcl mod loc_doc thing_inside
966 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
968 getIfModule :: IfL Module
969 getIfModule = do { env <- getLclEnv; return (if_mod env) }
972 failIfM :: Message -> IfL a
973 -- The Iface monad doesn't have a place to accumulate errors, so we
974 -- just fall over fast if one happens; it "shouldnt happen".
975 -- We use IfL here so that we can get context info out of the local env
977 = do { env <- getLclEnv
978 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
979 ; ioToIOEnv (printErrs (full_msg defaultErrStyle))
983 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
984 -- Run thing_inside in an interleaved thread.
985 -- It shares everything with the parent thread, so this is DANGEROUS.
987 -- It returns Nothing if the computation fails
989 -- It's used for lazily type-checking interface
990 -- signatures, which is pretty benign
992 forkM_maybe doc thing_inside
993 = do { unsafeInterleaveM $
994 do { traceIf (text "Starting fork {" <+> doc)
996 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
999 Right r -> do { traceIf (text "} ending fork" <+> doc)
1003 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1004 -- Otherwise we silently discard errors. Errors can legitimately
1005 -- happen when compiling interface signatures (see tcInterfaceSigs)
1006 ifOptM Opt_D_dump_if_trace
1007 (print_errs (hang (text "forkM failed:" <+> doc)
1008 4 (text (show exn))))
1010 ; traceIf (text "} ending fork (badly)" <+> doc)
1014 print_errs sdoc = ioToIOEnv (printErrs (sdoc defaultErrStyle))
1016 forkM :: SDoc -> IfL a -> IfL a
1017 forkM doc thing_inside
1018 = do { mb_res <- forkM_maybe doc thing_inside
1019 ; return (case mb_res of
1020 Nothing -> pgmError "Cannot continue after interface file error"
1021 -- pprPanic "forkM" doc