2 % (c) The University of Glasgow 2006
12 #include "HsVersions.h"
14 import TcRnTypes -- Re-export all
15 import IOEnv -- Re-export all
17 import HsSyn hiding (LIE)
47 import qualified Data.Set as Set
53 %************************************************************************
57 %************************************************************************
63 -> Bool -- True <=> retain renamed syntax trees
66 -> IO (Messages, Maybe r)
67 -- Nothing => error thrown by the thing inside
68 -- (error messages should have been printed already)
70 initTc hsc_env hsc_src keep_rn_syntax mod do_this
71 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
72 tvs_var <- newIORef emptyVarSet ;
73 dfuns_var <- newIORef emptyNameSet ;
74 keep_var <- newIORef emptyNameSet ;
75 used_rdrnames_var <- newIORef Set.empty ;
76 th_var <- newIORef False ;
77 dfun_n_var <- newIORef emptyOccSet ;
78 type_env_var <- case hsc_type_env_var hsc_env of {
79 Just (_mod, te_var) -> return te_var ;
80 Nothing -> newIORef emptyNameEnv } ;
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 = RecFields emptyNameEnv emptyNameSet,
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,
101 tcg_used_rdrnames = used_rdrnames_var,
105 tcg_rn_exports = maybe_rn_syntax [],
106 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
108 tcg_binds = emptyLHsBinds,
109 tcg_warns = NoWarnings,
115 tcg_dfun_n = dfun_n_var,
118 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing,
123 tcl_loc = mkGeneralSrcSpan (fsLit "Top level"),
125 tcl_rdr = emptyLocalRdrEnv,
126 tcl_th_ctxt = topStage,
127 tcl_arrow_ctxt = NoArrowCtxt,
128 tcl_env = emptyNameEnv,
129 tcl_tyvars = tvs_var,
130 tcl_lie = panic "initTc:LIE", -- only valid inside getLIE
131 tcl_tybinds = panic "initTc:tybinds"
132 -- only valid inside a getTyBinds
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
157 -> IO (Messages, Maybe r)
158 initTcPrintErrors env mod todo = do
159 (msgs, res) <- initTc env HsSrcFile False mod todo
163 %************************************************************************
167 %************************************************************************
171 initTcRnIf :: Char -- Tag for unique supply
176 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
177 = do { us <- mkSplitUniqSupply uniq_tag ;
178 ; us_var <- newIORef us ;
180 ; let { env = Env { env_top = hsc_env,
185 ; runIOEnv env thing_inside
189 %************************************************************************
193 %************************************************************************
196 getTopEnv :: TcRnIf gbl lcl HscEnv
197 getTopEnv = do { env <- getEnv; return (env_top env) }
199 getGblEnv :: TcRnIf gbl lcl gbl
200 getGblEnv = do { env <- getEnv; return (env_gbl env) }
202 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
203 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
204 env { env_gbl = upd gbl })
206 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
207 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
209 getLclEnv :: TcRnIf gbl lcl lcl
210 getLclEnv = do { env <- getEnv; return (env_lcl env) }
212 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
213 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
214 env { env_lcl = upd lcl })
216 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
217 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
219 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
220 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
222 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
223 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
230 getDOpts :: TcRnIf gbl lcl DynFlags
231 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
233 doptM :: DynFlag -> TcRnIf gbl lcl Bool
234 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
236 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
237 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
238 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
240 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
241 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
242 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
244 -- | Do it flag is true
245 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
246 ifOptM flag thing_inside = do { b <- doptM flag;
247 if b then thing_inside else return () }
249 getGhcMode :: TcRnIf gbl lcl GhcMode
250 getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
254 getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
255 getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
257 getEps :: TcRnIf gbl lcl ExternalPackageState
258 getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
260 -- Updating the EPS. This should be an atomic operation.
261 -- Note the delicate 'seq' which forces the EPS before putting it in the
262 -- variable. Otherwise what happens is that we get
263 -- write eps_var (....(unsafeRead eps_var)....)
264 -- and if the .... is strict, that's obviously bottom. By forcing it beforehand
265 -- we make the unsafeRead happen before we update the variable.
267 updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
269 updateEps upd_fn = do { traceIf (text "updating EPS")
270 ; eps_var <- getEpsVar
271 ; eps <- readMutVar eps_var
272 ; let { (eps', val) = upd_fn eps }
273 ; seq eps' (writeMutVar eps_var eps')
276 updateEps_ :: (ExternalPackageState -> ExternalPackageState)
278 updateEps_ upd_fn = do { traceIf (text "updating EPS_")
279 ; eps_var <- getEpsVar
280 ; eps <- readMutVar eps_var
281 ; let { eps' = upd_fn eps }
282 ; seq eps' (writeMutVar eps_var eps') }
284 getHpt :: TcRnIf gbl lcl HomePackageTable
285 getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
287 getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
288 getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
289 ; return (eps, hsc_HPT env) }
292 %************************************************************************
296 %************************************************************************
299 newUnique :: TcRnIf gbl lcl Unique
301 = do { env <- getEnv ;
302 let { u_var = env_us env } ;
303 us <- readMutVar u_var ;
304 case splitUniqSupply us of { (us1,_) -> do {
305 writeMutVar u_var us1 ;
306 return $! uniqFromSupply us }}}
307 -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
308 -- a chain of unevaluated supplies behind.
309 -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
310 -- throw away one half of the new split supply. This is safe because this
311 -- is the only place we use that unique. Using the other half of the split
312 -- supply is safer, but slower.
314 newUniqueSupply :: TcRnIf gbl lcl UniqSupply
316 = do { env <- getEnv ;
317 let { u_var = env_us env } ;
318 us <- readMutVar u_var ;
319 case splitUniqSupply us of { (us1,us2) -> do {
320 writeMutVar u_var us1 ;
323 newLocalName :: Name -> TcRnIf gbl lcl Name
324 newLocalName name -- Make a clone
325 = do { uniq <- newUnique
326 ; return (mkInternalName uniq (nameOccName name) (getSrcSpan name)) }
328 newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
329 newSysLocalIds fs tys
330 = do { us <- newUniqueSupply
331 ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
333 instance MonadUnique (IOEnv (Env gbl lcl)) where
334 getUniqueM = newUnique
335 getUniqueSupplyM = newUniqueSupply
339 %************************************************************************
343 %************************************************************************
346 traceTc, traceRn, traceSplice :: SDoc -> TcRn ()
347 traceRn = traceOptTcRn Opt_D_dump_rn_trace
348 traceTc = traceOptTcRn Opt_D_dump_tc_trace
349 traceSplice = traceOptTcRn Opt_D_dump_splices
352 traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()
353 traceIf = traceOptIf Opt_D_dump_if_trace
354 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
357 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
358 traceOptIf flag doc = ifOptM flag $
359 liftIO (printForUser stderr alwaysQualify doc)
361 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
362 traceOptTcRn flag doc = ifOptM flag $ do
365 ; env0 <- tcInitTidyEnv
366 ; ctxt_msgs <- do_ctxt env0 ctxt
367 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
368 ; dumpTcRn real_doc }
370 dumpTcRn :: SDoc -> TcRn ()
371 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv
373 ; liftIO (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
375 debugDumpTcRn :: SDoc -> TcRn ()
376 debugDumpTcRn doc | opt_NoDebugOutput = return ()
377 | otherwise = dumpTcRn doc
379 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
380 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
384 %************************************************************************
386 Typechecker global environment
388 %************************************************************************
391 getModule :: TcRn Module
392 getModule = do { env <- getGblEnv; return (tcg_mod env) }
394 setModule :: Module -> TcRn a -> TcRn a
395 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
397 tcIsHsBoot :: TcRn Bool
398 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
400 getGlobalRdrEnv :: TcRn GlobalRdrEnv
401 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
403 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
404 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
406 getImports :: TcRn ImportAvails
407 getImports = do { env <- getGblEnv; return (tcg_imports env) }
409 getFixityEnv :: TcRn FixityEnv
410 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
412 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
413 extendFixityEnv new_bit
414 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
415 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
417 getRecFieldEnv :: TcRn RecFieldEnv
418 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
420 getDeclaredDefaultTys :: TcRn (Maybe [Type])
421 getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
424 %************************************************************************
428 %************************************************************************
431 getSrcSpanM :: TcRn SrcSpan
432 -- Avoid clash with Name.getSrcLoc
433 getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
435 setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
436 setSrcSpan loc thing_inside
437 | isGoodSrcSpan loc = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
438 | otherwise = thing_inside -- Don't overwrite useful info with useless
440 addLocM :: (a -> TcM b) -> Located a -> TcM b
441 addLocM fn (L loc a) = setSrcSpan loc $ fn a
443 wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
444 wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
446 wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
447 wrapLocFstM fn (L loc a) =
452 wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
453 wrapLocSndM fn (L loc a) =
461 getErrsVar :: TcRn (TcRef Messages)
462 getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
464 setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
465 setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
467 addErr :: Message -> TcRn () -- Ignores the context stack
468 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
470 failWith :: Message -> TcRn a
471 failWith msg = addErr msg >> failM
473 addLocErr :: Located e -> (e -> Message) -> TcRn ()
474 addLocErr (L loc e) fn = addErrAt loc (fn e)
476 addErrAt :: SrcSpan -> Message -> TcRn ()
477 addErrAt loc msg = addLongErrAt loc msg empty
479 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
480 addLongErrAt loc msg extra
481 = do { traceTc (ptext (sLit "Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
482 errs_var <- getErrsVar ;
483 rdr_env <- getGlobalRdrEnv ;
485 let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
486 (warns, errs) <- readMutVar errs_var ;
487 writeMutVar errs_var (warns, errs `snocBag` err) }
489 addErrs :: [(SrcSpan,Message)] -> TcRn ()
490 addErrs msgs = mapM_ add msgs
492 add (loc,msg) = addErrAt loc msg
494 addReport :: Message -> TcRn ()
495 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
497 addReportAt :: SrcSpan -> Message -> TcRn ()
499 = do { errs_var <- getErrsVar ;
500 rdr_env <- getGlobalRdrEnv ;
502 let { warn = mkWarnMsg loc (mkPrintUnqualified dflags rdr_env) msg } ;
503 (warns, errs) <- readMutVar errs_var ;
504 writeMutVar errs_var (warns `snocBag` warn, errs) }
506 addWarn :: Message -> TcRn ()
507 addWarn msg = addReport (ptext (sLit "Warning:") <+> msg)
509 addWarnAt :: SrcSpan -> Message -> TcRn ()
510 addWarnAt loc msg = addReportAt loc (ptext (sLit "Warning:") <+> msg)
512 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
513 addLocWarn (L loc e) fn = addReportAt loc (fn e)
515 checkErr :: Bool -> Message -> TcRn ()
516 -- Add the error if the bool is False
517 checkErr ok msg = unless ok (addErr msg)
519 warnIf :: Bool -> Message -> TcRn ()
520 warnIf True msg = addWarn msg
521 warnIf False _ = return ()
523 addMessages :: Messages -> TcRn ()
524 addMessages (m_warns, m_errs)
525 = do { errs_var <- getErrsVar ;
526 (warns, errs) <- readMutVar errs_var ;
527 writeMutVar errs_var (warns `unionBags` m_warns,
528 errs `unionBags` m_errs) }
530 discardWarnings :: TcRn a -> TcRn a
531 -- Ignore warnings inside the thing inside;
532 -- used to ignore-unused-variable warnings inside derived code
533 -- With -dppr-debug, the effects is switched off, so you can still see
534 -- what warnings derived code would give
535 discardWarnings thing_inside
536 | opt_PprStyle_Debug = thing_inside
538 = do { errs_var <- newMutVar emptyMessages
539 ; result <- setErrsVar errs_var thing_inside
540 ; (_warns, errs) <- readMutVar errs_var
541 ; addMessages (emptyBag, errs)
547 try_m :: TcRn r -> TcRn (Either IOEnvFailure r)
548 -- Does try_m, with a debug-trace on failure
550 = do { mb_r <- tryM thing ;
552 Left exn -> do { traceTc (exn_msg exn); return mb_r }
553 Right _ -> return mb_r }
555 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
557 -----------------------
558 recoverM :: TcRn r -- Recovery action; do this if the main one fails
559 -> TcRn r -- Main action: do this first
561 -- Errors in 'thing' are retained
562 recoverM recover thing
563 = do { mb_res <- try_m thing ;
566 Right res -> return res }
569 -----------------------
570 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
571 -- Drop elements of the input that fail, so the result
572 -- list can be shorter than the argument list
573 mapAndRecoverM _ [] = return []
574 mapAndRecoverM f (x:xs) = do { mb_r <- try_m (f x)
575 ; rs <- mapAndRecoverM f xs
576 ; return (case mb_r of
581 -----------------------
582 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
583 -- (tryTc m) executes m, and returns
584 -- Just r, if m succeeds (returning r)
585 -- Nothing, if m fails
586 -- It also returns all the errors and warnings accumulated by m
587 -- It always succeeds (never raises an exception)
589 = do { errs_var <- newMutVar emptyMessages ;
590 res <- try_m (setErrsVar errs_var m) ;
591 msgs <- readMutVar errs_var ;
592 return (msgs, case res of
594 Right val -> Just val)
595 -- The exception is always the IOEnv built-in
596 -- in exception; see IOEnv.failM
599 -----------------------
600 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
601 -- Run the thing, returning
602 -- Just r, if m succceeds with no error messages
603 -- Nothing, if m fails, or if it succeeds but has error messages
604 -- Either way, the messages are returned; even in the Just case
605 -- there might be warnings
607 = do { (msgs, res) <- tryTc thing
609 ; let errs_found = errorsFound dflags msgs
610 ; return (msgs, case res of
612 Just val | errs_found -> Nothing
613 | otherwise -> Just val)
616 -----------------------
617 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
618 -- Just like tryTcErrs, except that it ensures that the LIE
619 -- for the thing is propagated only if there are no errors
620 -- Hence it's restricted to the type-check monad
621 tryTcLIE thing_inside
622 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
624 Nothing -> return (msgs, Nothing)
625 Just val -> do { extendLIEs lie; return (msgs, Just val) }
628 -----------------------
629 tryTcLIE_ :: TcM r -> TcM r -> TcM r
630 -- (tryTcLIE_ r m) tries m;
631 -- if m succeeds with no error messages, it's the answer
632 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
633 tryTcLIE_ recover main
634 = do { (msgs, mb_res) <- tryTcLIE main
636 Just val -> do { addMessages msgs -- There might be warnings
638 Nothing -> recover -- Discard all msgs
641 -----------------------
642 checkNoErrs :: TcM r -> TcM r
643 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
644 -- If m fails then (checkNoErrsTc m) fails.
645 -- If m succeeds, it checks whether m generated any errors messages
646 -- (it might have recovered internally)
647 -- If so, it fails too.
648 -- Regardless, any errors generated by m are propagated to the enclosing context.
650 = do { (msgs, mb_res) <- tryTcLIE main
654 Just val -> return val
657 ifErrsM :: TcRn r -> TcRn r -> TcRn r
658 -- ifErrsM bale_out main
659 -- does 'bale_out' if there are errors in errors collection
660 -- otherwise does 'main'
661 ifErrsM bale_out normal
662 = do { errs_var <- getErrsVar ;
663 msgs <- readMutVar errs_var ;
665 if errorsFound dflags msgs then
670 failIfErrsM :: TcRn ()
671 -- Useful to avoid error cascades
672 failIfErrsM = ifErrsM failM (return ())
676 %************************************************************************
678 Context management and error message generation
681 %************************************************************************
684 getErrCtxt :: TcM ErrCtxt
685 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
687 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
688 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
690 addErrCtxt :: Message -> TcM a -> TcM a
691 addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
693 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
694 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
696 -- Helper function for the above
697 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
698 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
699 env { tcl_ctxt = upd ctxt })
701 -- Conditionally add an error context
702 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
703 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
704 maybeAddErrCtxt Nothing thing_inside = thing_inside
706 popErrCtxt :: TcM a -> TcM a
707 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
709 getInstLoc :: InstOrigin -> TcM InstLoc
711 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
712 return (InstLoc origin loc (tcl_ctxt env)) }
714 addInstCtxt :: InstLoc -> TcM a -> TcM a
715 -- Add the SrcSpan and context from the first Inst in the list
716 -- (they all have similar locations)
717 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
718 = setSrcSpan src_loc (updCtxt (\_ -> ctxt) thing_inside)
721 The addErrTc functions add an error message, but do not cause failure.
722 The 'M' variants pass a TidyEnv that has already been used to
723 tidy up the message; we then use it to tidy the context messages
726 addErrTc :: Message -> TcM ()
727 addErrTc err_msg = do { env0 <- tcInitTidyEnv
728 ; addErrTcM (env0, err_msg) }
730 addErrsTc :: [Message] -> TcM ()
731 addErrsTc err_msgs = mapM_ addErrTc err_msgs
733 addErrTcM :: (TidyEnv, Message) -> TcM ()
734 addErrTcM (tidy_env, err_msg)
735 = do { ctxt <- getErrCtxt ;
737 add_err_tcm tidy_env err_msg loc ctxt }
740 The failWith functions add an error message and cause failure
743 failWithTc :: Message -> TcM a -- Add an error message and fail
745 = addErrTc err_msg >> failM
747 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
748 failWithTcM local_and_msg
749 = addErrTcM local_and_msg >> failM
751 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
752 checkTc True _ = return ()
753 checkTc False err = failWithTc err
756 Warnings have no 'M' variant, nor failure
759 addWarnTc :: Message -> TcM ()
760 addWarnTc msg = do { env0 <- tcInitTidyEnv
761 ; addWarnTcM (env0, msg) }
763 addWarnTcM :: (TidyEnv, Message) -> TcM ()
764 addWarnTcM (env0, msg)
765 = do { ctxt <- getErrCtxt ;
766 ctxt_msgs <- do_ctxt env0 ctxt ;
767 addReport (vcat (ptext (sLit "Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
769 warnTc :: Bool -> Message -> TcM ()
770 warnTc warn_if_true warn_msg
771 | warn_if_true = addWarnTc warn_msg
772 | otherwise = return ()
775 -----------------------------------
778 We initialise the "tidy-env", used for tidying types before printing,
779 by building a reverse map from the in-scope type variables to the
780 OccName that the programmer originally used for them
783 tcInitTidyEnv :: TcM TidyEnv
785 = do { lcl_env <- getLclEnv
786 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
787 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
789 ; return (foldl add emptyTidyEnv nm_tv_prs) }
791 add (env,subst) (name, tyvar)
792 = case tidyOccName env (nameOccName name) of
793 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
795 tyvar' = setTyVarName tyvar name'
796 name' = tidyNameOcc name occ'
799 -----------------------------------
800 Other helper functions
803 add_err_tcm :: TidyEnv -> Message -> SrcSpan
804 -> [TidyEnv -> TcM (TidyEnv, SDoc)]
806 add_err_tcm tidy_env err_msg loc ctxt
807 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
808 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
810 do_ctxt :: TidyEnv -> [TidyEnv -> TcM (TidyEnv, SDoc)] -> TcM [SDoc]
813 do_ctxt tidy_env (c:cs)
814 = do { (tidy_env', m) <- c tidy_env ;
815 ms <- do_ctxt tidy_env' cs ;
818 ctxt_to_use :: [SDoc] -> [SDoc]
819 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
820 | otherwise = take 3 ctxt
823 debugTc is useful for monadic debugging code
826 debugTc :: TcM () -> TcM ()
829 | otherwise = return ()
832 %************************************************************************
834 Type constraints (the so-called LIE)
836 %************************************************************************
839 chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
840 chooseUniqueOccTc fn =
841 do { env <- getGblEnv
842 ; let dfun_n_var = tcg_dfun_n env
843 ; set <- readMutVar dfun_n_var
845 ; writeMutVar dfun_n_var (extendOccSet set occ)
849 getLIEVar :: TcM (TcRef LIE)
850 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
852 setLIEVar :: TcRef LIE -> TcM a -> TcM a
853 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
855 getLIE :: TcM a -> TcM (a, [Inst])
856 -- (getLIE m) runs m, and returns the type constraints it generates
858 = do { lie_var <- newMutVar emptyLIE ;
859 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
861 lie <- readMutVar lie_var ;
862 return (res, lieToList lie) }
864 extendLIE :: Inst -> TcM ()
866 = do { lie_var <- getLIEVar ;
867 lie <- readMutVar lie_var ;
868 writeMutVar lie_var (inst `consLIE` lie) }
870 extendLIEs :: [Inst] -> TcM ()
874 = do { lie_var <- getLIEVar ;
875 lie <- readMutVar lie_var ;
876 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
880 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
881 -- Set the local type envt, but do *not* disturb other fields,
882 -- notably the lie_var
883 setLclTypeEnv lcl_env thing_inside
884 = updLclEnv upd thing_inside
886 upd env = env { tcl_env = tcl_env lcl_env,
887 tcl_tyvars = tcl_tyvars lcl_env }
891 %************************************************************************
893 Meta type variable bindings
895 %************************************************************************
898 getTcTyVarBindsVar :: TcM (TcRef TcTyVarBinds)
899 getTcTyVarBindsVar = do { env <- getLclEnv; return (tcl_tybinds env) }
901 getTcTyVarBinds :: TcM a -> TcM (a, TcTyVarBinds)
902 getTcTyVarBinds thing_inside
903 = do { tybinds_var <- newMutVar emptyBag
904 ; res <- updLclEnv (\ env -> env { tcl_tybinds = tybinds_var })
906 ; tybinds <- readMutVar tybinds_var
907 ; return (res, tybinds)
910 bindMetaTyVar :: TcTyVar -> TcType -> TcM ()
912 = do { ASSERTM2( do { details <- readMutVar (metaTvRef tv)
913 ; return (isFlexi details) }, ppr tv )
914 ; tybinds_var <- getTcTyVarBindsVar
915 ; tybinds <- readMutVar tybinds_var
916 ; writeMutVar tybinds_var (tybinds `snocBag` TcTyVarBind tv ty)
919 getTcTyVarBindsRelation :: TcM [(TcTyVar, TcTyVarSet)]
920 getTcTyVarBindsRelation
921 = do { tybinds_var <- getTcTyVarBindsVar
922 ; tybinds <- readMutVar tybinds_var
923 ; return $ map freeTvs (bagToList tybinds)
926 freeTvs (TcTyVarBind tv ty) = (tv, tyVarsOfType ty)
929 %************************************************************************
931 Template Haskell context
933 %************************************************************************
936 recordThUse :: TcM ()
937 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
939 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
941 | isLocalId id = do { env <- getGblEnv;
942 ; updMutVar (tcg_keep env) (`addOneToNameSet` idName id) }
943 | otherwise = return ()
945 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
946 keepAliveSetTc ns = do { env <- getGblEnv;
947 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
949 getStage :: TcM ThStage
950 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
952 setStage :: ThStage -> TcM a -> TcM a
953 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
957 %************************************************************************
959 Stuff for the renamer's local env
961 %************************************************************************
964 getLocalRdrEnv :: RnM LocalRdrEnv
965 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
967 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
968 setLocalRdrEnv rdr_env thing_inside
969 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
973 %************************************************************************
975 Stuff for interface decls
977 %************************************************************************
980 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
981 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
983 if_tv_env = emptyUFM,
984 if_id_env = emptyUFM }
986 initIfaceTcRn :: IfG a -> TcRn a
987 initIfaceTcRn thing_inside
988 = do { tcg_env <- getGblEnv
989 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
990 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
991 ; setEnvs (if_env, ()) thing_inside }
993 initIfaceExtCore :: IfL a -> TcRn a
994 initIfaceExtCore thing_inside
995 = do { tcg_env <- getGblEnv
996 ; let { mod = tcg_mod tcg_env
997 ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
998 ; if_env = IfGblEnv {
999 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
1000 ; if_lenv = mkIfLclEnv mod doc
1002 ; setEnvs (if_env, if_lenv) thing_inside }
1004 initIfaceCheck :: HscEnv -> IfG a -> IO a
1005 -- Used when checking the up-to-date-ness of the old Iface
1006 -- Initialise the environment with no useful info at all
1007 initIfaceCheck hsc_env do_this
1008 = do let rec_types = case hsc_type_env_var hsc_env of
1009 Just (mod,var) -> Just (mod, readMutVar var)
1011 gbl_env = IfGblEnv { if_rec_types = rec_types }
1012 initTcRnIf 'i' hsc_env gbl_env () do_this
1014 initIfaceTc :: ModIface
1015 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
1016 -- Used when type-checking checking an up-to-date interface file
1017 -- No type envt from the current module, but we do know the module dependencies
1018 initIfaceTc iface do_this
1019 = do { tc_env_var <- newMutVar emptyTypeEnv
1020 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
1021 ; if_lenv = mkIfLclEnv mod doc
1023 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
1026 mod = mi_module iface
1027 doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
1029 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
1030 -- Used when sucking in new Rules in SimplCore
1031 -- We have available the type envt of the module being compiled, and we must use it
1032 initIfaceRules hsc_env guts do_this
1034 type_info = (mg_module guts, return (mg_types guts))
1035 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
1038 -- Run the thing; any exceptions just bubble out from here
1039 ; initTcRnIf 'i' hsc_env gbl_env () do_this
1042 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
1043 initIfaceLcl mod loc_doc thing_inside
1044 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1046 getIfModule :: IfL Module
1047 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1049 --------------------
1050 failIfM :: Message -> IfL a
1051 -- The Iface monad doesn't have a place to accumulate errors, so we
1052 -- just fall over fast if one happens; it "shouldnt happen".
1053 -- We use IfL here so that we can get context info out of the local env
1055 = do { env <- getLclEnv
1056 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1057 ; liftIO (printErrs (full_msg defaultErrStyle))
1060 --------------------
1061 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1062 -- Run thing_inside in an interleaved thread.
1063 -- It shares everything with the parent thread, so this is DANGEROUS.
1065 -- It returns Nothing if the computation fails
1067 -- It's used for lazily type-checking interface
1068 -- signatures, which is pretty benign
1070 forkM_maybe doc thing_inside
1071 = do { unsafeInterleaveM $
1072 do { traceIf (text "Starting fork {" <+> doc)
1074 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1077 Right r -> do { traceIf (text "} ending fork" <+> doc)
1081 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1082 -- Otherwise we silently discard errors. Errors can legitimately
1083 -- happen when compiling interface signatures (see tcInterfaceSigs)
1084 ifOptM Opt_D_dump_if_trace
1085 (print_errs (hang (text "forkM failed:" <+> doc)
1086 4 (text (show exn))))
1088 ; traceIf (text "} ending fork (badly)" <+> doc)
1092 print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1094 forkM :: SDoc -> IfL a -> IfL a
1095 forkM doc thing_inside
1096 = do { mb_res <- forkM_maybe doc thing_inside
1097 ; return (case mb_res of
1098 Nothing -> pgmError "Cannot continue after interface file error"
1099 -- pprPanic "forkM" doc