PageRenderTime 72ms CodeModel.GetById 20ms 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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file