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 ; err_info <- mkErrInfo env0 ctxt
367 ; let real_doc = mkLocMessage loc (doc $$ err_info)
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 ctxt = updCtxt (\ ctxts -> (False, ctxt) : ctxts)
696 addLandmarkErrCtxt :: Message -> TcM a -> TcM a
697 addLandmarkErrCtxt msg = updCtxt (\ctxts -> (True, \env -> return (env,msg)) : ctxts)
699 -- Helper function for the above
700 updCtxt :: ([ErrCtxt] -> [ErrCtxt]) -> TcM a -> TcM a
701 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
702 env { tcl_ctxt = upd ctxt })
704 -- Conditionally add an error context
705 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
706 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
707 maybeAddErrCtxt Nothing thing_inside = thing_inside
709 popErrCtxt :: TcM a -> TcM a
710 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
712 getInstLoc :: InstOrigin -> TcM InstLoc
714 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
715 return (InstLoc origin loc (tcl_ctxt env)) }
717 setInstCtxt :: InstLoc -> TcM a -> TcM a
718 -- Add the SrcSpan and context from the first Inst in the list
719 -- (they all have similar locations)
720 setInstCtxt (InstLoc _ src_loc ctxt) thing_inside
721 = setSrcSpan src_loc (setErrCtxt ctxt thing_inside)
724 The addErrTc functions add an error message, but do not cause failure.
725 The 'M' variants pass a TidyEnv that has already been used to
726 tidy up the message; we then use it to tidy the context messages
729 addErrTc :: Message -> TcM ()
730 addErrTc err_msg = do { env0 <- tcInitTidyEnv
731 ; addErrTcM (env0, err_msg) }
733 addErrsTc :: [Message] -> TcM ()
734 addErrsTc err_msgs = mapM_ addErrTc err_msgs
736 addErrTcM :: (TidyEnv, Message) -> TcM ()
737 addErrTcM (tidy_env, err_msg)
738 = do { ctxt <- getErrCtxt ;
740 add_err_tcm tidy_env err_msg loc ctxt }
743 The failWith functions add an error message and cause failure
746 failWithTc :: Message -> TcM a -- Add an error message and fail
748 = addErrTc err_msg >> failM
750 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
751 failWithTcM local_and_msg
752 = addErrTcM local_and_msg >> failM
754 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
755 checkTc True _ = return ()
756 checkTc False err = failWithTc err
759 Warnings have no 'M' variant, nor failure
762 addWarnTc :: Message -> TcM ()
763 addWarnTc msg = do { env0 <- tcInitTidyEnv
764 ; addWarnTcM (env0, msg) }
766 addWarnTcM :: (TidyEnv, Message) -> TcM ()
767 addWarnTcM (env0, msg)
768 = do { ctxt <- getErrCtxt ;
769 err_info <- mkErrInfo env0 ctxt ;
770 addReport (vcat [ptext (sLit "Warning:") <+> msg, err_info]) }
772 warnTc :: Bool -> Message -> TcM ()
773 warnTc warn_if_true warn_msg
774 | warn_if_true = addWarnTc warn_msg
775 | otherwise = return ()
778 -----------------------------------
781 We initialise the "tidy-env", used for tidying types before printing,
782 by building a reverse map from the in-scope type variables to the
783 OccName that the programmer originally used for them
786 tcInitTidyEnv :: TcM TidyEnv
788 = do { lcl_env <- getLclEnv
789 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
790 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
792 ; return (foldl add emptyTidyEnv nm_tv_prs) }
794 add (env,subst) (name, tyvar)
795 = case tidyOccName env (nameOccName name) of
796 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
798 tyvar' = setTyVarName tyvar name'
799 name' = tidyNameOcc name occ'
802 -----------------------------------
803 Other helper functions
806 add_err_tcm :: TidyEnv -> Message -> SrcSpan
809 add_err_tcm tidy_env err_msg loc ctxt
810 = do { err_info <- mkErrInfo tidy_env ctxt ;
811 addLongErrAt loc err_msg err_info }
813 mkErrInfo :: TidyEnv -> [ErrCtxt] -> TcM SDoc
814 -- Tidy the error info, trimming excessive contexts
818 go :: Int -> TidyEnv -> [ErrCtxt] -> TcM SDoc
819 go _ _ [] = return empty
820 go n env ((is_landmark, ctxt) : ctxts)
821 | is_landmark || opt_PprStyle_Debug || n < mAX_CONTEXTS
822 = do { (env', msg) <- ctxt env
823 ; let n' = if is_landmark then n else n+1
824 ; rest <- go n' env' ctxts
825 ; return (msg $$ rest) }
829 mAX_CONTEXTS :: Int -- No more than this number of non-landmark contexts
833 debugTc is useful for monadic debugging code
836 debugTc :: TcM () -> TcM ()
839 | otherwise = return ()
842 %************************************************************************
844 Type constraints (the so-called LIE)
846 %************************************************************************
849 chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
850 chooseUniqueOccTc fn =
851 do { env <- getGblEnv
852 ; let dfun_n_var = tcg_dfun_n env
853 ; set <- readMutVar dfun_n_var
855 ; writeMutVar dfun_n_var (extendOccSet set occ)
859 getLIEVar :: TcM (TcRef LIE)
860 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
862 setLIEVar :: TcRef LIE -> TcM a -> TcM a
863 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
865 getLIE :: TcM a -> TcM (a, [Inst])
866 -- (getLIE m) runs m, and returns the type constraints it generates
868 = do { lie_var <- newMutVar emptyLIE ;
869 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
871 lie <- readMutVar lie_var ;
872 return (res, lieToList lie) }
874 extendLIE :: Inst -> TcM ()
876 = do { lie_var <- getLIEVar ;
877 lie <- readMutVar lie_var ;
878 writeMutVar lie_var (inst `consLIE` lie) }
880 extendLIEs :: [Inst] -> TcM ()
884 = do { lie_var <- getLIEVar ;
885 lie <- readMutVar lie_var ;
886 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
890 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
891 -- Set the local type envt, but do *not* disturb other fields,
892 -- notably the lie_var
893 setLclTypeEnv lcl_env thing_inside
894 = updLclEnv upd thing_inside
896 upd env = env { tcl_env = tcl_env lcl_env,
897 tcl_tyvars = tcl_tyvars lcl_env }
901 %************************************************************************
903 Meta type variable bindings
905 %************************************************************************
908 getTcTyVarBindsVar :: TcM (TcRef TcTyVarBinds)
909 getTcTyVarBindsVar = do { env <- getLclEnv; return (tcl_tybinds env) }
911 getTcTyVarBinds :: TcM a -> TcM (a, TcTyVarBinds)
912 getTcTyVarBinds thing_inside
913 = do { tybinds_var <- newMutVar emptyBag
914 ; res <- updLclEnv (\ env -> env { tcl_tybinds = tybinds_var })
916 ; tybinds <- readMutVar tybinds_var
917 ; return (res, tybinds)
920 bindMetaTyVar :: TcTyVar -> TcType -> TcM ()
922 = do { ASSERTM2( do { details <- readMutVar (metaTvRef tv)
923 ; return (isFlexi details) }, ppr tv )
924 ; tybinds_var <- getTcTyVarBindsVar
925 ; tybinds <- readMutVar tybinds_var
926 ; writeMutVar tybinds_var (tybinds `snocBag` TcTyVarBind tv ty)
929 getTcTyVarBindsRelation :: TcM [(TcTyVar, TcTyVarSet)]
930 getTcTyVarBindsRelation
931 = do { tybinds_var <- getTcTyVarBindsVar
932 ; tybinds <- readMutVar tybinds_var
933 ; return $ map freeTvs (bagToList tybinds)
936 freeTvs (TcTyVarBind tv ty) = (tv, tyVarsOfType ty)
939 %************************************************************************
941 Template Haskell context
943 %************************************************************************
946 recordThUse :: TcM ()
947 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
949 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
951 | isLocalId id = do { env <- getGblEnv;
952 ; updMutVar (tcg_keep env) (`addOneToNameSet` idName id) }
953 | otherwise = return ()
955 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
956 keepAliveSetTc ns = do { env <- getGblEnv;
957 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
959 getStage :: TcM ThStage
960 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
962 setStage :: ThStage -> TcM a -> TcM a
963 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
967 %************************************************************************
969 Stuff for the renamer's local env
971 %************************************************************************
974 getLocalRdrEnv :: RnM LocalRdrEnv
975 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
977 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
978 setLocalRdrEnv rdr_env thing_inside
979 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
983 %************************************************************************
985 Stuff for interface decls
987 %************************************************************************
990 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
991 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
993 if_tv_env = emptyUFM,
994 if_id_env = emptyUFM }
996 initIfaceTcRn :: IfG a -> TcRn a
997 initIfaceTcRn thing_inside
998 = do { tcg_env <- getGblEnv
999 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
1000 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
1001 ; setEnvs (if_env, ()) thing_inside }
1003 initIfaceExtCore :: IfL a -> TcRn a
1004 initIfaceExtCore thing_inside
1005 = do { tcg_env <- getGblEnv
1006 ; let { mod = tcg_mod tcg_env
1007 ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
1008 ; if_env = IfGblEnv {
1009 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
1010 ; if_lenv = mkIfLclEnv mod doc
1012 ; setEnvs (if_env, if_lenv) thing_inside }
1014 initIfaceCheck :: HscEnv -> IfG a -> IO a
1015 -- Used when checking the up-to-date-ness of the old Iface
1016 -- Initialise the environment with no useful info at all
1017 initIfaceCheck hsc_env do_this
1018 = do let rec_types = case hsc_type_env_var hsc_env of
1019 Just (mod,var) -> Just (mod, readMutVar var)
1021 gbl_env = IfGblEnv { if_rec_types = rec_types }
1022 initTcRnIf 'i' hsc_env gbl_env () do_this
1024 initIfaceTc :: ModIface
1025 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
1026 -- Used when type-checking checking an up-to-date interface file
1027 -- No type envt from the current module, but we do know the module dependencies
1028 initIfaceTc iface do_this
1029 = do { tc_env_var <- newMutVar emptyTypeEnv
1030 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
1031 ; if_lenv = mkIfLclEnv mod doc
1033 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
1036 mod = mi_module iface
1037 doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
1039 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
1040 -- Used when sucking in new Rules in SimplCore
1041 -- We have available the type envt of the module being compiled, and we must use it
1042 initIfaceRules hsc_env guts do_this
1044 type_info = (mg_module guts, return (mg_types guts))
1045 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
1048 -- Run the thing; any exceptions just bubble out from here
1049 ; initTcRnIf 'i' hsc_env gbl_env () do_this
1052 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
1053 initIfaceLcl mod loc_doc thing_inside
1054 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1056 getIfModule :: IfL Module
1057 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1059 --------------------
1060 failIfM :: Message -> IfL a
1061 -- The Iface monad doesn't have a place to accumulate errors, so we
1062 -- just fall over fast if one happens; it "shouldnt happen".
1063 -- We use IfL here so that we can get context info out of the local env
1065 = do { env <- getLclEnv
1066 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1067 ; liftIO (printErrs (full_msg defaultErrStyle))
1070 --------------------
1071 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1072 -- Run thing_inside in an interleaved thread.
1073 -- It shares everything with the parent thread, so this is DANGEROUS.
1075 -- It returns Nothing if the computation fails
1077 -- It's used for lazily type-checking interface
1078 -- signatures, which is pretty benign
1080 forkM_maybe doc thing_inside
1081 = do { unsafeInterleaveM $
1082 do { traceIf (text "Starting fork {" <+> doc)
1084 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1087 Right r -> do { traceIf (text "} ending fork" <+> doc)
1091 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1092 -- Otherwise we silently discard errors. Errors can legitimately
1093 -- happen when compiling interface signatures (see tcInterfaceSigs)
1094 ifOptM Opt_D_dump_if_trace
1095 (print_errs (hang (text "forkM failed:" <+> doc)
1096 4 (text (show exn))))
1098 ; traceIf (text "} ending fork (badly)" <+> doc)
1102 print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1104 forkM :: SDoc -> IfL a -> IfL a
1105 forkM doc thing_inside
1106 = do { mb_res <- forkM_maybe doc thing_inside
1107 ; return (case mb_res of
1108 Nothing -> pgmError "Cannot continue after interface file error"
1109 -- pprPanic "forkM" doc