2 % (c) The University of Glasgow 2006
12 import TcRnTypes -- Re-export all
13 import IOEnv -- Re-export all
15 import HsSyn hiding (LIE)
52 %************************************************************************
56 %************************************************************************
62 -> Bool -- True <=> retain renamed syntax trees
65 -> IO (Messages, Maybe r)
66 -- Nothing => error thrown by the thing inside
67 -- (error messages should have been printed already)
69 initTc hsc_env hsc_src keep_rn_syntax mod do_this
70 = do { errs_var <- newIORef (emptyBag, emptyBag) ;
71 tvs_var <- newIORef emptyVarSet ;
72 dfuns_var <- newIORef emptyNameSet ;
73 keep_var <- newIORef emptyNameSet ;
74 th_var <- newIORef False ;
75 dfun_n_var <- newIORef 1 ;
76 type_env_var <- case hsc_type_env_var hsc_env of {
77 Just (_mod, te_var) -> return te_var ;
78 Nothing -> newIORef emptyNameEnv } ;
80 maybe_rn_syntax empty_val
81 | keep_rn_syntax = Just empty_val
82 | otherwise = Nothing ;
87 tcg_rdr_env = hsc_global_rdr_env hsc_env,
88 tcg_fix_env = emptyNameEnv,
89 tcg_field_env = emptyNameEnv,
90 tcg_default = Nothing,
91 tcg_type_env = hsc_global_type_env hsc_env,
92 tcg_type_env_var = type_env_var,
93 tcg_inst_env = emptyInstEnv,
94 tcg_fam_inst_env = emptyFamInstEnv,
95 tcg_inst_uses = dfuns_var,
98 tcg_imports = emptyImportAvails,
101 tcg_rn_imports = maybe_rn_syntax [],
102 tcg_rn_exports = maybe_rn_syntax [],
103 tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
105 tcg_binds = emptyLHsBinds,
106 tcg_warns = NoWarnings,
111 tcg_dfun_n = dfun_n_var,
114 tcg_hmi = HaddockModInfo Nothing Nothing Nothing Nothing,
119 tcl_loc = mkGeneralSrcSpan (fsLit "Top level"),
121 tcl_rdr = emptyLocalRdrEnv,
122 tcl_th_ctxt = topStage,
123 tcl_arrow_ctxt = NoArrowCtxt,
124 tcl_env = emptyNameEnv,
125 tcl_tyvars = tvs_var,
126 tcl_lie = panic "initTc:LIE" -- LIE only valid inside a getLIE
130 -- OK, here's the business end!
131 maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
132 do { r <- tryM do_this
134 Right res -> return (Just res)
135 Left _ -> return Nothing } ;
137 -- Collect any error messages
138 msgs <- readIORef errs_var ;
140 let { dflags = hsc_dflags hsc_env
141 ; final_res | errorsFound dflags msgs = Nothing
142 | otherwise = maybe_res } ;
144 return (msgs, final_res)
147 initTcPrintErrors -- Used from the interactive loop only
152 initTcPrintErrors env mod todo = do
153 (msgs, res) <- initTc env HsSrcFile False mod todo
154 printErrorsAndWarnings (hsc_dflags env) msgs
158 %************************************************************************
162 %************************************************************************
166 initTcRnIf :: Char -- Tag for unique supply
171 initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
172 = do { us <- mkSplitUniqSupply uniq_tag ;
173 ; us_var <- newIORef us ;
175 ; let { env = Env { env_top = hsc_env,
180 ; runIOEnv env thing_inside
184 %************************************************************************
188 %************************************************************************
191 getTopEnv :: TcRnIf gbl lcl HscEnv
192 getTopEnv = do { env <- getEnv; return (env_top env) }
194 getGblEnv :: TcRnIf gbl lcl gbl
195 getGblEnv = do { env <- getEnv; return (env_gbl env) }
197 updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
198 updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
199 env { env_gbl = upd gbl })
201 setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
202 setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
204 getLclEnv :: TcRnIf gbl lcl lcl
205 getLclEnv = do { env <- getEnv; return (env_lcl env) }
207 updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
208 updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
209 env { env_lcl = upd lcl })
211 setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
212 setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
214 getEnvs :: TcRnIf gbl lcl (gbl, lcl)
215 getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
217 setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
218 setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
225 getDOpts :: TcRnIf gbl lcl DynFlags
226 getDOpts = do { env <- getTopEnv; return (hsc_dflags env) }
228 doptM :: DynFlag -> TcRnIf gbl lcl Bool
229 doptM flag = do { dflags <- getDOpts; return (dopt flag dflags) }
231 setOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
232 setOptM flag = updEnv (\ env@(Env { env_top = top }) ->
233 env { env_top = top { hsc_dflags = dopt_set (hsc_dflags top) flag}} )
235 unsetOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
236 unsetOptM flag = updEnv (\ env@(Env { env_top = top }) ->
237 env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
239 -- | Do it flag is true
240 ifOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
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) }
328 instance MonadUnique (IOEnv (Env gbl lcl)) where
329 getUniqueM = newUnique
330 getUniqueSupplyM = newUniqueSupply
334 %************************************************************************
338 %************************************************************************
341 traceTc, traceRn, traceSplice :: SDoc -> TcRn ()
342 traceRn = traceOptTcRn Opt_D_dump_rn_trace
343 traceTc = traceOptTcRn Opt_D_dump_tc_trace
344 traceSplice = traceOptTcRn Opt_D_dump_splices
347 traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()
348 traceIf = traceOptIf Opt_D_dump_if_trace
349 traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
352 traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
353 traceOptIf flag doc = ifOptM flag $
354 liftIO (printForUser stderr alwaysQualify doc)
356 traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
357 traceOptTcRn flag doc = ifOptM flag $ do
360 ; env0 <- tcInitTidyEnv
361 ; ctxt_msgs <- do_ctxt env0 ctxt
362 ; let real_doc = mkLocMessage loc (vcat (doc : ctxt_to_use ctxt_msgs))
363 ; dumpTcRn real_doc }
365 dumpTcRn :: SDoc -> TcRn ()
366 dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv ;
368 liftIO (printForUser stderr (mkPrintUnqualified dflags rdr_env) doc) }
370 debugDumpTcRn :: SDoc -> TcRn ()
371 debugDumpTcRn doc | opt_NoDebugOutput = return ()
372 | otherwise = dumpTcRn doc
374 dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
375 dumpOptTcRn flag doc = ifOptM flag (dumpTcRn doc)
379 %************************************************************************
381 Typechecker global environment
383 %************************************************************************
386 getModule :: TcRn Module
387 getModule = do { env <- getGblEnv; return (tcg_mod env) }
389 setModule :: Module -> TcRn a -> TcRn a
390 setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
392 tcIsHsBoot :: TcRn Bool
393 tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
395 getGlobalRdrEnv :: TcRn GlobalRdrEnv
396 getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
398 getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
399 getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
401 getImports :: TcRn ImportAvails
402 getImports = do { env <- getGblEnv; return (tcg_imports env) }
404 getFixityEnv :: TcRn FixityEnv
405 getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
407 extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
408 extendFixityEnv new_bit
409 = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
410 env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
412 getRecFieldEnv :: TcRn RecFieldEnv
413 getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
415 extendRecFieldEnv :: RecFieldEnv -> RnM a -> RnM a
416 extendRecFieldEnv new_bit
417 = updGblEnv (\env@(TcGblEnv { tcg_field_env = old_env }) ->
418 env {tcg_field_env = old_env `plusNameEnv` new_bit})
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 ()
468 addErr msg = do { loc <- getSrcSpanM ; addErrAt loc msg }
470 addLocErr :: Located e -> (e -> Message) -> TcRn ()
471 addLocErr (L loc e) fn = addErrAt loc (fn e)
473 addErrAt :: SrcSpan -> Message -> TcRn ()
474 addErrAt loc msg = addLongErrAt loc msg empty
476 addLongErrAt :: SrcSpan -> Message -> Message -> TcRn ()
477 addLongErrAt loc msg extra
478 = do { traceTc (ptext (sLit "Adding error:") <+> (mkLocMessage loc (msg $$ extra))) ;
479 errs_var <- getErrsVar ;
480 rdr_env <- getGlobalRdrEnv ;
482 let { err = mkLongErrMsg loc (mkPrintUnqualified dflags rdr_env) msg extra } ;
483 (warns, errs) <- readMutVar errs_var ;
484 writeMutVar errs_var (warns, errs `snocBag` err) }
486 addErrs :: [(SrcSpan,Message)] -> TcRn ()
487 addErrs msgs = mapM_ add msgs
489 add (loc,msg) = addErrAt loc msg
491 addReport :: Message -> TcRn ()
492 addReport msg = do loc <- getSrcSpanM; addReportAt loc msg
494 addReportAt :: SrcSpan -> Message -> TcRn ()
496 = do { errs_var <- getErrsVar ;
497 rdr_env <- getGlobalRdrEnv ;
499 let { warn = mkWarnMsg loc (mkPrintUnqualified dflags rdr_env) msg } ;
500 (warns, errs) <- readMutVar errs_var ;
501 writeMutVar errs_var (warns `snocBag` warn, errs) }
503 addWarn :: Message -> TcRn ()
504 addWarn msg = addReport (ptext (sLit "Warning:") <+> msg)
506 addWarnAt :: SrcSpan -> Message -> TcRn ()
507 addWarnAt loc msg = addReportAt loc (ptext (sLit "Warning:") <+> msg)
509 addLocWarn :: Located e -> (e -> Message) -> TcRn ()
510 addLocWarn (L loc e) fn = addReportAt loc (fn e)
512 checkErr :: Bool -> Message -> TcRn ()
513 -- Add the error if the bool is False
514 checkErr ok msg = unless ok (addErr msg)
516 warnIf :: Bool -> Message -> TcRn ()
517 warnIf True msg = addWarn msg
518 warnIf False _ = return ()
520 addMessages :: Messages -> TcRn ()
521 addMessages (m_warns, m_errs)
522 = do { errs_var <- getErrsVar ;
523 (warns, errs) <- readMutVar errs_var ;
524 writeMutVar errs_var (warns `unionBags` m_warns,
525 errs `unionBags` m_errs) }
527 discardWarnings :: TcRn a -> TcRn a
528 -- Ignore warnings inside the thing inside;
529 -- used to ignore-unused-variable warnings inside derived code
530 -- With -dppr-debug, the effects is switched off, so you can still see
531 -- what warnings derived code would give
532 discardWarnings thing_inside
533 | opt_PprStyle_Debug = thing_inside
535 = do { errs_var <- newMutVar emptyMessages
536 ; result <- setErrsVar errs_var thing_inside
537 ; (_warns, errs) <- readMutVar errs_var
538 ; addMessages (emptyBag, errs)
544 #if __GLASGOW_HASKELL__ < 609
545 try_m :: TcRn r -> TcRn (Either Exception r)
547 try_m :: TcRn r -> TcRn (Either ErrorCall r)
549 -- Does try_m, with a debug-trace on failure
551 = do { mb_r <- tryM thing ;
553 Left exn -> do { traceTc (exn_msg exn); return mb_r }
554 Right _ -> return mb_r }
556 exn_msg exn = text "tryTc/recoverM recovering from" <+> text (showException exn)
558 -----------------------
559 recoverM :: TcRn r -- Recovery action; do this if the main one fails
560 -> TcRn r -- Main action: do this first
562 -- Errors in 'thing' are retained
563 recoverM recover thing
564 = do { mb_res <- try_m thing ;
567 Right res -> return res }
570 -----------------------
571 mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
572 -- Drop elements of the input that fail, so the result
573 -- list can be shorter than the argument list
574 mapAndRecoverM _ [] = return []
575 mapAndRecoverM f (x:xs) = do { mb_r <- tryM (f x)
576 ; rs <- mapAndRecoverM f xs
577 ; return (case mb_r of
582 -----------------------
583 tryTc :: TcRn a -> TcRn (Messages, Maybe a)
584 -- (tryTc m) executes m, and returns
585 -- Just r, if m succeeds (returning r)
586 -- Nothing, if m fails
587 -- It also returns all the errors and warnings accumulated by m
588 -- It always succeeds (never raises an exception)
590 = do { errs_var <- newMutVar emptyMessages ;
591 res <- try_m (setErrsVar errs_var m) ;
592 msgs <- readMutVar errs_var ;
593 return (msgs, case res of
595 Right val -> Just val)
596 -- The exception is always the IOEnv built-in
597 -- in exception; see IOEnv.failM
600 -----------------------
601 tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
602 -- Run the thing, returning
603 -- Just r, if m succceeds with no error messages
604 -- Nothing, if m fails, or if it succeeds but has error messages
605 -- Either way, the messages are returned; even in the Just case
606 -- there might be warnings
608 = do { (msgs, res) <- tryTc thing
610 ; let errs_found = errorsFound dflags msgs
611 ; return (msgs, case res of
613 Just val | errs_found -> Nothing
614 | otherwise -> Just val)
617 -----------------------
618 tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
619 -- Just like tryTcErrs, except that it ensures that the LIE
620 -- for the thing is propagated only if there are no errors
621 -- Hence it's restricted to the type-check monad
622 tryTcLIE thing_inside
623 = do { ((msgs, mb_res), lie) <- getLIE (tryTcErrs thing_inside) ;
625 Nothing -> return (msgs, Nothing)
626 Just val -> do { extendLIEs lie; return (msgs, Just val) }
629 -----------------------
630 tryTcLIE_ :: TcM r -> TcM r -> TcM r
631 -- (tryTcLIE_ r m) tries m;
632 -- if m succeeds with no error messages, it's the answer
633 -- otherwise tryTcLIE_ drops everything from m and tries r instead.
634 tryTcLIE_ recover main
635 = do { (msgs, mb_res) <- tryTcLIE main
637 Just val -> do { addMessages msgs -- There might be warnings
639 Nothing -> recover -- Discard all msgs
642 -----------------------
643 checkNoErrs :: TcM r -> TcM r
644 -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
645 -- If m fails then (checkNoErrsTc m) fails.
646 -- If m succeeds, it checks whether m generated any errors messages
647 -- (it might have recovered internally)
648 -- If so, it fails too.
649 -- Regardless, any errors generated by m are propagated to the enclosing context.
651 = do { (msgs, mb_res) <- tryTcLIE main
655 Just val -> return val
658 ifErrsM :: TcRn r -> TcRn r -> TcRn r
659 -- ifErrsM bale_out main
660 -- does 'bale_out' if there are errors in errors collection
661 -- otherwise does 'main'
662 ifErrsM bale_out normal
663 = do { errs_var <- getErrsVar ;
664 msgs <- readMutVar errs_var ;
666 if errorsFound dflags msgs then
671 failIfErrsM :: TcRn ()
672 -- Useful to avoid error cascades
673 failIfErrsM = ifErrsM failM (return ())
677 %************************************************************************
679 Context management and error message generation
682 %************************************************************************
685 getErrCtxt :: TcM ErrCtxt
686 getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
688 setErrCtxt :: ErrCtxt -> TcM a -> TcM a
689 setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
691 addErrCtxt :: Message -> TcM a -> TcM a
692 addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
694 addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, Message)) -> TcM a -> TcM a
695 addErrCtxtM msg = updCtxt (\ msgs -> msg : msgs)
697 -- Helper function for the above
698 updCtxt :: (ErrCtxt -> ErrCtxt) -> TcM a -> TcM a
699 updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
700 env { tcl_ctxt = upd ctxt })
702 -- Conditionally add an error context
703 maybeAddErrCtxt :: Maybe Message -> TcM a -> TcM a
704 maybeAddErrCtxt (Just msg) thing_inside = addErrCtxt msg thing_inside
705 maybeAddErrCtxt Nothing thing_inside = thing_inside
707 popErrCtxt :: TcM a -> TcM a
708 popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
710 getInstLoc :: InstOrigin -> TcM InstLoc
712 = do { loc <- getSrcSpanM ; env <- getLclEnv ;
713 return (InstLoc origin loc (tcl_ctxt env)) }
715 addInstCtxt :: InstLoc -> TcM a -> TcM a
716 -- Add the SrcSpan and context from the first Inst in the list
717 -- (they all have similar locations)
718 addInstCtxt (InstLoc _ src_loc ctxt) thing_inside
719 = setSrcSpan src_loc (updCtxt (\_ -> ctxt) thing_inside)
722 The addErrTc functions add an error message, but do not cause failure.
723 The 'M' variants pass a TidyEnv that has already been used to
724 tidy up the message; we then use it to tidy the context messages
727 addErrTc :: Message -> TcM ()
728 addErrTc err_msg = do { env0 <- tcInitTidyEnv
729 ; addErrTcM (env0, err_msg) }
731 addErrsTc :: [Message] -> TcM ()
732 addErrsTc err_msgs = mapM_ addErrTc err_msgs
734 addErrTcM :: (TidyEnv, Message) -> TcM ()
735 addErrTcM (tidy_env, err_msg)
736 = do { ctxt <- getErrCtxt ;
738 add_err_tcm tidy_env err_msg loc ctxt }
741 The failWith functions add an error message and cause failure
744 failWithTc :: Message -> TcM a -- Add an error message and fail
746 = addErrTc err_msg >> failM
748 failWithTcM :: (TidyEnv, Message) -> TcM a -- Add an error message and fail
749 failWithTcM local_and_msg
750 = addErrTcM local_and_msg >> failM
752 checkTc :: Bool -> Message -> TcM () -- Check that the boolean is true
753 checkTc True _ = return ()
754 checkTc False err = failWithTc err
757 Warnings have no 'M' variant, nor failure
760 addWarnTc :: Message -> TcM ()
761 addWarnTc msg = do { env0 <- tcInitTidyEnv
762 ; addWarnTcM (env0, msg) }
764 addWarnTcM :: (TidyEnv, Message) -> TcM ()
765 addWarnTcM (env0, msg)
766 = do { ctxt <- getErrCtxt ;
767 ctxt_msgs <- do_ctxt env0 ctxt ;
768 addReport (vcat (ptext (sLit "Warning:") <+> msg : ctxt_to_use ctxt_msgs)) }
770 warnTc :: Bool -> Message -> TcM ()
771 warnTc warn_if_true warn_msg
772 | warn_if_true = addWarnTc warn_msg
773 | otherwise = return ()
776 -----------------------------------
779 We initialise the "tidy-env", used for tidying types before printing,
780 by building a reverse map from the in-scope type variables to the
781 OccName that the programmer originally used for them
784 tcInitTidyEnv :: TcM TidyEnv
786 = do { lcl_env <- getLclEnv
787 ; let nm_tv_prs = [ (name, tcGetTyVar "tcInitTidyEnv" ty)
788 | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)
790 ; return (foldl add emptyTidyEnv nm_tv_prs) }
792 add (env,subst) (name, tyvar)
793 = case tidyOccName env (nameOccName name) of
794 (env', occ') -> (env', extendVarEnv subst tyvar tyvar')
796 tyvar' = setTyVarName tyvar name'
797 name' = tidyNameOcc name occ'
800 -----------------------------------
801 Other helper functions
804 add_err_tcm :: TidyEnv -> Message -> SrcSpan
805 -> [TidyEnv -> TcM (TidyEnv, SDoc)]
807 add_err_tcm tidy_env err_msg loc ctxt
808 = do { ctxt_msgs <- do_ctxt tidy_env ctxt ;
809 addLongErrAt loc err_msg (vcat (ctxt_to_use ctxt_msgs)) }
811 do_ctxt :: TidyEnv -> [TidyEnv -> TcM (TidyEnv, SDoc)] -> TcM [SDoc]
814 do_ctxt tidy_env (c:cs)
815 = do { (tidy_env', m) <- c tidy_env ;
816 ms <- do_ctxt tidy_env' cs ;
819 ctxt_to_use :: [SDoc] -> [SDoc]
820 ctxt_to_use ctxt | opt_PprStyle_Debug = ctxt
821 | otherwise = take 3 ctxt
824 debugTc is useful for monadic debugging code
827 debugTc :: TcM () -> TcM ()
830 | otherwise = return ()
833 %************************************************************************
835 Type constraints (the so-called LIE)
837 %************************************************************************
840 nextDFunIndex :: TcM Int -- Get the next dfun index
841 nextDFunIndex = do { env <- getGblEnv
842 ; let dfun_n_var = tcg_dfun_n env
843 ; n <- readMutVar dfun_n_var
844 ; writeMutVar dfun_n_var (n+1)
847 getLIEVar :: TcM (TcRef LIE)
848 getLIEVar = do { env <- getLclEnv; return (tcl_lie env) }
850 setLIEVar :: TcRef LIE -> TcM a -> TcM a
851 setLIEVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
853 getLIE :: TcM a -> TcM (a, [Inst])
854 -- (getLIE m) runs m, and returns the type constraints it generates
856 = do { lie_var <- newMutVar emptyLIE ;
857 res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
859 lie <- readMutVar lie_var ;
860 return (res, lieToList lie) }
862 extendLIE :: Inst -> TcM ()
864 = do { lie_var <- getLIEVar ;
865 lie <- readMutVar lie_var ;
866 writeMutVar lie_var (inst `consLIE` lie) }
868 extendLIEs :: [Inst] -> TcM ()
872 = do { lie_var <- getLIEVar ;
873 lie <- readMutVar lie_var ;
874 writeMutVar lie_var (mkLIE insts `plusLIE` lie) }
878 setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
879 -- Set the local type envt, but do *not* disturb other fields,
880 -- notably the lie_var
881 setLclTypeEnv lcl_env thing_inside
882 = updLclEnv upd thing_inside
884 upd env = env { tcl_env = tcl_env lcl_env,
885 tcl_tyvars = tcl_tyvars lcl_env }
889 %************************************************************************
891 Template Haskell context
893 %************************************************************************
896 recordThUse :: TcM ()
897 recordThUse = do { env <- getGblEnv; writeMutVar (tcg_th_used env) True }
899 keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
901 | isLocalId id = do { env <- getGblEnv;
902 ; updMutVar (tcg_keep env) (`addOneToNameSet` idName id) }
903 | otherwise = return ()
905 keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
906 keepAliveSetTc ns = do { env <- getGblEnv;
907 ; updMutVar (tcg_keep env) (`unionNameSets` ns) }
909 getStage :: TcM ThStage
910 getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
912 setStage :: ThStage -> TcM a -> TcM a
913 setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
917 %************************************************************************
919 Stuff for the renamer's local env
921 %************************************************************************
924 getLocalRdrEnv :: RnM LocalRdrEnv
925 getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
927 setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
928 setLocalRdrEnv rdr_env thing_inside
929 = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
933 %************************************************************************
935 Stuff for interface decls
937 %************************************************************************
940 mkIfLclEnv :: Module -> SDoc -> IfLclEnv
941 mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
943 if_tv_env = emptyUFM,
944 if_id_env = emptyUFM }
946 initIfaceTcRn :: IfG a -> TcRn a
947 initIfaceTcRn thing_inside
948 = do { tcg_env <- getGblEnv
949 ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
950 ; get_type_env = readMutVar (tcg_type_env_var tcg_env) }
951 ; setEnvs (if_env, ()) thing_inside }
953 initIfaceExtCore :: IfL a -> TcRn a
954 initIfaceExtCore thing_inside
955 = do { tcg_env <- getGblEnv
956 ; let { mod = tcg_mod tcg_env
957 ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
958 ; if_env = IfGblEnv {
959 if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
960 ; if_lenv = mkIfLclEnv mod doc
962 ; setEnvs (if_env, if_lenv) thing_inside }
964 initIfaceCheck :: HscEnv -> IfG a -> IO a
965 -- Used when checking the up-to-date-ness of the old Iface
966 -- Initialise the environment with no useful info at all
967 initIfaceCheck hsc_env do_this
968 = do let rec_types = case hsc_type_env_var hsc_env of
969 Just (mod,var) -> Just (mod, readMutVar var)
971 gbl_env = IfGblEnv { if_rec_types = rec_types }
972 initTcRnIf 'i' hsc_env gbl_env () do_this
974 initIfaceTc :: ModIface
975 -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
976 -- Used when type-checking checking an up-to-date interface file
977 -- No type envt from the current module, but we do know the module dependencies
978 initIfaceTc iface do_this
979 = do { tc_env_var <- newMutVar emptyTypeEnv
980 ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readMutVar tc_env_var) } ;
981 ; if_lenv = mkIfLclEnv mod doc
983 ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
986 mod = mi_module iface
987 doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
989 initIfaceRules :: HscEnv -> ModGuts -> IfG a -> IO a
990 -- Used when sucking in new Rules in SimplCore
991 -- We have available the type envt of the module being compiled, and we must use it
992 initIfaceRules hsc_env guts do_this
994 type_info = (mg_module guts, return (mg_types guts))
995 ; gbl_env = IfGblEnv { if_rec_types = Just type_info } ;
998 -- Run the thing; any exceptions just bubble out from here
999 ; initTcRnIf 'i' hsc_env gbl_env () do_this
1002 initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
1003 initIfaceLcl mod loc_doc thing_inside
1004 = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
1006 getIfModule :: IfL Module
1007 getIfModule = do { env <- getLclEnv; return (if_mod env) }
1009 --------------------
1010 failIfM :: Message -> IfL a
1011 -- The Iface monad doesn't have a place to accumulate errors, so we
1012 -- just fall over fast if one happens; it "shouldnt happen".
1013 -- We use IfL here so that we can get context info out of the local env
1015 = do { env <- getLclEnv
1016 ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
1017 ; liftIO (printErrs (full_msg defaultErrStyle))
1020 --------------------
1021 forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
1022 -- Run thing_inside in an interleaved thread.
1023 -- It shares everything with the parent thread, so this is DANGEROUS.
1025 -- It returns Nothing if the computation fails
1027 -- It's used for lazily type-checking interface
1028 -- signatures, which is pretty benign
1030 forkM_maybe doc thing_inside
1031 = do { unsafeInterleaveM $
1032 do { traceIf (text "Starting fork {" <+> doc)
1034 updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
1037 Right r -> do { traceIf (text "} ending fork" <+> doc)
1041 -- Bleat about errors in the forked thread, if -ddump-if-trace is on
1042 -- Otherwise we silently discard errors. Errors can legitimately
1043 -- happen when compiling interface signatures (see tcInterfaceSigs)
1044 ifOptM Opt_D_dump_if_trace
1045 (print_errs (hang (text "forkM failed:" <+> doc)
1046 4 (text (show exn))))
1048 ; traceIf (text "} ending fork (badly)" <+> doc)
1052 print_errs sdoc = liftIO (printErrs (sdoc defaultErrStyle))
1054 forkM :: SDoc -> IfL a -> IfL a
1055 forkM doc thing_inside
1056 = do { mb_res <- forkM_maybe doc thing_inside
1057 ; return (case mb_res of
1058 Nothing -> pgmError "Cannot continue after interface file error"
1059 -- pprPanic "forkM" doc