PageRenderTime 63ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/typecheck/TcRnMonad.lhs

https://bitbucket.org/carter/ghc
Haskell | 1282 lines | 944 code | 231 blank | 107 comment | 15 complexity | 31bfec1ea8d98550f188de496db6a94e MD5 | raw file
  1. %
  2. % (c) The University of Glasgow 2006
  3. %
  4. Functions for working with the typechecker environment (setters, getters...).
  5. \begin{code}
  6. {-# OPTIONS_GHC -fno-warn-orphans #-}
  7. module TcRnMonad(
  8. module TcRnMonad,
  9. module TcRnTypes,
  10. module IOEnv
  11. ) where
  12. #include "HsVersions.h"
  13. import TcRnTypes -- Re-export all
  14. import IOEnv -- Re-export all
  15. import TcEvidence
  16. import HsSyn hiding (LIE)
  17. import HscTypes
  18. import Module
  19. import RdrName
  20. import Name
  21. import Type
  22. import Kind ( isSuperKind )
  23. import TcType
  24. import InstEnv
  25. import FamInstEnv
  26. import PrelNames
  27. import Var
  28. import Id
  29. import VarSet
  30. import VarEnv
  31. import ErrUtils
  32. import SrcLoc
  33. import NameEnv
  34. import NameSet
  35. import Bag
  36. import Outputable
  37. import UniqSupply
  38. import UniqFM
  39. import DynFlags
  40. import Maybes
  41. import StaticFlags
  42. import FastString
  43. import Panic
  44. import Util
  45. import Data.IORef
  46. import qualified Data.Set as Set
  47. import Control.Monad
  48. \end{code}
  49. %************************************************************************
  50. %* *
  51. initTc
  52. %* *
  53. %************************************************************************
  54. \begin{code}
  55. -- | Setup the initial typechecking environment
  56. initTc :: HscEnv
  57. -> HscSource
  58. -> Bool -- True <=> retain renamed syntax trees
  59. -> Module
  60. -> TcM r
  61. -> IO (Messages, Maybe r)
  62. -- Nothing => error thrown by the thing inside
  63. -- (error messages should have been printed already)
  64. initTc hsc_env hsc_src keep_rn_syntax mod do_this
  65. = do { errs_var <- newIORef (emptyBag, emptyBag) ;
  66. tvs_var <- newIORef emptyVarSet ;
  67. keep_var <- newIORef emptyNameSet ;
  68. used_rdr_var <- newIORef Set.empty ;
  69. th_var <- newIORef False ;
  70. th_splice_var<- newIORef False ;
  71. infer_var <- newIORef True ;
  72. lie_var <- newIORef emptyWC ;
  73. dfun_n_var <- newIORef emptyOccSet ;
  74. type_env_var <- case hsc_type_env_var hsc_env of {
  75. Just (_mod, te_var) -> return te_var ;
  76. Nothing -> newIORef emptyNameEnv } ;
  77. dependent_files_var <- newIORef [] ;
  78. let {
  79. maybe_rn_syntax :: forall a. a -> Maybe a ;
  80. maybe_rn_syntax empty_val
  81. | keep_rn_syntax = Just empty_val
  82. | otherwise = Nothing ;
  83. gbl_env = TcGblEnv {
  84. tcg_mod = mod,
  85. tcg_src = hsc_src,
  86. tcg_rdr_env = emptyGlobalRdrEnv,
  87. tcg_fix_env = emptyNameEnv,
  88. tcg_field_env = RecFields emptyNameEnv emptyNameSet,
  89. tcg_default = Nothing,
  90. tcg_type_env = emptyNameEnv,
  91. tcg_type_env_var = type_env_var,
  92. tcg_inst_env = emptyInstEnv,
  93. tcg_fam_inst_env = emptyFamInstEnv,
  94. tcg_th_used = th_var,
  95. tcg_th_splice_used = th_splice_var,
  96. tcg_exports = [],
  97. tcg_imports = emptyImportAvails,
  98. tcg_used_rdrnames = used_rdr_var,
  99. tcg_dus = emptyDUs,
  100. tcg_rn_imports = [],
  101. tcg_rn_exports = maybe_rn_syntax [],
  102. tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
  103. tcg_binds = emptyLHsBinds,
  104. tcg_imp_specs = [],
  105. tcg_sigs = emptyNameSet,
  106. tcg_ev_binds = emptyBag,
  107. tcg_warns = NoWarnings,
  108. tcg_anns = [],
  109. tcg_tcs = [],
  110. tcg_insts = [],
  111. tcg_fam_insts = [],
  112. tcg_rules = [],
  113. tcg_fords = [],
  114. tcg_vects = [],
  115. tcg_dfun_n = dfun_n_var,
  116. tcg_keep = keep_var,
  117. tcg_doc_hdr = Nothing,
  118. tcg_hpc = False,
  119. tcg_main = Nothing,
  120. tcg_safeInfer = infer_var,
  121. tcg_dependent_files = dependent_files_var
  122. } ;
  123. lcl_env = TcLclEnv {
  124. tcl_errs = errs_var,
  125. tcl_loc = mkGeneralSrcSpan (fsLit "Top level"),
  126. tcl_ctxt = [],
  127. tcl_rdr = emptyLocalRdrEnv,
  128. tcl_th_ctxt = topStage,
  129. tcl_arrow_ctxt = NoArrowCtxt,
  130. tcl_env = emptyNameEnv,
  131. tcl_bndrs = [],
  132. tcl_tidy = emptyTidyEnv,
  133. tcl_tyvars = tvs_var,
  134. tcl_lie = lie_var,
  135. tcl_untch = noUntouchables
  136. } ;
  137. } ;
  138. -- OK, here's the business end!
  139. maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
  140. do { r <- tryM do_this
  141. ; case r of
  142. Right res -> return (Just res)
  143. Left _ -> return Nothing } ;
  144. -- Check for unsolved constraints
  145. lie <- readIORef lie_var ;
  146. if isEmptyWC lie
  147. then return ()
  148. else pprPanic "initTc: unsolved constraints"
  149. (pprWantedsWithLocs lie) ;
  150. -- Collect any error messages
  151. msgs <- readIORef errs_var ;
  152. let { dflags = hsc_dflags hsc_env
  153. ; final_res | errorsFound dflags msgs = Nothing
  154. | otherwise = maybe_res } ;
  155. return (msgs, final_res)
  156. }
  157. initTcPrintErrors -- Used from the interactive loop only
  158. :: HscEnv
  159. -> Module
  160. -> TcM r
  161. -> IO (Messages, Maybe r)
  162. initTcPrintErrors env mod todo = initTc env HsSrcFile False mod todo
  163. initTcForLookup :: HscEnv -> TcM a -> IO a
  164. initTcForLookup hsc_env = liftM (expectJust "initTcInteractive" . snd) . initTc hsc_env HsSrcFile False iNTERACTIVE
  165. \end{code}
  166. %************************************************************************
  167. %* *
  168. Initialisation
  169. %* *
  170. %************************************************************************
  171. \begin{code}
  172. initTcRnIf :: Char -- Tag for unique supply
  173. -> HscEnv
  174. -> gbl -> lcl
  175. -> TcRnIf gbl lcl a
  176. -> IO a
  177. initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
  178. = do { us <- mkSplitUniqSupply uniq_tag ;
  179. ; us_var <- newIORef us ;
  180. ; let { env = Env { env_top = hsc_env,
  181. env_us = us_var,
  182. env_gbl = gbl_env,
  183. env_lcl = lcl_env} }
  184. ; runIOEnv env thing_inside
  185. }
  186. \end{code}
  187. %************************************************************************
  188. %* *
  189. Simple accessors
  190. %* *
  191. %************************************************************************
  192. \begin{code}
  193. discardResult :: TcM a -> TcM ()
  194. discardResult a = a >> return ()
  195. getTopEnv :: TcRnIf gbl lcl HscEnv
  196. getTopEnv = do { env <- getEnv; return (env_top env) }
  197. getGblEnv :: TcRnIf gbl lcl gbl
  198. getGblEnv = do { env <- getEnv; return (env_gbl env) }
  199. updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
  200. updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
  201. env { env_gbl = upd gbl })
  202. setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
  203. setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
  204. getLclEnv :: TcRnIf gbl lcl lcl
  205. getLclEnv = do { env <- getEnv; return (env_lcl env) }
  206. updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
  207. updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
  208. env { env_lcl = upd lcl })
  209. setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
  210. setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
  211. getEnvs :: TcRnIf gbl lcl (gbl, lcl)
  212. getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
  213. setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
  214. setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
  215. \end{code}
  216. Command-line flags
  217. \begin{code}
  218. xoptM :: ExtensionFlag -> TcRnIf gbl lcl Bool
  219. xoptM flag = do { dflags <- getDynFlags; return (xopt flag dflags) }
  220. doptM :: DynFlag -> TcRnIf gbl lcl Bool
  221. doptM flag = do { dflags <- getDynFlags; return (dopt flag dflags) }
  222. woptM :: WarningFlag -> TcRnIf gbl lcl Bool
  223. woptM flag = do { dflags <- getDynFlags; return (wopt flag dflags) }
  224. setXOptM :: ExtensionFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
  225. setXOptM flag = updEnv (\ env@(Env { env_top = top }) ->
  226. env { env_top = top { hsc_dflags = xopt_set (hsc_dflags top) flag}} )
  227. unsetDOptM :: DynFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
  228. unsetDOptM flag = updEnv (\ env@(Env { env_top = top }) ->
  229. env { env_top = top { hsc_dflags = dopt_unset (hsc_dflags top) flag}} )
  230. unsetWOptM :: WarningFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
  231. unsetWOptM flag = updEnv (\ env@(Env { env_top = top }) ->
  232. env { env_top = top { hsc_dflags = wopt_unset (hsc_dflags top) flag}} )
  233. -- | Do it flag is true
  234. ifDOptM :: DynFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
  235. ifDOptM flag thing_inside = do b <- doptM flag
  236. when b thing_inside
  237. ifWOptM :: WarningFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
  238. ifWOptM flag thing_inside = do b <- woptM flag
  239. when b thing_inside
  240. ifXOptM :: ExtensionFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
  241. ifXOptM flag thing_inside = do b <- xoptM flag
  242. when b thing_inside
  243. getGhcMode :: TcRnIf gbl lcl GhcMode
  244. getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
  245. \end{code}
  246. \begin{code}
  247. getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
  248. getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
  249. getEps :: TcRnIf gbl lcl ExternalPackageState
  250. getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
  251. -- | Update the external package state. Returns the second result of the
  252. -- modifier function.
  253. --
  254. -- This is an atomic operation and forces evaluation of the modified EPS in
  255. -- order to avoid space leaks.
  256. updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
  257. -> TcRnIf gbl lcl a
  258. updateEps upd_fn = do
  259. traceIf (text "updating EPS")
  260. eps_var <- getEpsVar
  261. atomicUpdMutVar' eps_var upd_fn
  262. -- | Update the external package state.
  263. --
  264. -- This is an atomic operation and forces evaluation of the modified EPS in
  265. -- order to avoid space leaks.
  266. updateEps_ :: (ExternalPackageState -> ExternalPackageState)
  267. -> TcRnIf gbl lcl ()
  268. updateEps_ upd_fn = do
  269. traceIf (text "updating EPS_")
  270. eps_var <- getEpsVar
  271. atomicUpdMutVar' eps_var (\eps -> (upd_fn eps, ()))
  272. getHpt :: TcRnIf gbl lcl HomePackageTable
  273. getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
  274. getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
  275. getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
  276. ; return (eps, hsc_HPT env) }
  277. \end{code}
  278. %************************************************************************
  279. %* *
  280. Unique supply
  281. %* *
  282. %************************************************************************
  283. \begin{code}
  284. newUnique :: TcRnIf gbl lcl Unique
  285. newUnique
  286. = do { env <- getEnv ;
  287. let { u_var = env_us env } ;
  288. us <- readMutVar u_var ;
  289. case takeUniqFromSupply us of { (uniq, us') -> do {
  290. writeMutVar u_var us' ;
  291. return $! uniq }}}
  292. -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
  293. -- a chain of unevaluated supplies behind.
  294. -- NOTE 2: we use the uniq in the supply from the MutVar directly, and
  295. -- throw away one half of the new split supply. This is safe because this
  296. -- is the only place we use that unique. Using the other half of the split
  297. -- supply is safer, but slower.
  298. newUniqueSupply :: TcRnIf gbl lcl UniqSupply
  299. newUniqueSupply
  300. = do { env <- getEnv ;
  301. let { u_var = env_us env } ;
  302. us <- readMutVar u_var ;
  303. case splitUniqSupply us of { (us1,us2) -> do {
  304. writeMutVar u_var us1 ;
  305. return us2 }}}
  306. newLocalName :: Name -> TcM Name
  307. newLocalName name = newName (nameOccName name)
  308. newName :: OccName -> TcM Name
  309. newName occ
  310. = do { uniq <- newUnique
  311. ; loc <- getSrcSpanM
  312. ; return (mkInternalName uniq occ loc) }
  313. newSysName :: OccName -> TcM Name
  314. newSysName occ
  315. = do { uniq <- newUnique
  316. ; return (mkSystemName uniq occ) }
  317. newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
  318. newSysLocalIds fs tys
  319. = do { us <- newUniqueSupply
  320. ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
  321. instance MonadUnique (IOEnv (Env gbl lcl)) where
  322. getUniqueM = newUnique
  323. getUniqueSupplyM = newUniqueSupply
  324. \end{code}
  325. %************************************************************************
  326. %* *
  327. Debugging
  328. %* *
  329. %************************************************************************
  330. \begin{code}
  331. newTcRef :: a -> TcRnIf gbl lcl (TcRef a)
  332. newTcRef = newMutVar
  333. readTcRef :: TcRef a -> TcRnIf gbl lcl a
  334. readTcRef = readMutVar
  335. writeTcRef :: TcRef a -> a -> TcRnIf gbl lcl ()
  336. writeTcRef = writeMutVar
  337. updTcRef :: TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
  338. updTcRef = updMutVar
  339. \end{code}
  340. %************************************************************************
  341. %* *
  342. Debugging
  343. %* *
  344. %************************************************************************
  345. \begin{code}
  346. traceTc :: String -> SDoc -> TcRn ()
  347. traceTc = traceTcN 1
  348. traceTcN :: Int -> String -> SDoc -> TcRn ()
  349. traceTcN level herald doc
  350. = do dflags <- getDynFlags
  351. when (level <= traceLevel dflags) $
  352. traceOptTcRn Opt_D_dump_tc_trace $ hang (text herald) 2 doc
  353. traceRn, traceSplice :: SDoc -> TcRn ()
  354. traceRn = traceOptTcRn Opt_D_dump_rn_trace
  355. traceSplice = traceOptTcRn Opt_D_dump_splices
  356. traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()
  357. traceIf = traceOptIf Opt_D_dump_if_trace
  358. traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
  359. traceOptIf :: DynFlag -> SDoc -> TcRnIf m n () -- No RdrEnv available, so qualify everything
  360. traceOptIf flag doc = ifDOptM flag $
  361. do dflags <- getDynFlags
  362. liftIO (printInfoForUser dflags alwaysQualify doc)
  363. traceOptTcRn :: DynFlag -> SDoc -> TcRn ()
  364. -- Output the message, with current location if opt_PprStyle_Debug
  365. traceOptTcRn flag doc = ifDOptM flag $ do
  366. { loc <- getSrcSpanM
  367. ; let real_doc
  368. | opt_PprStyle_Debug = mkLocMessage SevInfo loc doc
  369. | otherwise = doc -- The full location is
  370. -- usually way too much
  371. ; dumpTcRn real_doc }
  372. dumpTcRn :: SDoc -> TcRn ()
  373. dumpTcRn doc = do { rdr_env <- getGlobalRdrEnv
  374. ; dflags <- getDynFlags
  375. ; liftIO (printInfoForUser dflags (mkPrintUnqualified dflags rdr_env) doc) }
  376. debugDumpTcRn :: SDoc -> TcRn ()
  377. debugDumpTcRn doc | opt_NoDebugOutput = return ()
  378. | otherwise = dumpTcRn doc
  379. dumpOptTcRn :: DynFlag -> SDoc -> TcRn ()
  380. dumpOptTcRn flag doc = ifDOptM flag (dumpTcRn doc)
  381. \end{code}
  382. %************************************************************************
  383. %* *
  384. Typechecker global environment
  385. %* *
  386. %************************************************************************
  387. \begin{code}
  388. getModule :: TcRn Module
  389. getModule = do { env <- getGblEnv; return (tcg_mod env) }
  390. setModule :: Module -> TcRn a -> TcRn a
  391. setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
  392. getIsGHCi :: TcRn Bool
  393. getIsGHCi = do { mod <- getModule; return (mod == iNTERACTIVE) }
  394. getGHCiMonad :: TcRn Name
  395. getGHCiMonad = do { hsc <- getTopEnv; return (ic_monad $ hsc_IC hsc) }
  396. getInteractivePrintName :: TcRn Name
  397. getInteractivePrintName = do { hsc <- getTopEnv; return (ic_int_print $ hsc_IC hsc) }
  398. tcIsHsBoot :: TcRn Bool
  399. tcIsHsBoot = do { env <- getGblEnv; return (isHsBoot (tcg_src env)) }
  400. getGlobalRdrEnv :: TcRn GlobalRdrEnv
  401. getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
  402. getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
  403. getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
  404. getImports :: TcRn ImportAvails
  405. getImports = do { env <- getGblEnv; return (tcg_imports env) }
  406. getFixityEnv :: TcRn FixityEnv
  407. getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
  408. extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
  409. extendFixityEnv new_bit
  410. = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
  411. env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
  412. getRecFieldEnv :: TcRn RecFieldEnv
  413. getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
  414. getDeclaredDefaultTys :: TcRn (Maybe [Type])
  415. getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
  416. addDependentFiles :: [FilePath] -> TcRn ()
  417. addDependentFiles fs = do
  418. ref <- fmap tcg_dependent_files getGblEnv
  419. dep_files <- readTcRef ref
  420. writeTcRef ref (fs ++ dep_files)
  421. \end{code}
  422. %************************************************************************
  423. %* *
  424. Error management
  425. %* *
  426. %************************************************************************
  427. \begin{code}
  428. getSrcSpanM :: TcRn SrcSpan
  429. -- Avoid clash with Name.getSrcLoc
  430. getSrcSpanM = do { env <- getLclEnv; return (tcl_loc env) }
  431. setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
  432. setSrcSpan loc@(RealSrcSpan _) thing_inside
  433. = updLclEnv (\env -> env { tcl_loc = loc }) thing_inside
  434. -- Don't overwrite useful info with useless:
  435. setSrcSpan (UnhelpfulSpan _) thing_inside = thing_inside
  436. addLocM :: (a -> TcM b) -> Located a -> TcM b
  437. addLocM fn (L loc a) = setSrcSpan loc $ fn a
  438. wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
  439. wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
  440. wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
  441. wrapLocFstM fn (L loc a) =
  442. setSrcSpan loc $ do
  443. (b,c) <- fn a
  444. return (L loc b, c)
  445. wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
  446. wrapLocSndM fn (L loc a) =
  447. setSrcSpan loc $ do
  448. (b,c) <- fn a
  449. return (b, L loc c)
  450. \end{code}
  451. Reporting errors
  452. \begin{code}
  453. getErrsVar :: TcRn (TcRef Messages)
  454. getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
  455. setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
  456. setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
  457. addErr :: MsgDoc -> TcRn () -- Ignores the context stack
  458. addErr msg = do { loc <- getSrcSpanM; addErrAt loc msg }
  459. failWith :: MsgDoc -> TcRn a
  460. failWith msg = addErr msg >> failM
  461. addErrAt :: SrcSpan -> MsgDoc -> TcRn ()
  462. -- addErrAt is mainly (exclusively?) used by the renamer, where
  463. -- tidying is not an issue, but it's all lazy so the extra
  464. -- work doesn't matter
  465. addErrAt loc msg = do { ctxt <- getErrCtxt
  466. ; tidy_env <- tcInitTidyEnv
  467. ; err_info <- mkErrInfo tidy_env ctxt
  468. ; addLongErrAt loc msg err_info }
  469. addErrs :: [(SrcSpan,MsgDoc)] -> TcRn ()
  470. addErrs msgs = mapM_ add msgs
  471. where
  472. add (loc,msg) = addErrAt loc msg
  473. checkErr :: Bool -> MsgDoc -> TcRn ()
  474. -- Add the error if the bool is False
  475. checkErr ok msg = unless ok (addErr msg)
  476. warnIf :: Bool -> MsgDoc -> TcRn ()
  477. warnIf True msg = addWarn msg
  478. warnIf False _ = return ()
  479. addMessages :: Messages -> TcRn ()
  480. addMessages (m_warns, m_errs)
  481. = do { errs_var <- getErrsVar ;
  482. (warns, errs) <- readTcRef errs_var ;
  483. writeTcRef errs_var (warns `unionBags` m_warns,
  484. errs `unionBags` m_errs) }
  485. discardWarnings :: TcRn a -> TcRn a
  486. -- Ignore warnings inside the thing inside;
  487. -- used to ignore-unused-variable warnings inside derived code
  488. discardWarnings thing_inside
  489. = do { errs_var <- getErrsVar
  490. ; (old_warns, _) <- readTcRef errs_var ;
  491. ; result <- thing_inside
  492. -- Revert warnings to old_warns
  493. ; (_new_warns, new_errs) <- readTcRef errs_var
  494. ; writeTcRef errs_var (old_warns, new_errs)
  495. ; return result }
  496. \end{code}
  497. %************************************************************************
  498. %* *
  499. Shared error message stuff: renamer and typechecker
  500. %* *
  501. %************************************************************************
  502. \begin{code}
  503. mkLongErrAt :: SrcSpan -> MsgDoc -> MsgDoc -> TcRn ErrMsg
  504. mkLongErrAt loc msg extra
  505. = do { rdr_env <- getGlobalRdrEnv ;
  506. dflags <- getDynFlags ;
  507. return $ mkLongErrMsg dflags loc (mkPrintUnqualified dflags rdr_env) msg extra }
  508. addLongErrAt :: SrcSpan -> MsgDoc -> MsgDoc -> TcRn ()
  509. addLongErrAt loc msg extra = mkLongErrAt loc msg extra >>= reportError
  510. reportErrors :: [ErrMsg] -> TcM ()
  511. reportErrors = mapM_ reportError
  512. reportError :: ErrMsg -> TcRn ()
  513. reportError err
  514. = do { traceTc "Adding error:" (pprLocErrMsg err) ;
  515. errs_var <- getErrsVar ;
  516. (warns, errs) <- readTcRef errs_var ;
  517. writeTcRef errs_var (warns, errs `snocBag` err) }
  518. reportWarning :: ErrMsg -> TcRn ()
  519. reportWarning warn
  520. = do { traceTc "Adding warning:" (pprLocErrMsg warn) ;
  521. errs_var <- getErrsVar ;
  522. (warns, errs) <- readTcRef errs_var ;
  523. writeTcRef errs_var (warns `snocBag` warn, errs) }
  524. dumpDerivingInfo :: SDoc -> TcM ()
  525. dumpDerivingInfo doc
  526. = do { dflags <- getDynFlags
  527. ; when (dopt Opt_D_dump_deriv dflags) $ do
  528. { rdr_env <- getGlobalRdrEnv
  529. ; let unqual = mkPrintUnqualified dflags rdr_env
  530. ; liftIO (putMsgWith dflags unqual doc) } }
  531. \end{code}
  532. \begin{code}
  533. try_m :: TcRn r -> TcRn (Either IOEnvFailure r)
  534. -- Does try_m, with a debug-trace on failure
  535. try_m thing
  536. = do { mb_r <- tryM thing ;
  537. case mb_r of
  538. Left exn -> do { traceTc "tryTc/recoverM recovering from" $
  539. text (showException exn)
  540. ; return mb_r }
  541. Right _ -> return mb_r }
  542. -----------------------
  543. recoverM :: TcRn r -- Recovery action; do this if the main one fails
  544. -> TcRn r -- Main action: do this first
  545. -> TcRn r
  546. -- Errors in 'thing' are retained
  547. recoverM recover thing
  548. = do { mb_res <- try_m thing ;
  549. case mb_res of
  550. Left _ -> recover
  551. Right res -> return res }
  552. -----------------------
  553. mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
  554. -- Drop elements of the input that fail, so the result
  555. -- list can be shorter than the argument list
  556. mapAndRecoverM _ [] = return []
  557. mapAndRecoverM f (x:xs) = do { mb_r <- try_m (f x)
  558. ; rs <- mapAndRecoverM f xs
  559. ; return (case mb_r of
  560. Left _ -> rs
  561. Right r -> r:rs) }
  562. -----------------------
  563. tryTc :: TcRn a -> TcRn (Messages, Maybe a)
  564. -- (tryTc m) executes m, and returns
  565. -- Just r, if m succeeds (returning r)
  566. -- Nothing, if m fails
  567. -- It also returns all the errors and warnings accumulated by m
  568. -- It always succeeds (never raises an exception)
  569. tryTc m
  570. = do { errs_var <- newTcRef emptyMessages ;
  571. res <- try_m (setErrsVar errs_var m) ;
  572. msgs <- readTcRef errs_var ;
  573. return (msgs, case res of
  574. Left _ -> Nothing
  575. Right val -> Just val)
  576. -- The exception is always the IOEnv built-in
  577. -- in exception; see IOEnv.failM
  578. }
  579. -----------------------
  580. tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
  581. -- Run the thing, returning
  582. -- Just r, if m succceeds with no error messages
  583. -- Nothing, if m fails, or if it succeeds but has error messages
  584. -- Either way, the messages are returned; even in the Just case
  585. -- there might be warnings
  586. tryTcErrs thing
  587. = do { (msgs, res) <- tryTc thing
  588. ; dflags <- getDynFlags
  589. ; let errs_found = errorsFound dflags msgs
  590. ; return (msgs, case res of
  591. Nothing -> Nothing
  592. Just val | errs_found -> Nothing
  593. | otherwise -> Just val)
  594. }
  595. -----------------------
  596. tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
  597. -- Just like tryTcErrs, except that it ensures that the LIE
  598. -- for the thing is propagated only if there are no errors
  599. -- Hence it's restricted to the type-check monad
  600. tryTcLIE thing_inside
  601. = do { ((msgs, mb_res), lie) <- captureConstraints (tryTcErrs thing_inside) ;
  602. ; case mb_res of
  603. Nothing -> return (msgs, Nothing)
  604. Just val -> do { emitConstraints lie; return (msgs, Just val) }
  605. }
  606. -----------------------
  607. tryTcLIE_ :: TcM r -> TcM r -> TcM r
  608. -- (tryTcLIE_ r m) tries m;
  609. -- if m succeeds with no error messages, it's the answer
  610. -- otherwise tryTcLIE_ drops everything from m and tries r instead.
  611. tryTcLIE_ recover main
  612. = do { (msgs, mb_res) <- tryTcLIE main
  613. ; case mb_res of
  614. Just val -> do { addMessages msgs -- There might be warnings
  615. ; return val }
  616. Nothing -> recover -- Discard all msgs
  617. }
  618. -----------------------
  619. checkNoErrs :: TcM r -> TcM r
  620. -- (checkNoErrs m) succeeds iff m succeeds and generates no errors
  621. -- If m fails then (checkNoErrsTc m) fails.
  622. -- If m succeeds, it checks whether m generated any errors messages
  623. -- (it might have recovered internally)
  624. -- If so, it fails too.
  625. -- Regardless, any errors generated by m are propagated to the enclosing context.
  626. checkNoErrs main
  627. = do { (msgs, mb_res) <- tryTcLIE main
  628. ; addMessages msgs
  629. ; case mb_res of
  630. Nothing -> failM
  631. Just val -> return val
  632. }
  633. ifErrsM :: TcRn r -> TcRn r -> TcRn r
  634. -- ifErrsM bale_out normal
  635. -- does 'bale_out' if there are errors in errors collection
  636. -- otherwise does 'normal'
  637. ifErrsM bale_out normal
  638. = do { errs_var <- getErrsVar ;
  639. msgs <- readTcRef errs_var ;
  640. dflags <- getDynFlags ;
  641. if errorsFound dflags msgs then
  642. bale_out
  643. else
  644. normal }
  645. failIfErrsM :: TcRn ()
  646. -- Useful to avoid error cascades
  647. failIfErrsM = ifErrsM failM (return ())
  648. \end{code}
  649. %************************************************************************
  650. %* *
  651. Context management for the type checker
  652. %* *
  653. %************************************************************************
  654. \begin{code}
  655. getErrCtxt :: TcM [ErrCtxt]
  656. getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
  657. setErrCtxt :: [ErrCtxt] -> TcM a -> TcM a
  658. setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
  659. addErrCtxt :: MsgDoc -> TcM a -> TcM a
  660. addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
  661. addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, MsgDoc)) -> TcM a -> TcM a
  662. addErrCtxtM ctxt = updCtxt (\ ctxts -> (False, ctxt) : ctxts)
  663. addLandmarkErrCtxt :: MsgDoc -> TcM a -> TcM a
  664. addLandmarkErrCtxt msg = updCtxt (\ctxts -> (True, \env -> return (env,msg)) : ctxts)
  665. -- Helper function for the above
  666. updCtxt :: ([ErrCtxt] -> [ErrCtxt]) -> TcM a -> TcM a
  667. updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
  668. env { tcl_ctxt = upd ctxt })
  669. popErrCtxt :: TcM a -> TcM a
  670. popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
  671. getCtLoc :: CtOrigin -> TcM CtLoc
  672. getCtLoc origin
  673. = do { env <- getLclEnv
  674. ; return (CtLoc { ctl_origin = origin, ctl_env = env, ctl_depth = 0 }) }
  675. setCtLoc :: CtLoc -> TcM a -> TcM a
  676. -- Set the SrcSpan and error context from the CtLoc
  677. setCtLoc (CtLoc { ctl_env = lcl }) thing_inside
  678. = updLclEnv (\env -> env { tcl_loc = tcl_loc lcl
  679. , tcl_bndrs = tcl_bndrs lcl
  680. , tcl_ctxt = tcl_ctxt lcl })
  681. thing_inside
  682. \end{code}
  683. %************************************************************************
  684. %* *
  685. Error message generation (type checker)
  686. %* *
  687. %************************************************************************
  688. The addErrTc functions add an error message, but do not cause failure.
  689. The 'M' variants pass a TidyEnv that has already been used to
  690. tidy up the message; we then use it to tidy the context messages
  691. \begin{code}
  692. addErrTc :: MsgDoc -> TcM ()
  693. addErrTc err_msg = do { env0 <- tcInitTidyEnv
  694. ; addErrTcM (env0, err_msg) }
  695. addErrsTc :: [MsgDoc] -> TcM ()
  696. addErrsTc err_msgs = mapM_ addErrTc err_msgs
  697. addErrTcM :: (TidyEnv, MsgDoc) -> TcM ()
  698. addErrTcM (tidy_env, err_msg)
  699. = do { ctxt <- getErrCtxt ;
  700. loc <- getSrcSpanM ;
  701. add_err_tcm tidy_env err_msg loc ctxt }
  702. -- Return the error message, instead of reporting it straight away
  703. mkErrTcM :: (TidyEnv, MsgDoc) -> TcM ErrMsg
  704. mkErrTcM (tidy_env, err_msg)
  705. = do { ctxt <- getErrCtxt ;
  706. loc <- getSrcSpanM ;
  707. err_info <- mkErrInfo tidy_env ctxt ;
  708. mkLongErrAt loc err_msg err_info }
  709. \end{code}
  710. The failWith functions add an error message and cause failure
  711. \begin{code}
  712. failWithTc :: MsgDoc -> TcM a -- Add an error message and fail
  713. failWithTc err_msg
  714. = addErrTc err_msg >> failM
  715. failWithTcM :: (TidyEnv, MsgDoc) -> TcM a -- Add an error message and fail
  716. failWithTcM local_and_msg
  717. = addErrTcM local_and_msg >> failM
  718. checkTc :: Bool -> MsgDoc -> TcM () -- Check that the boolean is true
  719. checkTc True _ = return ()
  720. checkTc False err = failWithTc err
  721. \end{code}
  722. Warnings have no 'M' variant, nor failure
  723. \begin{code}
  724. warnTc :: Bool -> MsgDoc -> TcM ()
  725. warnTc warn_if_true warn_msg
  726. | warn_if_true = addWarnTc warn_msg
  727. | otherwise = return ()
  728. addWarnTc :: MsgDoc -> TcM ()
  729. addWarnTc msg = do { env0 <- tcInitTidyEnv
  730. ; addWarnTcM (env0, msg) }
  731. addWarnTcM :: (TidyEnv, MsgDoc) -> TcM ()
  732. addWarnTcM (env0, msg)
  733. = do { ctxt <- getErrCtxt ;
  734. err_info <- mkErrInfo env0 ctxt ;
  735. add_warn msg err_info }
  736. addWarn :: MsgDoc -> TcRn ()
  737. addWarn msg = add_warn msg empty
  738. addWarnAt :: SrcSpan -> MsgDoc -> TcRn ()
  739. addWarnAt loc msg = add_warn_at loc msg empty
  740. add_warn :: MsgDoc -> MsgDoc -> TcRn ()
  741. add_warn msg extra_info
  742. = do { loc <- getSrcSpanM
  743. ; add_warn_at loc msg extra_info }
  744. add_warn_at :: SrcSpan -> MsgDoc -> MsgDoc -> TcRn ()
  745. add_warn_at loc msg extra_info
  746. = do { rdr_env <- getGlobalRdrEnv ;
  747. dflags <- getDynFlags ;
  748. let { warn = mkLongWarnMsg dflags loc (mkPrintUnqualified dflags rdr_env)
  749. msg extra_info } ;
  750. reportWarning warn }
  751. tcInitTidyEnv :: TcM TidyEnv
  752. tcInitTidyEnv
  753. = do { lcl_env <- getLclEnv
  754. ; return (tcl_tidy lcl_env) }
  755. \end{code}
  756. -----------------------------------
  757. Other helper functions
  758. \begin{code}
  759. add_err_tcm :: TidyEnv -> MsgDoc -> SrcSpan
  760. -> [ErrCtxt]
  761. -> TcM ()
  762. add_err_tcm tidy_env err_msg loc ctxt
  763. = do { err_info <- mkErrInfo tidy_env ctxt ;
  764. addLongErrAt loc err_msg err_info }
  765. mkErrInfo :: TidyEnv -> [ErrCtxt] -> TcM SDoc
  766. -- Tidy the error info, trimming excessive contexts
  767. mkErrInfo env ctxts
  768. -- | opt_PprStyle_Debug -- In -dppr-debug style the output
  769. -- = return empty -- just becomes too voluminous
  770. | otherwise
  771. = go 0 env ctxts
  772. where
  773. go :: Int -> TidyEnv -> [ErrCtxt] -> TcM SDoc
  774. go _ _ [] = return empty
  775. go n env ((is_landmark, ctxt) : ctxts)
  776. | is_landmark || n < mAX_CONTEXTS -- Too verbose || opt_PprStyle_Debug
  777. = do { (env', msg) <- ctxt env
  778. ; let n' = if is_landmark then n else n+1
  779. ; rest <- go n' env' ctxts
  780. ; return (msg $$ rest) }
  781. | otherwise
  782. = go n env ctxts
  783. mAX_CONTEXTS :: Int -- No more than this number of non-landmark contexts
  784. mAX_CONTEXTS = 3
  785. \end{code}
  786. debugTc is useful for monadic debugging code
  787. \begin{code}
  788. debugTc :: TcM () -> TcM ()
  789. debugTc thing
  790. | debugIsOn = thing
  791. | otherwise = return ()
  792. \end{code}
  793. %************************************************************************
  794. %* *
  795. Type constraints
  796. %* *
  797. %************************************************************************
  798. \begin{code}
  799. newTcEvBinds :: TcM EvBindsVar
  800. newTcEvBinds = do { ref <- newTcRef emptyEvBindMap
  801. ; uniq <- newUnique
  802. ; return (EvBindsVar ref uniq) }
  803. addTcEvBind :: EvBindsVar -> EvVar -> EvTerm -> TcM ()
  804. -- Add a binding to the TcEvBinds by side effect
  805. addTcEvBind (EvBindsVar ev_ref _) var t
  806. = do { bnds <- readTcRef ev_ref
  807. ; writeTcRef ev_ref (extendEvBinds bnds var t) }
  808. getTcEvBinds :: EvBindsVar -> TcM (Bag EvBind)
  809. getTcEvBinds (EvBindsVar ev_ref _)
  810. = do { bnds <- readTcRef ev_ref
  811. ; return (evBindMapBinds bnds) }
  812. chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
  813. chooseUniqueOccTc fn =
  814. do { env <- getGblEnv
  815. ; let dfun_n_var = tcg_dfun_n env
  816. ; set <- readTcRef dfun_n_var
  817. ; let occ = fn set
  818. ; writeTcRef dfun_n_var (extendOccSet set occ)
  819. ; return occ }
  820. getConstraintVar :: TcM (TcRef WantedConstraints)
  821. getConstraintVar = do { env <- getLclEnv; return (tcl_lie env) }
  822. setConstraintVar :: TcRef WantedConstraints -> TcM a -> TcM a
  823. setConstraintVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
  824. emitConstraints :: WantedConstraints -> TcM ()
  825. emitConstraints ct
  826. = do { lie_var <- getConstraintVar ;
  827. updTcRef lie_var (`andWC` ct) }
  828. emitFlat :: Ct -> TcM ()
  829. emitFlat ct
  830. = do { lie_var <- getConstraintVar ;
  831. updTcRef lie_var (`addFlats` unitBag ct) }
  832. emitFlats :: Cts -> TcM ()
  833. emitFlats cts
  834. = do { lie_var <- getConstraintVar ;
  835. updTcRef lie_var (`addFlats` cts) }
  836. emitImplication :: Implication -> TcM ()
  837. emitImplication ct
  838. = do { lie_var <- getConstraintVar ;
  839. updTcRef lie_var (`addImplics` unitBag ct) }
  840. emitImplications :: Bag Implication -> TcM ()
  841. emitImplications ct
  842. = do { lie_var <- getConstraintVar ;
  843. updTcRef lie_var (`addImplics` ct) }
  844. emitInsoluble :: Ct -> TcM ()
  845. emitInsoluble ct
  846. = do { lie_var <- getConstraintVar ;
  847. updTcRef lie_var (`addInsols` unitBag ct) ;
  848. v <- readTcRef lie_var ;
  849. traceTc "emitInsoluble" (ppr v) }
  850. captureConstraints :: TcM a -> TcM (a, WantedConstraints)
  851. -- (captureConstraints m) runs m, and returns the type constraints it generates
  852. captureConstraints thing_inside
  853. = do { lie_var <- newTcRef emptyWC ;
  854. res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
  855. thing_inside ;
  856. lie <- readTcRef lie_var ;
  857. return (res, lie) }
  858. captureUntouchables :: TcM a -> TcM (a, Untouchables)
  859. captureUntouchables thing_inside
  860. = do { env <- getLclEnv
  861. ; let untch' = pushUntouchables (tcl_untch env)
  862. ; res <- setLclEnv (env { tcl_untch = untch' })
  863. thing_inside
  864. ; return (res, untch') }
  865. getUntouchables :: TcM Untouchables
  866. getUntouchables = do { env <- getLclEnv
  867. ; return (tcl_untch env) }
  868. setUntouchables :: Untouchables -> TcM a -> TcM a
  869. setUntouchables untch thing_inside
  870. = updLclEnv (\env -> env { tcl_untch = untch }) thing_inside
  871. isTouchableTcM :: TcTyVar -> TcM Bool
  872. isTouchableTcM tv
  873. -- Kind variables are always touchable
  874. | isSuperKind (tyVarKind tv)
  875. = return False
  876. | otherwise
  877. = do { env <- getLclEnv
  878. ; return (isTouchableMetaTyVar (tcl_untch env) tv) }
  879. getLclTypeEnv :: TcM TcTypeEnv
  880. getLclTypeEnv = do { env <- getLclEnv; return (tcl_env env) }
  881. setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
  882. -- Set the local type envt, but do *not* disturb other fields,
  883. -- notably the lie_var
  884. setLclTypeEnv lcl_env thing_inside
  885. = updLclEnv upd thing_inside
  886. where
  887. upd env = env { tcl_env = tcl_env lcl_env,
  888. tcl_tyvars = tcl_tyvars lcl_env }
  889. traceTcConstraints :: String -> TcM ()
  890. traceTcConstraints msg
  891. = do { lie_var <- getConstraintVar
  892. ; lie <- readTcRef lie_var
  893. ; traceTc (msg ++ "LIE:") (ppr lie)
  894. }
  895. \end{code}
  896. %************************************************************************
  897. %* *
  898. Template Haskell context
  899. %* *
  900. %************************************************************************
  901. \begin{code}
  902. recordThUse :: TcM ()
  903. recordThUse = do { env <- getGblEnv; writeTcRef (tcg_th_used env) True }
  904. recordThSpliceUse :: TcM ()
  905. recordThSpliceUse = do { env <- getGblEnv; writeTcRef (tcg_th_splice_used env) True }
  906. keepAliveTc :: Id -> TcM () -- Record the name in the keep-alive set
  907. keepAliveTc id
  908. | isLocalId id = do { env <- getGblEnv;
  909. ; updTcRef (tcg_keep env) (`addOneToNameSet` idName id) }
  910. | otherwise = return ()
  911. keepAliveSetTc :: NameSet -> TcM () -- Record the name in the keep-alive set
  912. keepAliveSetTc ns = do { env <- getGblEnv;
  913. ; updTcRef (tcg_keep env) (`unionNameSets` ns) }
  914. getStage :: TcM ThStage
  915. getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
  916. setStage :: ThStage -> TcM a -> TcM a
  917. setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
  918. \end{code}
  919. %************************************************************************
  920. %* *
  921. Safe Haskell context
  922. %* *
  923. %************************************************************************
  924. \begin{code}
  925. -- | Mark that safe inference has failed
  926. recordUnsafeInfer :: TcM ()
  927. recordUnsafeInfer = getGblEnv >>= \env -> writeTcRef (tcg_safeInfer env) False
  928. -- | Figure out the final correct safe haskell mode
  929. finalSafeMode :: DynFlags -> TcGblEnv -> IO SafeHaskellMode
  930. finalSafeMode dflags tcg_env = do
  931. safeInf <- readIORef (tcg_safeInfer tcg_env)
  932. return $ if safeInferOn dflags && not safeInf
  933. then Sf_None
  934. else safeHaskell dflags
  935. \end{code}
  936. %************************************************************************
  937. %* *
  938. Stuff for the renamer's local env
  939. %* *
  940. %************************************************************************
  941. \begin{code}
  942. getLocalRdrEnv :: RnM LocalRdrEnv
  943. getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
  944. setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
  945. setLocalRdrEnv rdr_env thing_inside
  946. = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
  947. \end{code}
  948. %************************************************************************
  949. %* *
  950. Stuff for interface decls
  951. %* *
  952. %************************************************************************
  953. \begin{code}
  954. mkIfLclEnv :: Module -> SDoc -> IfLclEnv
  955. mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
  956. if_loc = loc,
  957. if_tv_env = emptyUFM,
  958. if_id_env = emptyUFM }
  959. initIfaceTcRn :: IfG a -> TcRn a
  960. initIfaceTcRn thing_inside
  961. = do { tcg_env <- getGblEnv
  962. ; let { if_env = IfGblEnv { if_rec_types = Just (tcg_mod tcg_env, get_type_env) }
  963. ; get_type_env = readTcRef (tcg_type_env_var tcg_env) }
  964. ; setEnvs (if_env, ()) thing_inside }
  965. initIfaceExtCore :: IfL a -> TcRn a
  966. initIfaceExtCore thing_inside
  967. = do { tcg_env <- getGblEnv
  968. ; let { mod = tcg_mod tcg_env
  969. ; doc = ptext (sLit "External Core file for") <+> quotes (ppr mod)
  970. ; if_env = IfGblEnv {
  971. if_rec_types = Just (mod, return (tcg_type_env tcg_env)) }
  972. ; if_lenv = mkIfLclEnv mod doc
  973. }
  974. ; setEnvs (if_env, if_lenv) thing_inside }
  975. initIfaceCheck :: HscEnv -> IfG a -> IO a
  976. -- Used when checking the up-to-date-ness of the old Iface
  977. -- Initialise the environment with no useful info at all
  978. initIfaceCheck hsc_env do_this
  979. = do let rec_types = case hsc_type_env_var hsc_env of
  980. Just (mod,var) -> Just (mod, readTcRef var)
  981. Nothing -> Nothing
  982. gbl_env = IfGblEnv { if_rec_types = rec_types }
  983. initTcRnIf 'i' hsc_env gbl_env () do_this
  984. initIfaceTc :: ModIface
  985. -> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
  986. -- Used when type-checking checking an up-to-date interface file
  987. -- No type envt from the current module, but we do know the module dependencies
  988. initIfaceTc iface do_this
  989. = do { tc_env_var <- newTcRef emptyTypeEnv
  990. ; let { gbl_env = IfGblEnv { if_rec_types = Just (mod, readTcRef tc_env_var) } ;
  991. ; if_lenv = mkIfLclEnv mod doc
  992. }
  993. ; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
  994. }
  995. where
  996. mod = mi_module iface
  997. doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
  998. initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
  999. initIfaceLcl mod loc_doc thing_inside
  1000. = setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
  1001. getIfModule :: IfL Module
  1002. getIfModule = do { env <- getLclEnv; return (if_mod env) }
  1003. --------------------
  1004. failIfM :: MsgDoc -> IfL a
  1005. -- The Iface monad doesn't have a place to accumulate errors, so we
  1006. -- just fall over fast if one happens; it "shouldnt happen".
  1007. -- We use IfL here so that we can get context info out of the local env
  1008. failIfM msg
  1009. = do { env <- getLclEnv
  1010. ; let full_msg = (if_loc env <> colon) $$ nest 2 msg
  1011. ; dflags <- getDynFlags
  1012. ; liftIO (log_action dflags dflags SevFatal noSrcSpan (defaultErrStyle dflags) full_msg)
  1013. ; failM }
  1014. --------------------
  1015. forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
  1016. -- Run thing_inside in an interleaved thread.
  1017. -- It shares everything with the parent thread, so this is DANGEROUS.
  1018. --
  1019. -- It returns Nothing if the computation fails
  1020. --
  1021. -- It's used for lazily type-checking interface
  1022. -- signatures, which is pretty benign
  1023. forkM_maybe doc thing_inside
  1024. = do { unsafeInterleaveM $
  1025. do { traceIf (text "Starting fork {" <+> doc)
  1026. ; mb_res <- tryM $
  1027. updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
  1028. thing_inside
  1029. ; case mb_res of
  1030. Right r -> do { traceIf (text "} ending fork" <+> doc)
  1031. ; return (Just r) }
  1032. Left exn -> do {
  1033. -- Bleat about errors in the forked thread, if -ddump-if-trace is on
  1034. -- Otherwise we silently discard errors. Errors can legitimately
  1035. -- happen when compiling interface signatures (see tcInterfaceSigs)
  1036. ifDOptM Opt_D_dump_if_trace $ do
  1037. dflags <- getDynFlags
  1038. let msg = hang (text "forkM failed:" <+> doc)
  1039. 2 (text (show exn))
  1040. liftIO $ log_action dflags dflags SevFatal noSrcSpan (defaultErrStyle dflags) msg
  1041. ; traceIf (text "} ending fork (badly)" <+> doc)
  1042. ; return Nothing }
  1043. }}
  1044. forkM :: SDoc -> IfL a -> IfL a
  1045. forkM doc thing_inside
  1046. = do { mb_res <- forkM_maybe doc thing_inside
  1047. ; return (case mb_res of
  1048. Nothing -> pgmError "Cannot continue after interface file error"
  1049. -- pprPanic "forkM" doc
  1050. Just r -> r) }
  1051. \end{code}