PageRenderTime 61ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/ghc-7.4.1/compiler/main/HscMain.hs

#
Haskell | 1679 lines | 1026 code | 245 blank | 408 comment | 21 complexity | 907f4b0f6bca6692b1c2c4ff73b45d48 MD5 | raw file
Possible License(s): LGPL-3.0, BSD-3-Clause, BSD-2-Clause
  1. -------------------------------------------------------------------------------
  2. --
  3. -- | Main API for compiling plain Haskell source code.
  4. --
  5. -- This module implements compilation of a Haskell source. It is
  6. -- /not/ concerned with preprocessing of source files; this is handled
  7. -- in "DriverPipeline".
  8. --
  9. -- There are various entry points depending on what mode we're in:
  10. -- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and
  11. -- "interactive" mode (GHCi). There are also entry points for
  12. -- individual passes: parsing, typechecking/renaming, desugaring, and
  13. -- simplification.
  14. --
  15. -- All the functions here take an 'HscEnv' as a parameter, but none of
  16. -- them return a new one: 'HscEnv' is treated as an immutable value
  17. -- from here on in (although it has mutable components, for the
  18. -- caches).
  19. --
  20. -- Warning messages are dealt with consistently throughout this API:
  21. -- during compilation warnings are collected, and before any function
  22. -- in @HscMain@ returns, the warnings are either printed, or turned
  23. -- into a real compialtion error if the @-Werror@ flag is enabled.
  24. --
  25. -- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
  26. --
  27. -------------------------------------------------------------------------------
  28. module HscMain
  29. (
  30. -- * Making an HscEnv
  31. newHscEnv
  32. -- * Compiling complete source files
  33. , Compiler
  34. , HscStatus' (..)
  35. , InteractiveStatus, HscStatus
  36. , hscCompileOneShot
  37. , hscCompileBatch
  38. , hscCompileNothing
  39. , hscCompileInteractive
  40. , hscCompileCmmFile
  41. , hscCompileCore
  42. -- * Running passes separately
  43. , hscParse
  44. , hscTypecheckRename
  45. , hscDesugar
  46. , makeSimpleIface
  47. , makeSimpleDetails
  48. , hscSimplify -- ToDo, shouldn't really export this
  49. -- ** Backends
  50. , hscOneShotBackendOnly
  51. , hscBatchBackendOnly
  52. , hscNothingBackendOnly
  53. , hscInteractiveBackendOnly
  54. -- * Support for interactive evaluation
  55. , hscParseIdentifier
  56. , hscTcRcLookupName
  57. , hscTcRnGetInfo
  58. , hscCheckSafe
  59. #ifdef GHCI
  60. , hscGetModuleInterface
  61. , hscRnImportDecls
  62. , hscTcRnLookupRdrName
  63. , hscStmt, hscStmtWithLocation
  64. , hscDecls, hscDeclsWithLocation
  65. , hscTcExpr, hscImport, hscKcType
  66. , hscCompileCoreExpr
  67. #endif
  68. ) where
  69. #ifdef GHCI
  70. import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
  71. import Linker
  72. import CoreTidy ( tidyExpr )
  73. import Type ( Type )
  74. import PrelNames
  75. import {- Kind parts of -} Type ( Kind )
  76. import CoreLint ( lintUnfolding )
  77. import DsMeta ( templateHaskellNames )
  78. import VarSet
  79. import VarEnv ( emptyTidyEnv )
  80. import Panic
  81. #endif
  82. import Id
  83. import Module
  84. import Packages
  85. import RdrName
  86. import HsSyn
  87. import CoreSyn
  88. import StringBuffer
  89. import Parser
  90. import Lexer hiding (getDynFlags)
  91. import SrcLoc
  92. import TcRnDriver
  93. import TcIface ( typecheckIface )
  94. import TcRnMonad
  95. import IfaceEnv ( initNameCache )
  96. import LoadIface ( ifaceStats, initExternalPackageState )
  97. import PrelInfo
  98. import MkIface
  99. import Desugar
  100. import SimplCore
  101. import TidyPgm
  102. import CorePrep
  103. import CoreToStg ( coreToStg )
  104. import qualified StgCmm ( codeGen )
  105. import StgSyn
  106. import CostCentre
  107. import ProfInit
  108. import TyCon
  109. import Name
  110. import SimplStg ( stg2stg )
  111. import CodeGen ( codeGen )
  112. import OldCmm as Old ( CmmGroup )
  113. import PprCmm ( pprCmms )
  114. import CmmParse ( parseCmmFile )
  115. import CmmBuildInfoTables
  116. import CmmPipeline
  117. import CmmInfo
  118. import OptimizationFuel ( initOptFuelState )
  119. import CmmCvt
  120. import CodeOutput
  121. import NameEnv ( emptyNameEnv )
  122. import NameSet ( emptyNameSet )
  123. import InstEnv
  124. import FamInstEnv
  125. import Fingerprint ( Fingerprint )
  126. import DynFlags
  127. import ErrUtils
  128. import UniqSupply ( mkSplitUniqSupply )
  129. import Outputable
  130. import HscStats ( ppSourceStats )
  131. import HscTypes
  132. import MkExternalCore ( emitExternalCore )
  133. import FastString
  134. import UniqFM ( emptyUFM )
  135. import UniqSupply ( initUs_ )
  136. import Bag
  137. import Exception
  138. import Data.List
  139. import Control.Monad
  140. import Data.Maybe
  141. import Data.IORef
  142. import System.FilePath as FilePath
  143. import System.Directory
  144. #include "HsVersions.h"
  145. {- **********************************************************************
  146. %* *
  147. Initialisation
  148. %* *
  149. %********************************************************************* -}
  150. newHscEnv :: DynFlags -> IO HscEnv
  151. newHscEnv dflags = do
  152. eps_var <- newIORef initExternalPackageState
  153. us <- mkSplitUniqSupply 'r'
  154. nc_var <- newIORef (initNameCache us knownKeyNames)
  155. fc_var <- newIORef emptyUFM
  156. mlc_var <- newIORef emptyModuleEnv
  157. optFuel <- initOptFuelState
  158. safe_var <- newIORef True
  159. return HscEnv { hsc_dflags = dflags,
  160. hsc_targets = [],
  161. hsc_mod_graph = [],
  162. hsc_IC = emptyInteractiveContext,
  163. hsc_HPT = emptyHomePackageTable,
  164. hsc_EPS = eps_var,
  165. hsc_NC = nc_var,
  166. hsc_FC = fc_var,
  167. hsc_MLC = mlc_var,
  168. hsc_OptFuel = optFuel,
  169. hsc_type_env_var = Nothing,
  170. hsc_safeInf = safe_var }
  171. knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
  172. knownKeyNames = -- where templateHaskellNames are defined
  173. map getName wiredInThings
  174. ++ basicKnownKeyNames
  175. #ifdef GHCI
  176. ++ templateHaskellNames
  177. #endif
  178. -- -----------------------------------------------------------------------------
  179. -- The Hsc monad: Passing an enviornment and warning state
  180. newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))
  181. instance Monad Hsc where
  182. return a = Hsc $ \_ w -> return (a, w)
  183. Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
  184. case k a of
  185. Hsc k' -> k' e w1
  186. instance MonadIO Hsc where
  187. liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)
  188. runHsc :: HscEnv -> Hsc a -> IO a
  189. runHsc hsc_env (Hsc hsc) = do
  190. (a, w) <- hsc hsc_env emptyBag
  191. printOrThrowWarnings (hsc_dflags hsc_env) w
  192. return a
  193. getWarnings :: Hsc WarningMessages
  194. getWarnings = Hsc $ \_ w -> return (w, w)
  195. clearWarnings :: Hsc ()
  196. clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
  197. logWarnings :: WarningMessages -> Hsc ()
  198. logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
  199. getHscEnv :: Hsc HscEnv
  200. getHscEnv = Hsc $ \e w -> return (e, w)
  201. getDynFlags :: Hsc DynFlags
  202. getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
  203. handleWarnings :: Hsc ()
  204. handleWarnings = do
  205. dflags <- getDynFlags
  206. w <- getWarnings
  207. liftIO $ printOrThrowWarnings dflags w
  208. clearWarnings
  209. -- | log warning in the monad, and if there are errors then
  210. -- throw a SourceError exception.
  211. logWarningsReportErrors :: Messages -> Hsc ()
  212. logWarningsReportErrors (warns,errs) = do
  213. logWarnings warns
  214. when (not $ isEmptyBag errs) $ throwErrors errs
  215. -- | Throw some errors.
  216. throwErrors :: ErrorMessages -> Hsc a
  217. throwErrors = liftIO . throwIO . mkSrcErr
  218. -- | Deal with errors and warnings returned by a compilation step
  219. --
  220. -- In order to reduce dependencies to other parts of the compiler, functions
  221. -- outside the "main" parts of GHC return warnings and errors as a parameter
  222. -- and signal success via by wrapping the result in a 'Maybe' type. This
  223. -- function logs the returned warnings and propagates errors as exceptions
  224. -- (of type 'SourceError').
  225. --
  226. -- This function assumes the following invariants:
  227. --
  228. -- 1. If the second result indicates success (is of the form 'Just x'),
  229. -- there must be no error messages in the first result.
  230. --
  231. -- 2. If there are no error messages, but the second result indicates failure
  232. -- there should be warnings in the first result. That is, if the action
  233. -- failed, it must have been due to the warnings (i.e., @-Werror@).
  234. ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
  235. ioMsgMaybe ioA = do
  236. ((warns,errs), mb_r) <- liftIO $ ioA
  237. logWarnings warns
  238. case mb_r of
  239. Nothing -> throwErrors errs
  240. Just r -> ASSERT( isEmptyBag errs ) return r
  241. -- | like ioMsgMaybe, except that we ignore error messages and return
  242. -- 'Nothing' instead.
  243. ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a)
  244. ioMsgMaybe' ioA = do
  245. ((warns,_errs), mb_r) <- liftIO $ ioA
  246. logWarnings warns
  247. return mb_r
  248. -- -----------------------------------------------------------------------------
  249. -- | Lookup things in the compiler's environment
  250. #ifdef GHCI
  251. hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
  252. hscTcRnLookupRdrName hsc_env rdr_name =
  253. runHsc hsc_env $ ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
  254. #endif
  255. hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
  256. hscTcRcLookupName hsc_env name =
  257. runHsc hsc_env $ ioMsgMaybe' $ tcRnLookupName hsc_env name
  258. -- ignore errors: the only error we're likely to get is
  259. -- "name not found", and the Maybe in the return type
  260. -- is used to indicate that.
  261. hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [Instance]))
  262. hscTcRnGetInfo hsc_env name =
  263. runHsc hsc_env $ ioMsgMaybe' $ tcRnGetInfo hsc_env name
  264. #ifdef GHCI
  265. hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
  266. hscGetModuleInterface hsc_env mod =
  267. runHsc hsc_env $ ioMsgMaybe $ getModuleInterface hsc_env mod
  268. -- -----------------------------------------------------------------------------
  269. -- | Rename some import declarations
  270. hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv
  271. hscRnImportDecls hsc_env import_decls =
  272. runHsc hsc_env $ ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
  273. #endif
  274. -- -----------------------------------------------------------------------------
  275. -- | parse a file, returning the abstract syntax
  276. hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
  277. hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary
  278. -- internal version, that doesn't fail due to -Werror
  279. hscParse' :: ModSummary -> Hsc HsParsedModule
  280. hscParse' mod_summary = do
  281. dflags <- getDynFlags
  282. let src_filename = ms_hspp_file mod_summary
  283. maybe_src_buf = ms_hspp_buf mod_summary
  284. -------------------------- Parser ----------------
  285. liftIO $ showPass dflags "Parser"
  286. {-# SCC "Parser" #-} do
  287. -- sometimes we already have the buffer in memory, perhaps
  288. -- because we needed to parse the imports out of it, or get the
  289. -- module name.
  290. buf <- case maybe_src_buf of
  291. Just b -> return b
  292. Nothing -> liftIO $ hGetStringBuffer src_filename
  293. let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
  294. case unP parseModule (mkPState dflags buf loc) of
  295. PFailed span err ->
  296. liftIO $ throwOneError (mkPlainErrMsg span err)
  297. POk pst rdr_module -> do
  298. logWarningsReportErrors (getMessages pst)
  299. liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $
  300. ppr rdr_module
  301. liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $
  302. ppSourceStats False rdr_module
  303. -- To get the list of extra source files, we take the list
  304. -- that the parser gave us,
  305. -- - eliminate files beginning with '<'. gcc likes to use
  306. -- pseudo-filenames like "<built-in>" and "<command-line>"
  307. -- - normalise them (elimiante differences between ./f and f)
  308. -- - filter out the preprocessed source file
  309. -- - filter out anything beginning with tmpdir
  310. -- - remove duplicates
  311. -- - filter out the .hs/.lhs source filename if we have one
  312. --
  313. let n_hspp = FilePath.normalise src_filename
  314. srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`))
  315. $ filter (not . (== n_hspp))
  316. $ map FilePath.normalise
  317. $ filter (not . (== '<') . head)
  318. $ map unpackFS
  319. $ srcfiles pst
  320. srcs1 = case ml_hs_file (ms_location mod_summary) of
  321. Just f -> filter (/= FilePath.normalise f) srcs0
  322. Nothing -> srcs0
  323. -- sometimes we see source files from earlier
  324. -- preprocessing stages that cannot be found, so just
  325. -- filter them out:
  326. srcs2 <- liftIO $ filterM doesFileExist srcs1
  327. return HsParsedModule {
  328. hpm_module = rdr_module,
  329. hpm_src_files = srcs2
  330. }
  331. -- XXX: should this really be a Maybe X? Check under which circumstances this
  332. -- can become a Nothing and decide whether this should instead throw an
  333. -- exception/signal an error.
  334. type RenamedStuff =
  335. (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
  336. Maybe LHsDocString))
  337. -- | Rename and typecheck a module, additionally returning the renamed syntax
  338. hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
  339. -> IO (TcGblEnv, RenamedStuff)
  340. hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do
  341. tc_result <- {-# SCC "Typecheck-Rename" #-}
  342. ioMsgMaybe $
  343. tcRnModule hsc_env (ms_hsc_src mod_summary)
  344. True rdr_module
  345. -- This 'do' is in the Maybe monad!
  346. let rn_info = do decl <- tcg_rn_decls tc_result
  347. let imports = tcg_rn_imports tc_result
  348. exports = tcg_rn_exports tc_result
  349. doc_hdr = tcg_doc_hdr tc_result
  350. return (decl,imports,exports,doc_hdr)
  351. return (tc_result, rn_info)
  352. -- | Convert a typechecked module to Core
  353. hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
  354. hscDesugar hsc_env mod_summary tc_result =
  355. runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
  356. hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
  357. hscDesugar' mod_location tc_result = do
  358. hsc_env <- getHscEnv
  359. r <- ioMsgMaybe $
  360. {-# SCC "deSugar" #-}
  361. deSugar hsc_env mod_location tc_result
  362. -- always check -Werror after desugaring, this is the last opportunity for
  363. -- warnings to arise before the backend.
  364. handleWarnings
  365. return r
  366. -- | Make a 'ModIface' from the results of typechecking. Used when
  367. -- not optimising, and the interface doesn't need to contain any
  368. -- unfoldings or other cross-module optimisation info.
  369. -- ToDo: the old interface is only needed to get the version numbers,
  370. -- we should use fingerprint versions instead.
  371. makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
  372. -> IO (ModIface,Bool)
  373. makeSimpleIface hsc_env maybe_old_iface tc_result details =
  374. runHsc hsc_env $ ioMsgMaybe $
  375. mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
  376. -- | Make a 'ModDetails' from the results of typechecking. Used when
  377. -- typechecking only, as opposed to full compilation.
  378. makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
  379. makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
  380. {- **********************************************************************
  381. %* *
  382. The main compiler pipeline
  383. %* *
  384. %********************************************************************* -}
  385. {-
  386. --------------------------------
  387. The compilation proper
  388. --------------------------------
  389. It's the task of the compilation proper to compile Haskell, hs-boot and core
  390. files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all
  391. (the module is still parsed and type-checked. This feature is mostly used by
  392. IDE's and the likes). Compilation can happen in either 'one-shot', 'batch',
  393. 'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch'
  394. mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
  395. targets byte-code.
  396. The modes are kept separate because of their different types and meanings:
  397. * In 'one-shot' mode, we're only compiling a single file and can therefore
  398. discard the new ModIface and ModDetails. This is also the reason it only
  399. targets hard-code; compiling to byte-code or nothing doesn't make sense when
  400. we discard the result.
  401. * 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
  402. and ModDetails. 'Batch' mode doesn't target byte-code since that require us to
  403. return the newly compiled byte-code.
  404. * 'Nothing' mode has exactly the same type as 'batch' mode but they're still
  405. kept separate. This is because compiling to nothing is fairly special: We
  406. don't output any interface files, we don't run the simplifier and we don't
  407. generate any code.
  408. * 'Interactive' mode is similar to 'batch' mode except that we return the
  409. compiled byte-code together with the ModIface and ModDetails.
  410. Trying to compile a hs-boot file to byte-code will result in a run-time error.
  411. This is the only thing that isn't caught by the type-system.
  412. -}
  413. -- | Status of a compilation to hard-code or nothing.
  414. data HscStatus' a
  415. = HscNoRecomp
  416. | HscRecomp
  417. (Maybe FilePath) -- Has stub files. This is a hack. We can't compile
  418. -- C files here since it's done in DriverPipeline.
  419. -- For now we just return True if we want the caller
  420. -- to compile them for us.
  421. a
  422. -- This is a bit ugly. Since we use a typeclass below and would like to avoid
  423. -- functional dependencies, we have to parameterise the typeclass over the
  424. -- result type. Therefore we need to artificially distinguish some types. We do
  425. -- this by adding type tags which will simply be ignored by the caller.
  426. type HscStatus = HscStatus' ()
  427. type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
  428. -- INVARIANT: result is @Nothing@ <=> input was a boot file
  429. type OneShotResult = HscStatus
  430. type BatchResult = (HscStatus, ModIface, ModDetails)
  431. type NothingResult = (HscStatus, ModIface, ModDetails)
  432. type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
  433. -- ToDo: The old interface and module index are only using in 'batch' and
  434. -- 'interactive' mode. They should be removed from 'oneshot' mode.
  435. type Compiler result = HscEnv
  436. -> ModSummary
  437. -> SourceModified
  438. -> Maybe ModIface -- Old interface, if available
  439. -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
  440. -> IO result
  441. data HsCompiler a = HsCompiler {
  442. -- | Called when no recompilation is necessary.
  443. hscNoRecomp :: ModIface
  444. -> Hsc a,
  445. -- | Called to recompile the module.
  446. hscRecompile :: ModSummary -> Maybe Fingerprint
  447. -> Hsc a,
  448. hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint
  449. -> Hsc a,
  450. -- | Code generation for Boot modules.
  451. hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint
  452. -> Hsc a,
  453. -- | Code generation for normal modules.
  454. hscGenOutput :: ModGuts -> ModSummary -> Maybe Fingerprint
  455. -> Hsc a
  456. }
  457. genericHscCompile :: HsCompiler a
  458. -> (HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ())
  459. -> HscEnv -> ModSummary -> SourceModified
  460. -> Maybe ModIface -> Maybe (Int, Int)
  461. -> IO a
  462. genericHscCompile compiler hscMessage hsc_env
  463. mod_summary source_modified
  464. mb_old_iface0 mb_mod_index
  465. = do
  466. (recomp_reqd, mb_checked_iface)
  467. <- {-# SCC "checkOldIface" #-}
  468. checkOldIface hsc_env mod_summary
  469. source_modified mb_old_iface0
  470. -- save the interface that comes back from checkOldIface.
  471. -- In one-shot mode we don't have the old iface until this
  472. -- point, when checkOldIface reads it from the disk.
  473. let mb_old_hash = fmap mi_iface_hash mb_checked_iface
  474. let skip iface = do
  475. hscMessage hsc_env mb_mod_index RecompNotRequired mod_summary
  476. runHsc hsc_env $ hscNoRecomp compiler iface
  477. compile reason = do
  478. hscMessage hsc_env mb_mod_index reason mod_summary
  479. runHsc hsc_env $ hscRecompile compiler mod_summary mb_old_hash
  480. stable = case source_modified of
  481. SourceUnmodifiedAndStable -> True
  482. _ -> False
  483. -- If the module used TH splices when it was last compiled,
  484. -- then the recompilation check is not accurate enough (#481)
  485. -- and we must ignore it. However, if the module is stable
  486. -- (none of the modules it depends on, directly or indirectly,
  487. -- changed), then we *can* skip recompilation. This is why
  488. -- the SourceModified type contains SourceUnmodifiedAndStable,
  489. -- and it's pretty important: otherwise ghc --make would
  490. -- always recompile TH modules, even if nothing at all has
  491. -- changed. Stability is just the same check that make is
  492. -- doing for us in one-shot mode.
  493. case mb_checked_iface of
  494. Just iface | not recomp_reqd ->
  495. if mi_used_th iface && not stable
  496. then compile RecompForcedByTH
  497. else skip iface
  498. _otherwise ->
  499. compile RecompRequired
  500. hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
  501. hscCheckRecompBackend compiler tc_result hsc_env mod_summary
  502. source_modified mb_old_iface _m_of_n
  503. = do
  504. (recomp_reqd, mb_checked_iface)
  505. <- {-# SCC "checkOldIface" #-}
  506. checkOldIface hsc_env mod_summary
  507. source_modified mb_old_iface
  508. let mb_old_hash = fmap mi_iface_hash mb_checked_iface
  509. case mb_checked_iface of
  510. Just iface | not recomp_reqd
  511. -> runHsc hsc_env $
  512. hscNoRecomp compiler
  513. iface{ mi_globals = Just (tcg_rdr_env tc_result) }
  514. _otherwise
  515. -> runHsc hsc_env $
  516. hscBackend compiler tc_result mod_summary mb_old_hash
  517. genericHscRecompile :: HsCompiler a
  518. -> ModSummary -> Maybe Fingerprint
  519. -> Hsc a
  520. genericHscRecompile compiler mod_summary mb_old_hash
  521. | ExtCoreFile <- ms_hsc_src mod_summary =
  522. panic "GHC does not currently support reading External Core files"
  523. | otherwise = do
  524. tc_result <- hscFileFrontEnd mod_summary
  525. hscBackend compiler tc_result mod_summary mb_old_hash
  526. genericHscBackend :: HsCompiler a
  527. -> TcGblEnv -> ModSummary -> Maybe Fingerprint
  528. -> Hsc a
  529. genericHscBackend compiler tc_result mod_summary mb_old_hash
  530. | HsBootFile <- ms_hsc_src mod_summary =
  531. hscGenBootOutput compiler tc_result mod_summary mb_old_hash
  532. | otherwise = do
  533. guts <- hscDesugar' (ms_location mod_summary) tc_result
  534. hscGenOutput compiler guts mod_summary mb_old_hash
  535. compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a
  536. compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ =
  537. runHsc hsc_env $ hscBackend comp tcg ms' Nothing
  538. --------------------------------------------------------------
  539. -- Compilers
  540. --------------------------------------------------------------
  541. hscOneShotCompiler :: HsCompiler OneShotResult
  542. hscOneShotCompiler = HsCompiler {
  543. hscNoRecomp = \_old_iface -> do
  544. hsc_env <- getHscEnv
  545. liftIO $ dumpIfaceStats hsc_env
  546. return HscNoRecomp
  547. , hscRecompile = genericHscRecompile hscOneShotCompiler
  548. , hscBackend = \tc_result mod_summary mb_old_hash -> do
  549. dflags <- getDynFlags
  550. case hscTarget dflags of
  551. HscNothing -> return (HscRecomp Nothing ())
  552. _otherw -> genericHscBackend hscOneShotCompiler
  553. tc_result mod_summary mb_old_hash
  554. , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
  555. (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
  556. hscWriteIface iface changed mod_summary
  557. return (HscRecomp Nothing ())
  558. , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
  559. guts <- hscSimplify' guts0
  560. (iface, changed, _details, cgguts) <- hscNormalIface guts mb_old_iface
  561. hscWriteIface iface changed mod_summary
  562. hasStub <- hscGenHardCode cgguts mod_summary
  563. return (HscRecomp hasStub ())
  564. }
  565. -- Compile Haskell, boot and extCore in OneShot mode.
  566. hscCompileOneShot :: Compiler OneShotResult
  567. hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
  568. = do
  569. -- One-shot mode needs a knot-tying mutable variable for interface
  570. -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
  571. type_env_var <- newIORef emptyNameEnv
  572. let mod = ms_mod mod_summary
  573. hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
  574. genericHscCompile hscOneShotCompiler
  575. oneShotMsg hsc_env' mod_summary src_changed
  576. mb_old_iface mb_i_of_n
  577. hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult
  578. hscOneShotBackendOnly = compilerBackend hscOneShotCompiler
  579. --------------------------------------------------------------
  580. hscBatchCompiler :: HsCompiler BatchResult
  581. hscBatchCompiler = HsCompiler {
  582. hscNoRecomp = \iface -> do
  583. details <- genModDetails iface
  584. return (HscNoRecomp, iface, details)
  585. , hscRecompile = genericHscRecompile hscBatchCompiler
  586. , hscBackend = genericHscBackend hscBatchCompiler
  587. , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
  588. (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface
  589. hscWriteIface iface changed mod_summary
  590. return (HscRecomp Nothing (), iface, details)
  591. , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
  592. guts <- hscSimplify' guts0
  593. (iface, changed, details, cgguts) <- hscNormalIface guts mb_old_iface
  594. hscWriteIface iface changed mod_summary
  595. hasStub <- hscGenHardCode cgguts mod_summary
  596. return (HscRecomp hasStub (), iface, details)
  597. }
  598. -- | Compile Haskell, boot and extCore in batch mode.
  599. hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
  600. hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
  601. hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult
  602. hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler
  603. --------------------------------------------------------------
  604. hscInteractiveCompiler :: HsCompiler InteractiveResult
  605. hscInteractiveCompiler = HsCompiler {
  606. hscNoRecomp = \iface -> do
  607. details <- genModDetails iface
  608. return (HscNoRecomp, iface, details)
  609. , hscRecompile = genericHscRecompile hscInteractiveCompiler
  610. , hscBackend = genericHscBackend hscInteractiveCompiler
  611. , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
  612. (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
  613. return (HscRecomp Nothing Nothing, iface, details)
  614. , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
  615. guts <- hscSimplify' guts0
  616. (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface
  617. hscInteractive (iface, details, cgguts) mod_summary
  618. }
  619. -- Compile Haskell, extCore to bytecode.
  620. hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
  621. hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg
  622. hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult
  623. hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler
  624. --------------------------------------------------------------
  625. hscNothingCompiler :: HsCompiler NothingResult
  626. hscNothingCompiler = HsCompiler {
  627. hscNoRecomp = \iface -> do
  628. details <- genModDetails iface
  629. return (HscNoRecomp, iface, details)
  630. , hscRecompile = genericHscRecompile hscNothingCompiler
  631. , hscBackend = \tc_result _mod_summary mb_old_iface -> do
  632. handleWarnings
  633. (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
  634. return (HscRecomp Nothing (), iface, details)
  635. , hscGenBootOutput = \_ _ _ ->
  636. panic "hscCompileNothing: hscGenBootOutput should not be called"
  637. , hscGenOutput = \_ _ _ ->
  638. panic "hscCompileNothing: hscGenOutput should not be called"
  639. }
  640. -- Type-check Haskell and .hs-boot only (no external core)
  641. hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
  642. hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
  643. hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult
  644. hscNothingBackendOnly = compilerBackend hscNothingCompiler
  645. --------------------------------------------------------------
  646. -- NoRecomp handlers
  647. --------------------------------------------------------------
  648. genModDetails :: ModIface -> Hsc ModDetails
  649. genModDetails old_iface
  650. = do
  651. hsc_env <- getHscEnv
  652. new_details <- {-# SCC "tcRnIface" #-}
  653. liftIO $ initIfaceCheck hsc_env (typecheckIface old_iface)
  654. liftIO $ dumpIfaceStats hsc_env
  655. return new_details
  656. --------------------------------------------------------------
  657. -- Progress displayers.
  658. --------------------------------------------------------------
  659. data RecompReason = RecompNotRequired | RecompRequired | RecompForcedByTH
  660. deriving Eq
  661. oneShotMsg :: HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ()
  662. oneShotMsg hsc_env _mb_mod_index recomp _mod_summary =
  663. case recomp of
  664. RecompNotRequired ->
  665. compilationProgressMsg (hsc_dflags hsc_env) $
  666. "compilation IS NOT required"
  667. _other ->
  668. return ()
  669. batchMsg :: HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ()
  670. batchMsg hsc_env mb_mod_index recomp mod_summary =
  671. case recomp of
  672. RecompRequired -> showMsg "Compiling "
  673. RecompNotRequired
  674. | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping "
  675. | otherwise -> return ()
  676. RecompForcedByTH -> showMsg "Compiling [TH] "
  677. where
  678. showMsg msg =
  679. compilationProgressMsg (hsc_dflags hsc_env) $
  680. (showModuleIndex mb_mod_index ++
  681. msg ++ showModMsg (hscTarget (hsc_dflags hsc_env))
  682. (recomp == RecompRequired) mod_summary)
  683. --------------------------------------------------------------
  684. -- FrontEnds
  685. --------------------------------------------------------------
  686. hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
  687. hscFileFrontEnd mod_summary = do
  688. hpm <- hscParse' mod_summary
  689. hsc_env <- getHscEnv
  690. dflags <- getDynFlags
  691. tcg_env <-
  692. {-# SCC "Typecheck-Rename" #-}
  693. ioMsgMaybe $
  694. tcRnModule hsc_env (ms_hsc_src mod_summary) False hpm
  695. tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_env)
  696. -- end of the Safe Haskell line, how to respond to user?
  697. if not (safeHaskellOn dflags) || (safeInferOn dflags && not tcSafeOK)
  698. -- if safe haskell off or safe infer failed, wipe trust
  699. then wipeTrust tcg_env emptyBag
  700. -- module safe, throw warning if needed
  701. else do
  702. tcg_env' <- hscCheckSafeImports tcg_env
  703. safe <- liftIO $ hscGetSafeInf hsc_env
  704. when (safe && wopt Opt_WarnSafe dflags)
  705. (logWarnings $ unitBag $
  706. mkPlainWarnMsg (warnSafeOnLoc dflags) $ errSafe tcg_env')
  707. return tcg_env'
  708. where
  709. pprMod t = ppr $ moduleName $ tcg_mod t
  710. errSafe t = text "Warning:" <+> quotes (pprMod t)
  711. <+> text "has been infered as safe!"
  712. --------------------------------------------------------------
  713. -- Safe Haskell
  714. --------------------------------------------------------------
  715. -- Note [Safe Haskell Trust Check]
  716. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  717. -- Safe Haskell checks that an import is trusted according to the following
  718. -- rules for an import of module M that resides in Package P:
  719. --
  720. -- * If M is recorded as Safe and all its trust dependencies are OK
  721. -- then M is considered safe.
  722. -- * If M is recorded as Trustworthy and P is considered trusted and
  723. -- all M's trust dependencies are OK then M is considered safe.
  724. --
  725. -- By trust dependencies we mean that the check is transitive. So if
  726. -- a module M that is Safe relies on a module N that is trustworthy,
  727. -- importing module M will first check (according to the second case)
  728. -- that N is trusted before checking M is trusted.
  729. --
  730. -- This is a minimal description, so please refer to the user guide
  731. -- for more details. The user guide is also considered the authoritative
  732. -- source in this matter, not the comments or code.
  733. -- Note [Safe Haskell Inference]
  734. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  735. -- Safe Haskell does Safe inference on modules that don't have any specific
  736. -- safe haskell mode flag. The basic aproach to this is:
  737. -- * When deciding if we need to do a Safe language check, treat
  738. -- an unmarked module as having -XSafe mode specified.
  739. -- * For checks, don't throw errors but return them to the caller.
  740. -- * Caller checks if there are errors:
  741. -- * For modules explicitly marked -XSafe, we throw the errors.
  742. -- * For unmarked modules (inference mode), we drop the errors
  743. -- and mark the module as being Unsafe.
  744. -- | Check that the safe imports of the module being compiled are valid.
  745. -- If not we either issue a compilation error if the module is explicitly
  746. -- using Safe Haskell, or mark the module as unsafe if we're in safe
  747. -- inference mode.
  748. hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv
  749. hscCheckSafeImports tcg_env = do
  750. dflags <- getDynFlags
  751. tcg_env' <- checkSafeImports dflags tcg_env
  752. case safeLanguageOn dflags of
  753. True -> do
  754. -- we nuke user written RULES in -XSafe
  755. logWarnings $ warns (tcg_rules tcg_env')
  756. return tcg_env' { tcg_rules = [] }
  757. False
  758. -- user defined RULES, so not safe or already unsafe
  759. | safeInferOn dflags && not (null $ tcg_rules tcg_env') ||
  760. safeHaskell dflags == Sf_None
  761. -> wipeTrust tcg_env' $ warns (tcg_rules tcg_env')
  762. -- trustworthy OR safe infered with no RULES
  763. | otherwise
  764. -> return tcg_env'
  765. where
  766. warns rules = listToBag $ map warnRules rules
  767. warnRules (L loc (HsRule n _ _ _ _ _ _)) =
  768. mkPlainWarnMsg loc $
  769. text "Rule \"" <> ftext n <> text "\" ignored" $+$
  770. text "User defined rules are disabled under Safe Haskell"
  771. -- | Validate that safe imported modules are actually safe. For modules in the
  772. -- HomePackage (the package the module we are compiling in resides) this just
  773. -- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules
  774. -- that reside in another package we also must check that the external pacakge
  775. -- is trusted. See the Note [Safe Haskell Trust Check] above for more
  776. -- information.
  777. --
  778. -- The code for this is quite tricky as the whole algorithm is done in a few
  779. -- distinct phases in different parts of the code base. See
  780. -- RnNames.rnImportDecl for where package trust dependencies for a module are
  781. -- collected and unioned. Specifically see the Note [RnNames . Tracking Trust
  782. -- Transitively] and the Note [RnNames . Trust Own Package].
  783. checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv
  784. checkSafeImports dflags tcg_env
  785. = do
  786. -- We want to use the warning state specifically for detecting if safe
  787. -- inference has failed, so store and clear any existing warnings.
  788. oldErrs <- getWarnings
  789. clearWarnings
  790. imps <- mapM condense imports'
  791. pkgs <- mapM checkSafe imps
  792. -- grab any safe haskell specific errors and restore old warnings
  793. errs <- getWarnings
  794. clearWarnings
  795. logWarnings oldErrs
  796. -- See the Note [Safe Haskell Inference]
  797. case (not $ isEmptyBag errs) of
  798. -- We have errors!
  799. True ->
  800. -- did we fail safe inference or fail -XSafe?
  801. case safeInferOn dflags of
  802. True -> wipeTrust tcg_env errs
  803. False -> liftIO . throwIO . mkSrcErr $ errs
  804. -- All good matey!
  805. False -> do
  806. when (packageTrustOn dflags) $ checkPkgTrust dflags pkg_reqs
  807. -- add in trusted package requirements for this module
  808. let new_trust = emptyImportAvails { imp_trust_pkgs = catMaybes pkgs }
  809. return tcg_env { tcg_imports = imp_info `plusImportAvails` new_trust }
  810. where
  811. imp_info = tcg_imports tcg_env -- ImportAvails
  812. imports = imp_mods imp_info -- ImportedMods
  813. imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])
  814. pkg_reqs = imp_trust_pkgs imp_info -- [PackageId]
  815. condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport)
  816. condense (_, []) = panic "HscMain.condense: Pattern match failure!"
  817. condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs
  818. -- we turn all imports into safe ones when
  819. -- inference mode is on.
  820. let s' = if safeInferOn dflags then True else s
  821. return (m, l, s')
  822. -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
  823. cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
  824. cond' v1@(m1,_,l1,s1) (_,_,_,s2)
  825. | s1 /= s2
  826. = throwErrors $ unitBag $ mkPlainErrMsg l1
  827. (text "Module" <+> ppr m1 <+>
  828. (text $ "is imported both as a safe and unsafe import!"))
  829. | otherwise
  830. = return v1
  831. -- easier interface to work with
  832. checkSafe (_, _, False) = return Nothing
  833. checkSafe (m, l, True ) = hscCheckSafe' dflags m l
  834. -- | Check that a module is safe to import.
  835. --
  836. -- We return a package id if the safe import is OK and a Nothing otherwise
  837. -- with the reason for the failure printed out.
  838. hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO (Maybe PackageId)
  839. hscCheckSafe hsc_env m l = runHsc hsc_env $ do
  840. dflags <- getDynFlags
  841. hscCheckSafe' dflags m l
  842. hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageId)
  843. hscCheckSafe' dflags m l = do
  844. tw <- isModSafe m l
  845. case tw of
  846. False -> return Nothing
  847. True | isHomePkg m -> return Nothing
  848. | otherwise -> return $ Just $ modulePackageId m
  849. where
  850. -- Is a module trusted? Return Nothing if True, or a String if it isn't,
  851. -- containing the reason it isn't. Also return if the module trustworthy
  852. -- (true) or safe (false) so we know if we should check if the package
  853. -- itself is trusted in the future.
  854. isModSafe :: Module -> SrcSpan -> Hsc (Bool)
  855. isModSafe m l = do
  856. iface <- lookup' m
  857. case iface of
  858. -- can't load iface to check trust!
  859. Nothing -> throwErrors $ unitBag $ mkPlainErrMsg l
  860. $ text "Can't load the interface file for" <+> ppr m <>
  861. text ", to check that it can be safely imported"
  862. -- got iface, check trust
  863. Just iface' -> do
  864. let trust = getSafeMode $ mi_trust iface'
  865. trust_own_pkg = mi_trust_pkg iface'
  866. -- check module is trusted
  867. safeM = trust `elem` [Sf_SafeInfered, Sf_Safe, Sf_Trustworthy]
  868. -- check package is trusted
  869. safeP = packageTrusted trust trust_own_pkg m
  870. case (safeM, safeP) of
  871. -- General errors we throw but Safe errors we log
  872. (True, True ) -> return $ trust == Sf_Trustworthy
  873. (True, False) -> liftIO . throwIO $ pkgTrustErr
  874. (False, _ ) -> logWarnings modTrustErr >> return (trust == Sf_Trustworthy)
  875. where
  876. pkgTrustErr = mkSrcErr $ unitBag $ mkPlainErrMsg l $ ppr m
  877. <+> text "can't be safely imported!" <+> text "The package ("
  878. <> ppr (modulePackageId m)
  879. <> text ") the module resides in isn't trusted."
  880. modTrustErr = unitBag $ mkPlainErrMsg l $ ppr m
  881. <+> text "can't be safely imported!"
  882. <+> text "The module itself isn't safe."
  883. -- | Check the package a module resides in is trusted. Safe compiled
  884. -- modules are trusted without requiring that their package is trusted. For
  885. -- trustworthy modules, modules in the home package are trusted but
  886. -- otherwise we check the package trust flag.
  887. packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool
  888. packageTrusted _ _ _
  889. | not (packageTrustOn dflags) = True
  890. packageTrusted Sf_Safe False _ = True
  891. packageTrusted Sf_SafeInfered False _ = True
  892. packageTrusted _ _ m
  893. | isHomePkg m = True
  894. | otherwise = trusted $ getPackageDetails (pkgState dflags)
  895. (modulePackageId m)
  896. lookup' :: Module -> Hsc (Maybe ModIface)
  897. lookup' m = do
  898. hsc_env <- getHscEnv
  899. hsc_eps <- liftIO $ hscEPS hsc_env
  900. let pkgIfaceT = eps_PIT hsc_eps
  901. homePkgT = hsc_HPT hsc_env
  902. iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m
  903. return iface
  904. isHomePkg :: Module -> Bool
  905. isHomePkg m
  906. | thisPackage dflags == modulePackageId m = True
  907. | otherwise = False
  908. -- | Check the list of packages are trusted.
  909. checkPkgTrust :: DynFlags -> [PackageId] -> Hsc ()
  910. checkPkgTrust dflags pkgs =
  911. case errors of
  912. [] -> return ()
  913. _ -> (liftIO . throwIO . mkSrcErr . listToBag) errors
  914. where
  915. errors = catMaybes $ map go pkgs
  916. go pkg
  917. | trusted $ getPackageDetails (pkgState dflags) pkg
  918. = Nothing
  919. | otherwise
  920. = Just $ mkPlainErrMsg noSrcSpan
  921. $ text "The package (" <> ppr pkg <> text ") is required"
  922. <> text " to be trusted but it isn't!"
  923. -- | Set module to unsafe and wipe trust information.
  924. --
  925. -- Make sure to call this method to set a module to infered unsafe,
  926. -- it should be a central and single failure method.
  927. wipeTrust :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv
  928. wipeTrust tcg_env whyUnsafe = do
  929. env <- getHscEnv
  930. dflags <- getDynFlags
  931. when (wopt Opt_WarnUnsafe dflags)
  932. (logWarnings $ unitBag $
  933. mkPlainWarnMsg (warnUnsafeOnLoc dflags) whyUnsafe')
  934. liftIO $ hscSetSafeInf env False
  935. return $ tcg_env { tcg_imports = wiped_trust }
  936. where
  937. wiped_trust = (tcg_imports tcg_env) { imp_trust_pkgs = [] }
  938. pprMod = ppr $ moduleName $ tcg_mod tcg_env
  939. whyUnsafe' = vcat [ text "Warning:" <+> quotes pprMod
  940. <+> text "has been infered as unsafe!"
  941. , text "Reason:"
  942. , nest 4 (vcat $ pprErrMsgBag whyUnsafe) ]
  943. --------------------------------------------------------------
  944. -- Simplifiers
  945. --------------------------------------------------------------
  946. hscSimplify :: HscEnv -> ModGuts -> IO ModGuts
  947. hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts
  948. hscSimplify' :: ModGuts -> Hsc ModGuts
  949. hscSimplify' ds_result = do
  950. hsc_env <- getHscEnv
  951. {-# SCC "Core2Core" #-}
  952. liftIO $ core2core hsc_env ds_result
  953. --------------------------------------------------------------
  954. -- Interface generators
  955. --------------------------------------------------------------
  956. hscSimpleIface :: TcGblEnv
  957. -> Maybe Fingerprint
  958. -> Hsc (ModIface, Bool, ModDetails)
  959. hscSimpleIface tc_result mb_old_iface = do
  960. hsc_env <- getHscEnv
  961. details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
  962. (new_iface, no_change)
  963. <- {-# SCC "MkFinalIface" #-}
  964. ioMsgMaybe $
  965. mkIfaceTc hsc_env mb_old_iface details tc_result
  966. -- And the answer is ...
  967. liftIO $ dumpIfaceStats hsc_env
  968. return (new_iface, no_change, details)
  969. hscNormalIface :: ModGuts
  970. -> Maybe Fingerprint
  971. -> Hsc (ModIface, Bool, ModDetails, CgGuts)
  972. hscNormalIface simpl_result mb_old_iface = do
  973. hsc_env <- getHscEnv
  974. (cg_guts, details) <- {-# SCC "CoreTidy" #-}
  975. liftIO $ tidyProgram hsc_env simpl_result
  976. -- BUILD THE NEW ModIface and ModDetails
  977. -- and emit external core if necessary
  978. -- This has to happen *after* code gen so that the back-end
  979. -- info has been set. Not yet clear if it matters waiting
  980. -- until after code output
  981. (new_iface, no_change)
  982. <- {-# SCC "MkFinalIface" #-}
  983. ioMsgMaybe $
  984. mkIface hsc_env mb_old_iface details simpl_result
  985. -- Emit external core
  986. -- This should definitely be here and not after CorePrep,
  987. -- because CorePrep produces unqualified constructor wrapper declarations,
  988. -- so its output isn't valid External Core (without some preprocessing).
  989. liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts
  990. liftIO $ dumpIfaceStats hsc_env
  991. -- Return the prepared code.
  992. return (new_iface, no_change, details, cg_guts)
  993. --------------------------------------------------------------
  994. -- BackEnd combinators
  995. --------------------------------------------------------------
  996. hscWriteIface :: ModIface -> Bool -> ModSummary -> Hsc ()
  997. hscWriteIface iface no_change mod_summary = do
  998. dflags <- getDynFlags
  999. unless no_change $
  1000. {-# SCC "writeIface" #-}
  1001. liftIO $ writeIfaceFile dflags (ms_location mod_summary) iface
  1002. -- | Compile to hard-code.
  1003. hscGenHardCode :: CgGuts -> ModSummary
  1004. -> Hsc (Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f
  1005. hscGenHardCode cgguts mod_summary = do
  1006. hsc_env <- getHscEnv
  1007. liftIO $ do
  1008. let CgGuts{ -- This is the last use of the ModGuts in a compilation.
  1009. -- From now on, we just use the bits we need.
  1010. cg_module = this_mod,
  1011. cg_binds = core_binds,
  1012. cg_tycons = tycons,
  1013. cg_foreign = foreign_stubs0,
  1014. cg_dep_pkgs = dependencies,
  1015. cg_hpc_info = hpc_info } = cgguts
  1016. dflags = hsc_dflags hsc_env
  1017. platform = targetPlatform dflags
  1018. location = ms_location mod_summary
  1019. data_tycons = filter isDataTyCon tycons
  1020. -- cg_tycons includes newtypes, for the benefit of External Core,
  1021. -- but we don't generate any code for newtypes
  1022. -------------------
  1023. -- PREPARE FOR CODE GENERATION
  1024. -- Do saturation and convert to A-normal form
  1025. prepd_binds <- {-# SCC "CorePrep" #-}
  1026. corePrepPgm dflags core_binds data_tycons ;
  1027. ----------------- Convert to STG ------------------
  1028. (stg_binds, cost_centre_info)
  1029. <- {-# SCC "CoreToStg" #-}
  1030. myCoreToStg dflags this_mod prepd_binds
  1031. let prof_init = profilingInitCode platform this_mod cost_centre_info
  1032. foreign_stubs = foreign_stubs0 `appendStubC` prof_init
  1033. ------------------ Code generation ------------------
  1034. cmms <- if dopt Opt_TryNewCodeGen dflags
  1035. then {-# SCC "NewCodeGen" #-}
  1036. tryNewCodeGen hsc_env this_mod data_tycons
  1037. cost_centre_info
  1038. stg_binds hpc_info
  1039. else {-# SCC "CodeGen" #-}
  1040. codeGen dflags this_mod data_tycons
  1041. cost_centre_info
  1042. stg_binds hpc_info
  1043. ------------------ Code output -----------------------
  1044. rawcmms <- {-# SCC "cmmToRawCmm" #-}
  1045. cmmToRawCmm platform cmms
  1046. dumpIfSet_dyn dflags Opt_D_dump_raw_cmm "Raw Cmm" (pprPlatform platform rawcmms)
  1047. (_stub_h_exists, stub_c_exists)
  1048. <- {-# SCC "codeOutput" #-}
  1049. codeOutput dflags this_mod location foreign_stubs
  1050. dependencies rawcmms
  1051. return stub_c_exists
  1052. hscInteractive :: (ModIface, ModDetails, CgGuts)
  1053. -> ModSummary
  1054. -> Hsc (InteractiveStatus, ModIface, ModDetails)
  1055. #ifdef GHCI
  1056. hscInteractive (iface, details, cgguts) mod_summary = do
  1057. dflags <- getDynFlags
  1058. let CgGuts{ -- This is the last use of the ModGuts in a compilation.
  1059. -- From now on, we just use the bits we need.
  1060. cg_module = this_mod,
  1061. cg_binds = core_binds,
  1062. cg_tycons = tycons,
  1063. cg_foreign = foreign_stubs,
  1064. cg_modBreaks = mod_breaks } = cgguts
  1065. location = ms_location mod_summary
  1066. data_tycons = filter isDataTyCon tycons
  1067. -- cg_tycons includes newtypes, for the benefit of External Core,
  1068. -- but we don't generate any code for newtypes
  1069. -------------------
  1070. -- PREPARE FOR CODE GENERATION
  1071. -- Do saturation and convert to A-normal form
  1072. prepd_binds <- {-# SCC "CorePrep" #-}
  1073. liftIO $ corePrepPgm dflags core_binds data_tycons ;
  1074. ----------------- Generate byte code ------------------
  1075. comp_bc <- liftIO $ byteCodeGen dflags this_mod prepd_binds
  1076. data_tycons mod_breaks
  1077. ------------------ Create f-x-dynamic C-side stuff ---
  1078. (_istub_h_exists, istub_c_exists)
  1079. <- liftIO $ outputForeignStubs dflags this_mod
  1080. location foreign_stubs
  1081. return (HscRecomp istub_c_exists (Just (comp_bc, mod_breaks))
  1082. , iface, details)
  1083. #else
  1084. hscInteractive _ _ = panic "GHC not compiled with interpreter"
  1085. #endif
  1086. ------------------------------
  1087. hscCompileCmmFile :: HscEnv -> FilePath -> IO ()
  1088. hscCompileCmmFile hsc_env filename = runHsc hsc_env $ do
  1089. let dflags = hsc_dflags hsc_env
  1090. cmm <- ioMsgMaybe $ parseCmmFile dflags filename
  1091. liftIO $ do
  1092. rawCmms <- cmmToRawCmm (targetPlatform dflags) [cmm]
  1093. _ <- codeOutput dflags no_mod no_loc NoStubs [] rawCmms
  1094. return ()
  1095. where
  1096. no_mod = panic "hscCmmFile: no_mod"
  1097. no_loc = ModLocation{ ml_hs_file = Just filename,
  1098. ml_hi_file = panic "hscCmmFile: no hi file",
  1099. ml_obj_file = panic "hscCmmFile: no obj file" }
  1100. -------------------- Stuff for new code gen ---------------------
  1101. tryNewCodeGen :: HscEnv -> Module -> [TyCon]
  1102. -> CollectedCCs
  1103. -> [(StgBinding,[(Id,[Id])])]
  1104. -> HpcInfo
  1105. -> IO [Old.CmmGroup]
  1106. tryNewCodeGen hsc_env this_mod data_tycons
  1107. cost_centre_info stg_binds hpc_info = do
  1108. let dflags = hsc_dflags hsc_env
  1109. platform = targetPlatform dflags
  1110. prog <- StgCmm.codeGen dflags this_mod data_tycons
  1111. cost_centre_info stg_binds hpc_info
  1112. dumpIfSet_dyn dflags Opt_D_dump_cmmz "Cmm produced by new codegen"
  1113. (pprCmms platform prog)
  1114. -- We are building a single SRT for the entire module, so
  1115. -- we must thread it through all the procedures as we cps-convert them.
  1116. us <- mkSplitUniqSupply 'S'
  1117. let initTopSRT = initUs_ us emptySRT
  1118. (topSRT, prog) <- foldM (cmmPipeline hsc_env) (initTopSRT, []) prog
  1119. let prog' = map cmmOfZgraph (srtToData topSRT : prog)
  1120. dumpIfSet_dyn dflags Opt_D_dump_cmmz "Output Cmm" (pprPlatform platform prog')
  1121. return prog'
  1122. myCoreToStg :: DynFlags -> Module -> CoreProgram
  1123. -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
  1124. , CollectedCCs) -- cost centre info (declared and used)
  1125. myCoreToStg dflags this_mod prepd_binds = do
  1126. stg_binds
  1127. <- {-# SCC "Core2Stg" #-}
  1128. coreToStg dflags prepd_binds
  1129. (stg_binds2, cost_centre_info)
  1130. <- {-# SCC "Stg2Stg" #-}
  1131. stg2stg dflags this_mod stg_binds
  1132. return (stg_binds2, cost_centre_info)
  1133. {- **********************************************************************
  1134. %* *
  1135. \subsection{Compiling a do-statement}
  1136. %* *
  1137. %********************************************************************* -}
  1138. {-
  1139. When the UnlinkedBCOExpr is linked you get an HValue of type
  1140. IO [HValue]
  1141. When you run it you get a list of HValues that should be
  1142. the same length as the list of names; add them to the ClosureEnv.
  1143. A naked expression returns a singleton Name [it].
  1144. What you type The IO [HValue] that hscStmt returns
  1145. ------------- ------------------------------------
  1146. let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
  1147. bindings: [x,y,...]
  1148. pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
  1149. bindings: [x,y,...]
  1150. expr (of IO type) ==> expr >>= \ v -> return [v]
  1151. [NB: result not printed] bindings: [it]
  1152. expr (of non-IO type,
  1153. result showable) ==> let v = expr in print v >> return [v]
  1154. bindings: [it]
  1155. expr (of non-IO type,
  1156. result not showable) ==> error
  1157. -}
  1158. #ifdef GHCI
  1159. -- | Compile a stmt all the way to an HValue, but don't run it
  1160. hscStmt :: HscEnv
  1161. -> String -- ^ The statement
  1162. -> IO (Maybe ([Id], HValue)) -- ^ 'Nothing' <==> empty statement
  1163. -- (or comment only), but no parse error
  1164. hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1
  1165. -- | Compile a stmt all the way to an HValue, but don't run it
  1166. hscStmtWithLocation :: HscEnv
  1167. -> String -- ^ The statement
  1168. -> String -- ^ The source
  1169. -> Int -- ^ Starting line
  1170. -> IO (Maybe ([Id], HValue)) -- ^ 'Nothing' <==> empty statement
  1171. -- (or comment only), but no parse error
  1172. hscStmtWithLocation hsc_env stmt source linenumber = runHsc hsc_env $ do
  1173. maybe_stmt <- hscParseStmtWithLocation source linenumber stmt
  1174. case maybe_stmt of
  1175. Nothing -> return Nothing
  1176. -- The real stuff
  1177. Just parsed_stmt -> do
  1178. -- Rename and typecheck it
  1179. let icontext = hsc_IC hsc_env
  1180. (ids, tc_expr) <- ioMsgMaybe $
  1181. tcRnStmt hsc_env icontext parsed_stmt
  1182. -- Desugar it
  1183. let rdr_env = ic_rn_gbl_env icontext
  1184. type_env = mkTypeEnvWithImplicits (ic_tythings icontext)
  1185. ds_expr <- ioMsgMaybe $
  1186. deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
  1187. handleWarnings
  1188. -- Then code-gen, and link it
  1189. let src_span = srcLocSpan interactiveSrcLoc
  1190. hsc_env <- getHscEnv
  1191. hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr
  1192. return $ Just (ids, hval)
  1193. -- | Compile a decls
  1194. hscDecls :: HscEnv
  1195. -> String -- ^ The statement
  1196. -> IO ([TyThing], InteractiveContext)
  1197. hscDecls hsc_env str = hscDeclsWithLocation hsc_env str "<interactive>" 1
  1198. -- | Compile a decls
  1199. hscDeclsWithLocation :: HscEnv
  1200. -> String -- ^ The statement
  1201. -> String -- ^ The source
  1202. -> Int -- ^ Starting line
  1203. -> IO ([TyThing], InteractiveContext)
  1204. hscDeclsWithLocation hsc_env str source linenumber = runHsc hsc_env $ do
  1205. L _ (HsModule{ hsmodDecls = decls }) <-
  1206. hscParseThingWithLocation source linenumber parseModule str
  1207. {- Rename and typecheck it -}
  1208. let icontext = hsc_IC hsc_env
  1209. tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env icontext decls
  1210. {- Grab the new instances -}
  1211. -- We grab the whole environment because of the overlapping that may have
  1212. -- been done. See the notes at the definition of InteractiveContext
  1213. -- (ic_instances) for more details.
  1214. let finsts = famInstEnvElts $ tcg_fam_inst_env tc_gblenv
  1215. insts = instEnvElts $ tcg_inst_env tc_gblenv
  1216. {- Desugar it -}
  1217. -- We use a basically null location for iNTERACTIVE
  1218. let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing,
  1219. ml_hi_file = undefined,
  1220. ml_obj_file = undefined}
  1221. ds_result <- hscDesugar' iNTERACTIVELoc tc_gblenv
  1222. {- Simplify -}
  1223. simpl_mg <- liftIO $ hscSimplify hsc_env ds_result
  1224. {- Tidy -}
  1225. (tidy_cg, _mod_details) <- liftIO $ tidyProgram hsc_env simpl_mg
  1226. let dflags = hsc_dflags hsc_env
  1227. !CgGuts{ cg_module = this_mod,
  1228. cg_binds = core_binds,
  1229. cg_tycons = tycons,
  1230. cg_modBreaks = mod_breaks } = tidy_cg
  1231. data_tycons = filter isDataTyCon tycons
  1232. {- Prepare For Code Generation -}
  1233. -- Do saturation and convert to A-normal form
  1234. prepd_binds <- {-# SCC "CorePrep" #-}
  1235. liftIO $ corePrepPgm dflags core_binds data_tycons
  1236. {- Generate byte code -}
  1237. cbc <- liftIO $ byteCodeGen dflags this_mod
  1238. prepd_binds data_tycons mod_breaks
  1239. let src_span = srcLocSpan interactiveSrcLoc
  1240. hsc_env <- getHscEnv
  1241. liftIO $ linkDecls hsc_env src_span cbc
  1242. let tcs = filter (not . isImplicitTyCon) $ (mg_tcs simpl_mg)
  1243. ext_vars = filter (isExternalName . idName) $
  1244. bindersOfBinds core_binds
  1245. (sys_vars, user_vars) = partition is_sys_var ext_vars
  1246. is_sys_var id = isDFunId id
  1247. || isRecordSelector id
  1248. || isJust (isClassOpId_maybe id)
  1249. -- we only need to keep around the external bindings
  1250. -- (as decided by TidyPgm), since those are the only ones
  1251. -- that might be referenced elsewhere.
  1252. tythings = map AnId user_vars
  1253. ++ map ATyCon tcs
  1254. let ictxt1 = extendInteractiveContext icontext tythings
  1255. ictxt = ictxt1 { ic_sys_vars = sys_vars ++ ic_sys_vars ictxt1,
  1256. ic_instances = (insts, finsts) }
  1257. return (tythings, ictxt)
  1258. hscImport :: HscEnv -> String -> IO (ImportDecl RdrName)
  1259. hscImport hsc_env str = runHsc hsc_env $ do
  1260. (L _ (HsModule{hsmodImports=is})) <-
  1261. hscParseThing parseModule str
  1262. case is of
  1263. [i] -> return (unLoc i)
  1264. _ -> liftIO $ throwOneError $
  1265. mkPlainErrMsg noSrcSpan $
  1266. ptext (sLit "parse error in import declaration")
  1267. -- | Typecheck an expression (but don't run it)
  1268. hscTcExpr :: HscEnv
  1269. -> String -- ^ The expression
  1270. -> IO Type
  1271. hscTcExpr hsc_env expr = runHsc hsc_env $ do
  1272. maybe_stmt <- hscParseStmt expr
  1273. case maybe_stmt of
  1274. Just (L _ (ExprStmt expr _ _ _)) ->
  1275. ioMsgMaybe $ tcRnExpr hsc_env (hsc_IC hsc_env) expr
  1276. _ ->
  1277. throwErrors $ unitBag $ mkPlainErrMsg noSrcSpan
  1278. (text "not an expression:" <+> quotes (text expr))
  1279. -- | Find the kind of a type
  1280. hscKcType
  1281. :: HscEnv
  1282. -> Bool -- ^ Normalise the type
  1283. -> String -- ^ The type as a string
  1284. -> IO (Type, Kind) -- ^ Resulting type (possibly normalised) and kind
  1285. hscKcType hsc_env normalise str = runHsc hsc_env $ do
  1286. ty <- hscParseType str
  1287. ioMsgMaybe $ tcRnType hsc_env (hsc_IC hsc_env) normalise ty
  1288. hscParseStmt :: String -> Hsc (Maybe (LStmt RdrName))
  1289. hscParseStmt = hscParseThing parseStmt
  1290. hscParseStmtWithLocation :: String -> Int -> String
  1291. -> Hsc (Maybe (LStmt RdrName))
  1292. hscParseStmtWithLocation source linenumber stmt =
  1293. hscParseThingWithLocation source linenumber parseStmt stmt
  1294. hscParseType :: String -> Hsc (LHsType RdrName)
  1295. hscParseType = hscParseThing parseType
  1296. #endif
  1297. hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName)
  1298. hscParseIdentifier hsc_env str =
  1299. runHsc hsc_env $ hscParseThing parseIdentifier str
  1300. hscParseThing :: (Outputable thing) => Lexer.P thing -> String -> Hsc thing
  1301. hscParseThing = hscParseThingWithLocation "<interactive>" 1
  1302. hscParseThingWithLocation :: (Outputable thing) => String -> Int
  1303. -> Lexer.P thing -> String -> Hsc thing
  1304. hscParseThingWithLocation source linenumber parser str
  1305. = {-# SCC "Parser" #-} do
  1306. dflags <- getDynFlags
  1307. liftIO $ showPass dflags "Parser"
  1308. let buf = stringToStringBuffer str
  1309. loc = mkRealSrcLoc (fsLit source) linenumber 1
  1310. case unP parser (mkPState dflags buf loc) of
  1311. PFailed span err -> do
  1312. let msg = mkPlainErrMsg span err
  1313. throwErrors $ unitBag msg
  1314. POk pst thing -> do
  1315. logWarningsReportErrors (getMessages pst)
  1316. liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
  1317. return thing
  1318. hscCompileCore :: HscEnv -> Bool -> ModSummary -> CoreProgram -> IO ()
  1319. hscCompileCore hsc_env simplify mod_summary binds = runHsc hsc_env $ do
  1320. guts <- maybe_simplify (mkModGuts (ms_mod mod_summary) binds)
  1321. (iface, changed, _details, cgguts) <- hscNormalIface guts Nothing
  1322. hscWriteIface iface changed mod_summary
  1323. _ <- hscGenHardCode cgguts mod_summary
  1324. return ()
  1325. where
  1326. maybe_simplify mod_guts | simplify = hscSimplify' mod_guts
  1327. | otherwise = return mod_guts
  1328. -- Makes a "vanilla" ModGuts.
  1329. mkModGuts :: Module -> CoreProgram -> ModGuts
  1330. mkModGuts mod binds =
  1331. ModGuts {
  1332. mg_module = mod,
  1333. mg_boot = False,
  1334. mg_exports = [],
  1335. mg_deps = noDependencies,
  1336. mg_dir_imps = emptyModuleEnv,
  1337. mg_used_names = emptyNameSet,
  1338. mg_used_th = False,
  1339. mg_rdr_env = emptyGlobalRdrEnv,
  1340. mg_fix_env = emptyFixityEnv,
  1341. mg_tcs = [],
  1342. mg_insts = [],
  1343. mg_fam_insts = [],
  1344. mg_rules = [],
  1345. mg_vect_decls = [],
  1346. mg_binds = binds,
  1347. mg_foreign = NoStubs,
  1348. mg_warns = NoWarnings,
  1349. mg_anns = [],
  1350. mg_hpc_info = emptyHpcInfo False,
  1351. mg_modBreaks = emptyModBreaks,
  1352. mg_vect_info = noVectInfo,
  1353. mg_inst_env = emptyInstEnv,
  1354. mg_fam_inst_env = emptyFamInstEnv,
  1355. mg_trust_pkg = False,
  1356. mg_dependent_files = []
  1357. }
  1358. {- **********************************************************************
  1359. %* *
  1360. Desugar, simplify, convert to bytecode, and link an expression
  1361. %* *
  1362. %********************************************************************* -}
  1363. #ifdef GHCI
  1364. hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
  1365. hscCompileCoreExpr hsc_env srcspan ds_expr
  1366. | rtsIsProfiled
  1367. = throwIO (InstallationError "You can't call hscCompileCoreExpr in a profiled compiler")
  1368. -- Otherwise you get a seg-fault when you run it
  1369. | otherwise = do
  1370. let dflags = hsc_dflags hsc_env
  1371. let lint_on = dopt Opt_DoCoreLinting dflags
  1372. {- Simplify it -}
  1373. simpl_expr <- simplifyExpr dflags ds_expr
  1374. {- Tidy it (temporary, until coreSat does cloning) -}
  1375. let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
  1376. {- Prepare for codegen -}
  1377. prepd_expr <- corePrepExpr dflags tidy_expr
  1378. {- Lint if necessary -}
  1379. -- ToDo: improve SrcLoc
  1380. when lint_on $
  1381. let ictxt = hsc_IC hsc_env
  1382. te = mkTypeEnvWithImplicits (ic_tythings ictxt ++ map AnId (ic_sys_vars ictxt))
  1383. tyvars = varSetElems $ tyThingsTyVars $ typeEnvElts $ te
  1384. vars = typeEnvIds te
  1385. in case lintUnfolding noSrcLoc (tyvars ++ vars) prepd_expr of
  1386. Just err -> pprPanic "hscCompileCoreExpr" err
  1387. Nothing -> return ()
  1388. {- Convert to BCOs -}
  1389. bcos <- coreExprToBCOs dflags iNTERACTIVE prepd_expr
  1390. {- link it -}
  1391. hval <- linkExpr hsc_env srcspan bcos
  1392. return hval
  1393. #endif
  1394. {- **********************************************************************
  1395. %* *
  1396. Statistics on reading interfaces
  1397. %* *
  1398. %********************************************************************* -}
  1399. dumpIfaceStats :: HscEnv -> IO ()
  1400. dumpIfaceStats hsc_env = do
  1401. eps <- readIORef (hsc_EPS hsc_env)
  1402. dumpIfSet (dump_if_trace || dump_rn_stats)
  1403. "Interface statistics"
  1404. (ifaceStats eps)
  1405. where
  1406. dflags = hsc_dflags hsc_env
  1407. dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
  1408. dump_if_trace = dopt Opt_D_dump_if_trace dflags
  1409. {- **********************************************************************
  1410. %* *
  1411. Progress Messages: Module i of n
  1412. %* *
  1413. %********************************************************************* -}
  1414. showModuleIndex :: Maybe (Int, Int) -> String
  1415. showModuleIndex Nothing = ""
  1416. showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
  1417. where
  1418. n_str = show n
  1419. i_str = show i
  1420. padded = replicate (length n_str - length i_str) ' ' ++ i_str