PageRenderTime 67ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/ghc-7.4.1/compiler/typecheck/TcRnMonad.lhs

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