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

/compiler/main/HscMain.hs

https://bitbucket.org/carter/ghc
Haskell | 1799 lines | 1116 code | 271 blank | 412 comment | 17 complexity | fac5be020eb90da8916b6978a3b59a43 MD5 | raw file

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. , hscGetSafe
  60. #ifdef GHCI
  61. , hscIsGHCiMonad
  62. , hscGetModuleInterface
  63. , hscRnImportDecls
  64. , hscTcRnLookupRdrName
  65. , hscStmt, hscStmtWithLocation
  66. , hscDecls, hscDeclsWithLocation
  67. , hscTcExpr, hscImport, hscKcType
  68. , hscCompileCoreExpr
  69. #endif
  70. ) where
  71. #ifdef GHCI
  72. import Id
  73. import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
  74. import Linker
  75. import CoreTidy ( tidyExpr )
  76. import Type ( Type )
  77. import PrelNames
  78. import {- Kind parts of -} Type ( Kind )
  79. import CoreLint ( lintUnfolding )
  80. import DsMeta ( templateHaskellNames )
  81. import VarSet
  82. import VarEnv ( emptyTidyEnv )
  83. import Panic
  84. import GHC.Exts
  85. #endif
  86. import Module
  87. import Packages
  88. import RdrName
  89. import HsSyn
  90. import CoreSyn
  91. import StringBuffer
  92. import Parser
  93. import Lexer
  94. import SrcLoc
  95. import TcRnDriver
  96. import TcIface ( typecheckIface )
  97. import TcRnMonad
  98. import IfaceEnv ( initNameCache )
  99. import LoadIface ( ifaceStats, initExternalPackageState )
  100. import PrelInfo
  101. import MkIface
  102. import Desugar
  103. import SimplCore
  104. import TidyPgm
  105. import CorePrep
  106. import CoreToStg ( coreToStg )
  107. import qualified StgCmm ( codeGen )
  108. import StgSyn
  109. import CostCentre
  110. import ProfInit
  111. import TyCon
  112. import Name
  113. import SimplStg ( stg2stg )
  114. import qualified OldCmm as Old
  115. import qualified Cmm as New
  116. import CmmParse ( parseCmmFile )
  117. import CmmBuildInfoTables
  118. import CmmPipeline
  119. import CmmInfo
  120. import CmmCvt
  121. import CodeOutput
  122. import NameEnv ( emptyNameEnv )
  123. import NameSet ( emptyNameSet )
  124. import InstEnv
  125. import FamInstEnv
  126. import Fingerprint ( Fingerprint )
  127. import DynFlags
  128. import ErrUtils
  129. import Outputable
  130. import HscStats ( ppSourceStats )
  131. import HscTypes
  132. import MkExternalCore ( emitExternalCore )
  133. import FastString
  134. import UniqFM ( emptyUFM )
  135. import UniqSupply
  136. import Bag
  137. import Exception
  138. import qualified Stream
  139. import Stream (Stream)
  140. import Util
  141. import Data.List
  142. import Control.Monad
  143. import Data.Maybe
  144. import Data.IORef
  145. import System.FilePath as FilePath
  146. import System.Directory
  147. #include "HsVersions.h"
  148. {- **********************************************************************
  149. %* *
  150. Initialisation
  151. %* *
  152. %********************************************************************* -}
  153. newHscEnv :: DynFlags -> IO HscEnv
  154. newHscEnv dflags = do
  155. eps_var <- newIORef initExternalPackageState
  156. us <- mkSplitUniqSupply 'r'
  157. nc_var <- newIORef (initNameCache us knownKeyNames)
  158. fc_var <- newIORef emptyUFM
  159. mlc_var <- newIORef emptyModuleEnv
  160. return HscEnv { hsc_dflags = dflags,
  161. hsc_targets = [],
  162. hsc_mod_graph = [],
  163. hsc_IC = emptyInteractiveContext dflags,
  164. hsc_HPT = emptyHomePackageTable,
  165. hsc_EPS = eps_var,
  166. hsc_NC = nc_var,
  167. hsc_FC = fc_var,
  168. hsc_MLC = mlc_var,
  169. hsc_type_env_var = Nothing }
  170. knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
  171. knownKeyNames = -- where templateHaskellNames are defined
  172. map getName wiredInThings
  173. ++ basicKnownKeyNames
  174. #ifdef GHCI
  175. ++ templateHaskellNames
  176. #endif
  177. -- -----------------------------------------------------------------------------
  178. -- The Hsc monad: Passing an enviornment and warning state
  179. newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))
  180. instance Monad Hsc where
  181. return a = Hsc $ \_ w -> return (a, w)
  182. Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
  183. case k a of
  184. Hsc k' -> k' e w1
  185. instance MonadIO Hsc where
  186. liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)
  187. instance Functor Hsc where
  188. fmap f m = m >>= \a -> return $ f a
  189. runHsc :: HscEnv -> Hsc a -> IO a
  190. runHsc hsc_env (Hsc hsc) = do
  191. (a, w) <- hsc hsc_env emptyBag
  192. printOrThrowWarnings (hsc_dflags hsc_env) w
  193. return a
  194. -- A variant of runHsc that switches in the DynFlags from the
  195. -- InteractiveContext before running the Hsc computation.
  196. --
  197. runInteractiveHsc :: HscEnv -> Hsc a -> IO a
  198. runInteractiveHsc hsc_env =
  199. runHsc (hsc_env { hsc_dflags = ic_dflags (hsc_IC hsc_env) })
  200. getWarnings :: Hsc WarningMessages
  201. getWarnings = Hsc $ \_ w -> return (w, w)
  202. clearWarnings :: Hsc ()
  203. clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
  204. logWarnings :: WarningMessages -> Hsc ()
  205. logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
  206. getHscEnv :: Hsc HscEnv
  207. getHscEnv = Hsc $ \e w -> return (e, w)
  208. instance HasDynFlags Hsc where
  209. getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
  210. handleWarnings :: Hsc ()
  211. handleWarnings = do
  212. dflags <- getDynFlags
  213. w <- getWarnings
  214. liftIO $ printOrThrowWarnings dflags w
  215. clearWarnings
  216. -- | log warning in the monad, and if there are errors then
  217. -- throw a SourceError exception.
  218. logWarningsReportErrors :: Messages -> Hsc ()
  219. logWarningsReportErrors (warns,errs) = do
  220. logWarnings warns
  221. when (not $ isEmptyBag errs) $ throwErrors errs
  222. -- | Throw some errors.
  223. throwErrors :: ErrorMessages -> Hsc a
  224. throwErrors = liftIO . throwIO . mkSrcErr
  225. -- | Deal with errors and warnings returned by a compilation step
  226. --
  227. -- In order to reduce dependencies to other parts of the compiler, functions
  228. -- outside the "main" parts of GHC return warnings and errors as a parameter
  229. -- and signal success via by wrapping the result in a 'Maybe' type. This
  230. -- function logs the returned warnings and propagates errors as exceptions
  231. -- (of type 'SourceError').
  232. --
  233. -- This function assumes the following invariants:
  234. --
  235. -- 1. If the second result indicates success (is of the form 'Just x'),
  236. -- there must be no error messages in the first result.
  237. --
  238. -- 2. If there are no error messages, but the second result indicates failure
  239. -- there should be warnings in the first result. That is, if the action
  240. -- failed, it must have been due to the warnings (i.e., @-Werror@).
  241. ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
  242. ioMsgMaybe ioA = do
  243. ((warns,errs), mb_r) <- liftIO ioA
  244. logWarnings warns
  245. case mb_r of
  246. Nothing -> throwErrors errs
  247. Just r -> ASSERT( isEmptyBag errs ) return r
  248. -- | like ioMsgMaybe, except that we ignore error messages and return
  249. -- 'Nothing' instead.
  250. ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a)
  251. ioMsgMaybe' ioA = do
  252. ((warns,_errs), mb_r) <- liftIO $ ioA
  253. logWarnings warns
  254. return mb_r
  255. -- -----------------------------------------------------------------------------
  256. -- | Lookup things in the compiler's environment
  257. #ifdef GHCI
  258. hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
  259. hscTcRnLookupRdrName hsc_env0 rdr_name = runInteractiveHsc hsc_env0 $ do
  260. hsc_env <- getHscEnv
  261. ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
  262. #endif
  263. hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
  264. hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do
  265. hsc_env <- getHscEnv
  266. ioMsgMaybe' $ tcRnLookupName hsc_env name
  267. -- ignore errors: the only error we're likely to get is
  268. -- "name not found", and the Maybe in the return type
  269. -- is used to indicate that.
  270. hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst]))
  271. hscTcRnGetInfo hsc_env0 name = runInteractiveHsc hsc_env0 $ do
  272. hsc_env <- getHscEnv
  273. ioMsgMaybe' $ tcRnGetInfo hsc_env name
  274. #ifdef GHCI
  275. hscIsGHCiMonad :: HscEnv -> String -> IO Name
  276. hscIsGHCiMonad hsc_env name =
  277. let icntxt = hsc_IC hsc_env
  278. in runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env icntxt name
  279. hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
  280. hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
  281. hsc_env <- getHscEnv
  282. ioMsgMaybe $ getModuleInterface hsc_env mod
  283. -- -----------------------------------------------------------------------------
  284. -- | Rename some import declarations
  285. hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv
  286. hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do
  287. hsc_env <- getHscEnv
  288. ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
  289. #endif
  290. -- -----------------------------------------------------------------------------
  291. -- | parse a file, returning the abstract syntax
  292. hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
  293. hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary
  294. -- internal version, that doesn't fail due to -Werror
  295. hscParse' :: ModSummary -> Hsc HsParsedModule
  296. hscParse' mod_summary = do
  297. dflags <- getDynFlags
  298. let src_filename = ms_hspp_file mod_summary
  299. maybe_src_buf = ms_hspp_buf mod_summary
  300. -------------------------- Parser ----------------
  301. liftIO $ showPass dflags "Parser"
  302. {-# SCC "Parser" #-} do
  303. -- sometimes we already have the buffer in memory, perhaps
  304. -- because we needed to parse the imports out of it, or get the
  305. -- module name.
  306. buf <- case maybe_src_buf of
  307. Just b -> return b
  308. Nothing -> liftIO $ hGetStringBuffer src_filename
  309. let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
  310. case unP parseModule (mkPState dflags buf loc) of
  311. PFailed span err ->
  312. liftIO $ throwOneError (mkPlainErrMsg dflags span err)
  313. POk pst rdr_module -> do
  314. logWarningsReportErrors (getMessages pst)
  315. liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $
  316. ppr rdr_module
  317. liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $
  318. ppSourceStats False rdr_module
  319. -- To get the list of extra source files, we take the list
  320. -- that the parser gave us,
  321. -- - eliminate files beginning with '<'. gcc likes to use
  322. -- pseudo-filenames like "<built-in>" and "<command-line>"
  323. -- - normalise them (elimiante differences between ./f and f)
  324. -- - filter out the preprocessed source file
  325. -- - filter out anything beginning with tmpdir
  326. -- - remove duplicates
  327. -- - filter out the .hs/.lhs source filename if we have one
  328. --
  329. let n_hspp = FilePath.normalise src_filename
  330. srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`))
  331. $ filter (not . (== n_hspp))
  332. $ map FilePath.normalise
  333. $ filter (not . (isPrefixOf "<"))
  334. $ map unpackFS
  335. $ srcfiles pst
  336. srcs1 = case ml_hs_file (ms_location mod_summary) of
  337. Just f -> filter (/= FilePath.normalise f) srcs0
  338. Nothing -> srcs0
  339. -- sometimes we see source files from earlier
  340. -- preprocessing stages that cannot be found, so just
  341. -- filter them out:
  342. srcs2 <- liftIO $ filterM doesFileExist srcs1
  343. return HsParsedModule {
  344. hpm_module = rdr_module,
  345. hpm_src_files = srcs2
  346. }
  347. -- XXX: should this really be a Maybe X? Check under which circumstances this
  348. -- can become a Nothing and decide whether this should instead throw an
  349. -- exception/signal an error.
  350. type RenamedStuff =
  351. (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
  352. Maybe LHsDocString))
  353. -- | Rename and typecheck a module, additionally returning the renamed syntax
  354. hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
  355. -> IO (TcGblEnv, RenamedStuff)
  356. hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do
  357. tc_result <- tcRnModule' hsc_env mod_summary True rdr_module
  358. -- This 'do' is in the Maybe monad!
  359. let rn_info = do decl <- tcg_rn_decls tc_result
  360. let imports = tcg_rn_imports tc_result
  361. exports = tcg_rn_exports tc_result
  362. doc_hdr = tcg_doc_hdr tc_result
  363. return (decl,imports,exports,doc_hdr)
  364. return (tc_result, rn_info)
  365. -- wrapper around tcRnModule to handle safe haskell extras
  366. tcRnModule' :: HscEnv -> ModSummary -> Bool -> HsParsedModule
  367. -> Hsc TcGblEnv
  368. tcRnModule' hsc_env sum save_rn_syntax mod = do
  369. tcg_res <- {-# SCC "Typecheck-Rename" #-}
  370. ioMsgMaybe $
  371. tcRnModule hsc_env (ms_hsc_src sum) save_rn_syntax mod
  372. tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_res)
  373. dflags <- getDynFlags
  374. -- end of the Safe Haskell line, how to respond to user?
  375. if not (safeHaskellOn dflags) || (safeInferOn dflags && not tcSafeOK)
  376. -- if safe haskell off or safe infer failed, wipe trust
  377. then wipeTrust tcg_res emptyBag
  378. -- module safe, throw warning if needed
  379. else do
  380. tcg_res' <- hscCheckSafeImports tcg_res
  381. safe <- liftIO $ readIORef (tcg_safeInfer tcg_res')
  382. when (safe && wopt Opt_WarnSafe dflags)
  383. (logWarnings $ unitBag $
  384. mkPlainWarnMsg dflags (warnSafeOnLoc dflags) $ errSafe tcg_res')
  385. return tcg_res'
  386. where
  387. pprMod t = ppr $ moduleName $ tcg_mod t
  388. errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
  389. -- | Convert a typechecked module to Core
  390. hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
  391. hscDesugar hsc_env mod_summary tc_result =
  392. runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
  393. hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
  394. hscDesugar' mod_location tc_result = do
  395. hsc_env <- getHscEnv
  396. r <- ioMsgMaybe $
  397. {-# SCC "deSugar" #-}
  398. deSugar hsc_env mod_location tc_result
  399. -- always check -Werror after desugaring, this is the last opportunity for
  400. -- warnings to arise before the backend.
  401. handleWarnings
  402. return r
  403. -- | Make a 'ModIface' from the results of typechecking. Used when
  404. -- not optimising, and the interface doesn't need to contain any
  405. -- unfoldings or other cross-module optimisation info.
  406. -- ToDo: the old interface is only needed to get the version numbers,
  407. -- we should use fingerprint versions instead.
  408. makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
  409. -> IO (ModIface,Bool)
  410. makeSimpleIface hsc_env maybe_old_iface tc_result details = runHsc hsc_env $ do
  411. safe_mode <- hscGetSafeMode tc_result
  412. ioMsgMaybe $ do
  413. mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) safe_mode
  414. details tc_result
  415. -- | Make a 'ModDetails' from the results of typechecking. Used when
  416. -- typechecking only, as opposed to full compilation.
  417. makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
  418. makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
  419. {- **********************************************************************
  420. %* *
  421. The main compiler pipeline
  422. %* *
  423. %********************************************************************* -}
  424. {-
  425. --------------------------------
  426. The compilation proper
  427. --------------------------------
  428. It's the task of the compilation proper to compile Haskell, hs-boot and core
  429. files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all
  430. (the module is still parsed and type-checked. This feature is mostly used by
  431. IDE's and the likes). Compilation can happen in either 'one-shot', 'batch',
  432. 'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch'
  433. mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
  434. targets byte-code.
  435. The modes are kept separate because of their different types and meanings:
  436. * In 'one-shot' mode, we're only compiling a single file and can therefore
  437. discard the new ModIface and ModDetails. This is also the reason it only
  438. targets hard-code; compiling to byte-code or nothing doesn't make sense when
  439. we discard the result.
  440. * 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
  441. and ModDetails. 'Batch' mode doesn't target byte-code since that require us to
  442. return the newly compiled byte-code.
  443. * 'Nothing' mode has exactly the same type as 'batch' mode but they're still
  444. kept separate. This is because compiling to nothing is fairly special: We
  445. don't output any interface files, we don't run the simplifier and we don't
  446. generate any code.
  447. * 'Interactive' mode is similar to 'batch' mode except that we return the
  448. compiled byte-code together with the ModIface and ModDetails.
  449. Trying to compile a hs-boot file to byte-code will result in a run-time error.
  450. This is the only thing that isn't caught by the type-system.
  451. -}
  452. -- | Status of a compilation to hard-code or nothing.
  453. data HscStatus' a
  454. = HscNoRecomp
  455. | HscRecomp
  456. (Maybe FilePath) -- Has stub files. This is a hack. We can't compile
  457. -- C files here since it's done in DriverPipeline.
  458. -- For now we just return True if we want the caller
  459. -- to compile them for us.
  460. a
  461. -- This is a bit ugly. Since we use a typeclass below and would like to avoid
  462. -- functional dependencies, we have to parameterise the typeclass over the
  463. -- result type. Therefore we need to artificially distinguish some types. We do
  464. -- this by adding type tags which will simply be ignored by the caller.
  465. type HscStatus = HscStatus' ()
  466. type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
  467. -- INVARIANT: result is @Nothing@ <=> input was a boot file
  468. type OneShotResult = HscStatus
  469. type BatchResult = (HscStatus, ModIface, ModDetails)
  470. type NothingResult = (HscStatus, ModIface, ModDetails)
  471. type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
  472. -- ToDo: The old interface and module index are only using in 'batch' and
  473. -- 'interactive' mode. They should be removed from 'oneshot' mode.
  474. type Compiler result = HscEnv
  475. -> ModSummary
  476. -> SourceModified
  477. -> Maybe ModIface -- Old interface, if available
  478. -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
  479. -> IO result
  480. data HsCompiler a = HsCompiler {
  481. -- | Called when no recompilation is necessary.
  482. hscNoRecomp :: ModIface
  483. -> Hsc a,
  484. -- | Called to recompile the module.
  485. hscRecompile :: ModSummary -> Maybe Fingerprint
  486. -> Hsc a,
  487. hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint
  488. -> Hsc a,
  489. -- | Code generation for Boot modules.
  490. hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint
  491. -> Hsc a,
  492. -- | Code generation for normal modules.
  493. hscGenOutput :: ModGuts -> ModSummary -> Maybe Fingerprint
  494. -> Hsc a
  495. }
  496. genericHscCompile :: HsCompiler a
  497. -> (HscEnv -> Maybe (Int,Int) -> RecompileRequired -> ModSummary -> IO ())
  498. -> HscEnv -> ModSummary -> SourceModified
  499. -> Maybe ModIface -> Maybe (Int, Int)
  500. -> IO a
  501. genericHscCompile compiler hscMessage hsc_env
  502. mod_summary source_modified
  503. mb_old_iface0 mb_mod_index
  504. = do
  505. (recomp_reqd, mb_checked_iface)
  506. <- {-# SCC "checkOldIface" #-}
  507. checkOldIface hsc_env mod_summary
  508. source_modified mb_old_iface0
  509. -- save the interface that comes back from checkOldIface.
  510. -- In one-shot mode we don't have the old iface until this
  511. -- point, when checkOldIface reads it from the disk.
  512. let mb_old_hash = fmap mi_iface_hash mb_checked_iface
  513. let skip iface = do
  514. hscMessage hsc_env mb_mod_index UpToDate mod_summary
  515. runHsc hsc_env $ hscNoRecomp compiler iface
  516. compile reason = do
  517. hscMessage hsc_env mb_mod_index reason mod_summary
  518. runHsc hsc_env $ hscRecompile compiler mod_summary mb_old_hash
  519. stable = case source_modified of
  520. SourceUnmodifiedAndStable -> True
  521. _ -> False
  522. -- If the module used TH splices when it was last compiled,
  523. -- then the recompilation check is not accurate enough (#481)
  524. -- and we must ignore it. However, if the module is stable
  525. -- (none of the modules it depends on, directly or indirectly,
  526. -- changed), then we *can* skip recompilation. This is why
  527. -- the SourceModified type contains SourceUnmodifiedAndStable,
  528. -- and it's pretty important: otherwise ghc --make would
  529. -- always recompile TH modules, even if nothing at all has
  530. -- changed. Stability is just the same check that make is
  531. -- doing for us in one-shot mode.
  532. case mb_checked_iface of
  533. Just iface | not (recompileRequired recomp_reqd) ->
  534. if mi_used_th iface && not stable
  535. then compile (RecompBecause "TH")
  536. else skip iface
  537. _otherwise ->
  538. compile recomp_reqd
  539. hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
  540. hscCheckRecompBackend compiler tc_result hsc_env mod_summary
  541. source_modified mb_old_iface _m_of_n
  542. = do
  543. (recomp_reqd, mb_checked_iface)
  544. <- {-# SCC "checkOldIface" #-}
  545. checkOldIface hsc_env mod_summary
  546. source_modified mb_old_iface
  547. let mb_old_hash = fmap mi_iface_hash mb_checked_iface
  548. case mb_checked_iface of
  549. Just iface | not (recompileRequired recomp_reqd)
  550. -> runHsc hsc_env $
  551. hscNoRecomp compiler
  552. iface{ mi_globals = Just (tcg_rdr_env tc_result) }
  553. _otherwise
  554. -> runHsc hsc_env $
  555. hscBackend compiler tc_result mod_summary mb_old_hash
  556. genericHscRecompile :: HsCompiler a
  557. -> ModSummary -> Maybe Fingerprint
  558. -> Hsc a
  559. genericHscRecompile compiler mod_summary mb_old_hash
  560. | ExtCoreFile <- ms_hsc_src mod_summary =
  561. panic "GHC does not currently support reading External Core files"
  562. | otherwise = do
  563. tc_result <- hscFileFrontEnd mod_summary
  564. hscBackend compiler tc_result mod_summary mb_old_hash
  565. genericHscBackend :: HsCompiler a
  566. -> TcGblEnv -> ModSummary -> Maybe Fingerprint
  567. -> Hsc a
  568. genericHscBackend compiler tc_result mod_summary mb_old_hash
  569. | HsBootFile <- ms_hsc_src mod_summary =
  570. hscGenBootOutput compiler tc_result mod_summary mb_old_hash
  571. | otherwise = do
  572. guts <- hscDesugar' (ms_location mod_summary) tc_result
  573. hscGenOutput compiler guts mod_summary mb_old_hash
  574. compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a
  575. compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ =
  576. runHsc hsc_env $ hscBackend comp tcg ms' Nothing
  577. --------------------------------------------------------------
  578. -- Compilers
  579. --------------------------------------------------------------
  580. hscOneShotCompiler :: HsCompiler OneShotResult
  581. hscOneShotCompiler = HsCompiler {
  582. hscNoRecomp = \_old_iface -> do
  583. hsc_env <- getHscEnv
  584. liftIO $ dumpIfaceStats hsc_env
  585. return HscNoRecomp
  586. , hscRecompile = genericHscRecompile hscOneShotCompiler
  587. , hscBackend = \tc_result mod_summary mb_old_hash -> do
  588. dflags <- getDynFlags
  589. case hscTarget dflags of
  590. HscNothing -> return (HscRecomp Nothing ())
  591. _otherw -> genericHscBackend hscOneShotCompiler
  592. tc_result mod_summary mb_old_hash
  593. , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
  594. (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
  595. hscWriteIface iface changed mod_summary
  596. return (HscRecomp Nothing ())
  597. , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
  598. guts <- hscSimplify' guts0
  599. (iface, changed, _details, cgguts) <- hscNormalIface guts mb_old_iface
  600. hscWriteIface iface changed mod_summary
  601. hasStub <- hscGenHardCode cgguts mod_summary
  602. return (HscRecomp hasStub ())
  603. }
  604. -- Compile Haskell, boot and extCore in OneShot mode.
  605. hscCompileOneShot :: Compiler OneShotResult
  606. hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
  607. = do
  608. -- One-shot mode needs a knot-tying mutable variable for interface
  609. -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
  610. type_env_var <- newIORef emptyNameEnv
  611. let mod = ms_mod mod_summary
  612. hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
  613. genericHscCompile hscOneShotCompiler
  614. oneShotMsg hsc_env' mod_summary src_changed
  615. mb_old_iface mb_i_of_n
  616. hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult
  617. hscOneShotBackendOnly = compilerBackend hscOneShotCompiler
  618. --------------------------------------------------------------
  619. hscBatchCompiler :: HsCompiler BatchResult
  620. hscBatchCompiler = HsCompiler {
  621. hscNoRecomp = \iface -> do
  622. details <- genModDetails iface
  623. return (HscNoRecomp, iface, details)
  624. , hscRecompile = genericHscRecompile hscBatchCompiler
  625. , hscBackend = genericHscBackend hscBatchCompiler
  626. , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
  627. (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface
  628. hscWriteIface iface changed mod_summary
  629. return (HscRecomp Nothing (), iface, details)
  630. , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
  631. guts <- hscSimplify' guts0
  632. (iface, changed, details, cgguts) <- hscNormalIface guts mb_old_iface
  633. hscWriteIface iface changed mod_summary
  634. hasStub <- hscGenHardCode cgguts mod_summary
  635. return (HscRecomp hasStub (), iface, details)
  636. }
  637. -- | Compile Haskell, boot and extCore in batch mode.
  638. hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
  639. hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
  640. hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult
  641. hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler
  642. --------------------------------------------------------------
  643. hscInteractiveCompiler :: HsCompiler InteractiveResult
  644. hscInteractiveCompiler = HsCompiler {
  645. hscNoRecomp = \iface -> do
  646. details <- genModDetails iface
  647. return (HscNoRecomp, iface, details)
  648. , hscRecompile = genericHscRecompile hscInteractiveCompiler
  649. , hscBackend = genericHscBackend hscInteractiveCompiler
  650. , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
  651. (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
  652. return (HscRecomp Nothing Nothing, iface, details)
  653. , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
  654. guts <- hscSimplify' guts0
  655. (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface
  656. hscInteractive (iface, details, cgguts) mod_summary
  657. }
  658. -- Compile Haskell, extCore to bytecode.
  659. hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
  660. hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg
  661. hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult
  662. hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler
  663. --------------------------------------------------------------
  664. hscNothingCompiler :: HsCompiler NothingResult
  665. hscNothingCompiler = HsCompiler {
  666. hscNoRecomp = \iface -> do
  667. details <- genModDetails iface
  668. return (HscNoRecomp, iface, details)
  669. , hscRecompile = genericHscRecompile hscNothingCompiler
  670. , hscBackend = \tc_result _mod_summary mb_old_iface -> do
  671. handleWarnings
  672. (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
  673. return (HscRecomp Nothing (), iface, details)
  674. , hscGenBootOutput = \_ _ _ ->
  675. panic "hscCompileNothing: hscGenBootOutput should not be called"
  676. , hscGenOutput = \_ _ _ ->
  677. panic "hscCompileNothing: hscGenOutput should not be called"
  678. }
  679. -- Type-check Haskell and .hs-boot only (no external core)
  680. hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
  681. hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
  682. hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult
  683. hscNothingBackendOnly = compilerBackend hscNothingCompiler
  684. --------------------------------------------------------------
  685. -- NoRecomp handlers
  686. --------------------------------------------------------------
  687. genModDetails :: ModIface -> Hsc ModDetails
  688. genModDetails old_iface
  689. = do
  690. hsc_env <- getHscEnv
  691. new_details <- {-# SCC "tcRnIface" #-}
  692. liftIO $ initIfaceCheck hsc_env (typecheckIface old_iface)
  693. liftIO $ dumpIfaceStats hsc_env
  694. return new_details
  695. --------------------------------------------------------------
  696. -- Progress displayers.
  697. --------------------------------------------------------------
  698. oneShotMsg :: HscEnv -> Maybe (Int,Int) -> RecompileRequired -> ModSummary
  699. -> IO ()
  700. oneShotMsg hsc_env _mb_mod_index recomp _mod_summary =
  701. case recomp of
  702. UpToDate ->
  703. compilationProgressMsg (hsc_dflags hsc_env) $
  704. "compilation IS NOT required"
  705. _other ->
  706. return ()
  707. batchMsg :: HscEnv -> Maybe (Int,Int) -> RecompileRequired -> ModSummary
  708. -> IO ()
  709. batchMsg hsc_env mb_mod_index recomp mod_summary =
  710. case recomp of
  711. MustCompile -> showMsg "Compiling " ""
  712. UpToDate
  713. | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping " ""
  714. | otherwise -> return ()
  715. RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
  716. where
  717. dflags = hsc_dflags hsc_env
  718. showMsg msg reason =
  719. compilationProgressMsg dflags $
  720. (showModuleIndex mb_mod_index ++
  721. msg ++ showModMsg dflags (hscTarget dflags)
  722. (recompileRequired recomp) mod_summary)
  723. ++ reason
  724. --------------------------------------------------------------
  725. -- FrontEnds
  726. --------------------------------------------------------------
  727. hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
  728. hscFileFrontEnd mod_summary = do
  729. hpm <- hscParse' mod_summary
  730. hsc_env <- getHscEnv
  731. tcg_env <- tcRnModule' hsc_env mod_summary False hpm
  732. return tcg_env
  733. --------------------------------------------------------------
  734. -- Safe Haskell
  735. --------------------------------------------------------------
  736. -- Note [Safe Haskell Trust Check]
  737. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  738. -- Safe Haskell checks that an import is trusted according to the following
  739. -- rules for an import of module M that resides in Package P:
  740. --
  741. -- * If M is recorded as Safe and all its trust dependencies are OK
  742. -- then M is considered safe.
  743. -- * If M is recorded as Trustworthy and P is considered trusted and
  744. -- all M's trust dependencies are OK then M is considered safe.
  745. --
  746. -- By trust dependencies we mean that the check is transitive. So if
  747. -- a module M that is Safe relies on a module N that is trustworthy,
  748. -- importing module M will first check (according to the second case)
  749. -- that N is trusted before checking M is trusted.
  750. --
  751. -- This is a minimal description, so please refer to the user guide
  752. -- for more details. The user guide is also considered the authoritative
  753. -- source in this matter, not the comments or code.
  754. -- Note [Safe Haskell Inference]
  755. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  756. -- Safe Haskell does Safe inference on modules that don't have any specific
  757. -- safe haskell mode flag. The basic aproach to this is:
  758. -- * When deciding if we need to do a Safe language check, treat
  759. -- an unmarked module as having -XSafe mode specified.
  760. -- * For checks, don't throw errors but return them to the caller.
  761. -- * Caller checks if there are errors:
  762. -- * For modules explicitly marked -XSafe, we throw the errors.
  763. -- * For unmarked modules (inference mode), we drop the errors
  764. -- and mark the module as being Unsafe.
  765. -- | Check that the safe imports of the module being compiled are valid.
  766. -- If not we either issue a compilation error if the module is explicitly
  767. -- using Safe Haskell, or mark the module as unsafe if we're in safe
  768. -- inference mode.
  769. hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv
  770. hscCheckSafeImports tcg_env = do
  771. dflags <- getDynFlags
  772. tcg_env' <- checkSafeImports dflags tcg_env
  773. case safeLanguageOn dflags of
  774. True -> do
  775. -- we nuke user written RULES in -XSafe
  776. logWarnings $ warns dflags (tcg_rules tcg_env')
  777. return tcg_env' { tcg_rules = [] }
  778. False
  779. -- user defined RULES, so not safe or already unsafe
  780. | safeInferOn dflags && not (null $ tcg_rules tcg_env') ||
  781. safeHaskell dflags == Sf_None
  782. -> wipeTrust tcg_env' $ warns dflags (tcg_rules tcg_env')
  783. -- trustworthy OR safe inferred with no RULES
  784. | otherwise
  785. -> return tcg_env'
  786. where
  787. warns dflags rules = listToBag $ map (warnRules dflags) rules
  788. warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) =
  789. mkPlainWarnMsg dflags loc $
  790. text "Rule \"" <> ftext n <> text "\" ignored" $+$
  791. text "User defined rules are disabled under Safe Haskell"
  792. -- | Validate that safe imported modules are actually safe. For modules in the
  793. -- HomePackage (the package the module we are compiling in resides) this just
  794. -- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules
  795. -- that reside in another package we also must check that the external pacakge
  796. -- is trusted. See the Note [Safe Haskell Trust Check] above for more
  797. -- information.
  798. --
  799. -- The code for this is quite tricky as the whole algorithm is done in a few
  800. -- distinct phases in different parts of the code base. See
  801. -- RnNames.rnImportDecl for where package trust dependencies for a module are
  802. -- collected and unioned. Specifically see the Note [RnNames . Tracking Trust
  803. -- Transitively] and the Note [RnNames . Trust Own Package].
  804. checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv
  805. checkSafeImports dflags tcg_env
  806. = do
  807. -- We want to use the warning state specifically for detecting if safe
  808. -- inference has failed, so store and clear any existing warnings.
  809. oldErrs <- getWarnings
  810. clearWarnings
  811. imps <- mapM condense imports'
  812. pkgs <- mapM checkSafe imps
  813. -- grab any safe haskell specific errors and restore old warnings
  814. errs <- getWarnings
  815. clearWarnings
  816. logWarnings oldErrs
  817. -- See the Note [Safe Haskell Inference]
  818. case (not $ isEmptyBag errs) of
  819. -- We have errors!
  820. True ->
  821. -- did we fail safe inference or fail -XSafe?
  822. case safeInferOn dflags of
  823. True -> wipeTrust tcg_env errs
  824. False -> liftIO . throwIO . mkSrcErr $ errs
  825. -- All good matey!
  826. False -> do
  827. when (packageTrustOn dflags) $ checkPkgTrust dflags pkg_reqs
  828. -- add in trusted package requirements for this module
  829. let new_trust = emptyImportAvails { imp_trust_pkgs = catMaybes pkgs }
  830. return tcg_env { tcg_imports = imp_info `plusImportAvails` new_trust }
  831. where
  832. imp_info = tcg_imports tcg_env -- ImportAvails
  833. imports = imp_mods imp_info -- ImportedMods
  834. imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])
  835. pkg_reqs = imp_trust_pkgs imp_info -- [PackageId]
  836. condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport)
  837. condense (_, []) = panic "HscMain.condense: Pattern match failure!"
  838. condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs
  839. -- we turn all imports into safe ones when
  840. -- inference mode is on.
  841. let s' = if safeInferOn dflags then True else s
  842. return (m, l, s')
  843. -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
  844. cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
  845. cond' v1@(m1,_,l1,s1) (_,_,_,s2)
  846. | s1 /= s2
  847. = throwErrors $ unitBag $ mkPlainErrMsg dflags l1
  848. (text "Module" <+> ppr m1 <+>
  849. (text $ "is imported both as a safe and unsafe import!"))
  850. | otherwise
  851. = return v1
  852. -- easier interface to work with
  853. checkSafe (_, _, False) = return Nothing
  854. checkSafe (m, l, True ) = fst `fmap` hscCheckSafe' dflags m l
  855. -- | Check that a module is safe to import.
  856. --
  857. -- We return True to indicate the import is safe and False otherwise
  858. -- although in the False case an exception may be thrown first.
  859. hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO Bool
  860. hscCheckSafe hsc_env m l = runHsc hsc_env $ do
  861. dflags <- getDynFlags
  862. pkgs <- snd `fmap` hscCheckSafe' dflags m l
  863. when (packageTrustOn dflags) $ checkPkgTrust dflags pkgs
  864. errs <- getWarnings
  865. return $ isEmptyBag errs
  866. -- | Return if a module is trusted and the pkgs it depends on to be trusted.
  867. hscGetSafe :: HscEnv -> Module -> SrcSpan -> IO (Bool, [PackageId])
  868. hscGetSafe hsc_env m l = runHsc hsc_env $ do
  869. dflags <- getDynFlags
  870. (self, pkgs) <- hscCheckSafe' dflags m l
  871. good <- isEmptyBag `fmap` getWarnings
  872. clearWarnings -- don't want them printed...
  873. let pkgs' | Just p <- self = p:pkgs
  874. | otherwise = pkgs
  875. return (good, pkgs')
  876. -- | Is a module trusted? If not, throw or log errors depending on the type.
  877. -- Return (regardless of trusted or not) if the trust type requires the modules
  878. -- own package be trusted and a list of other packages required to be trusted
  879. -- (these later ones haven't been checked) but the own package trust has been.
  880. hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageId, [PackageId])
  881. hscCheckSafe' dflags m l = do
  882. (tw, pkgs) <- isModSafe m l
  883. case tw of
  884. False -> return (Nothing, pkgs)
  885. True | isHomePkg m -> return (Nothing, pkgs)
  886. | otherwise -> return (Just $ modulePackageId m, pkgs)
  887. where
  888. isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageId])
  889. isModSafe m l = do
  890. iface <- lookup' m
  891. case iface of
  892. -- can't load iface to check trust!
  893. Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l
  894. $ text "Can't load the interface file for" <+> ppr m
  895. <> text ", to check that it can be safely imported"
  896. -- got iface, check trust
  897. Just iface' ->
  898. let trust = getSafeMode $ mi_trust iface'
  899. trust_own_pkg = mi_trust_pkg iface'
  900. -- check module is trusted
  901. safeM = trust `elem` [Sf_SafeInferred, Sf_Safe, Sf_Trustworthy]
  902. -- check package is trusted
  903. safeP = packageTrusted trust trust_own_pkg m
  904. -- pkg trust reqs
  905. pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface'
  906. -- General errors we throw but Safe errors we log
  907. errs = case (safeM, safeP) of
  908. (True, True ) -> emptyBag
  909. (True, False) -> pkgTrustErr
  910. (False, _ ) -> modTrustErr
  911. in do
  912. logWarnings errs
  913. return (trust == Sf_Trustworthy, pkgRs)
  914. where
  915. pkgTrustErr = unitBag $ mkPlainErrMsg dflags l $
  916. sep [ ppr (moduleName m)
  917. <> text ": Can't be safely imported!"
  918. , text "The package (" <> ppr (modulePackageId m)
  919. <> text ") the module resides in isn't trusted."
  920. ]
  921. modTrustErr = unitBag $ mkPlainErrMsg dflags l $
  922. sep [ ppr (moduleName m)
  923. <> text ": Can't be safely imported!"
  924. , text "The module itself isn't safe." ]
  925. -- | Check the package a module resides in is trusted. Safe compiled
  926. -- modules are trusted without requiring that their package is trusted. For
  927. -- trustworthy modules, modules in the home package are trusted but
  928. -- otherwise we check the package trust flag.
  929. packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool
  930. packageTrusted Sf_None _ _ = False -- shouldn't hit these cases
  931. packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness.
  932. packageTrusted _ _ _
  933. | not (packageTrustOn dflags) = True
  934. packageTrusted Sf_Safe False _ = True
  935. packageTrusted Sf_SafeInferred False _ = True
  936. packageTrusted _ _ m
  937. | isHomePkg m = True
  938. | otherwise = trusted $ getPackageDetails (pkgState dflags)
  939. (modulePackageId m)
  940. lookup' :: Module -> Hsc (Maybe ModIface)
  941. lookup' m = do
  942. hsc_env <- getHscEnv
  943. hsc_eps <- liftIO $ hscEPS hsc_env
  944. let pkgIfaceT = eps_PIT hsc_eps
  945. homePkgT = hsc_HPT hsc_env
  946. iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m
  947. #ifdef GHCI
  948. -- the 'lookupIfaceByModule' method will always fail when calling from GHCi
  949. -- as the compiler hasn't filled in the various module tables
  950. -- so we need to call 'getModuleInterface' to load from disk
  951. iface' <- case iface of
  952. Just _ -> return iface
  953. Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m)
  954. return iface'
  955. #else
  956. return iface
  957. #endif
  958. isHomePkg :: Module -> Bool
  959. isHomePkg m
  960. | thisPackage dflags == modulePackageId m = True
  961. | otherwise = False
  962. -- | Check the list of packages are trusted.
  963. checkPkgTrust :: DynFlags -> [PackageId] -> Hsc ()
  964. checkPkgTrust dflags pkgs =
  965. case errors of
  966. [] -> return ()
  967. _ -> (liftIO . throwIO . mkSrcErr . listToBag) errors
  968. where
  969. errors = catMaybes $ map go pkgs
  970. go pkg
  971. | trusted $ getPackageDetails (pkgState dflags) pkg
  972. = Nothing
  973. | otherwise
  974. = Just $ mkPlainErrMsg dflags noSrcSpan
  975. $ text "The package (" <> ppr pkg <> text ") is required" <>
  976. text " to be trusted but it isn't!"
  977. -- | Set module to unsafe and wipe trust information.
  978. --
  979. -- Make sure to call this method to set a module to inferred unsafe,
  980. -- it should be a central and single failure method.
  981. wipeTrust :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv
  982. wipeTrust tcg_env whyUnsafe = do
  983. dflags <- getDynFlags
  984. when (wopt Opt_WarnUnsafe dflags)
  985. (logWarnings $ unitBag $
  986. mkPlainWarnMsg dflags (warnUnsafeOnLoc dflags) (whyUnsafe' dflags))
  987. liftIO $ writeIORef (tcg_safeInfer tcg_env) False
  988. return $ tcg_env { tcg_imports = wiped_trust }
  989. where
  990. wiped_trust = (tcg_imports tcg_env) { imp_trust_pkgs = [] }
  991. pprMod = ppr $ moduleName $ tcg_mod tcg_env
  992. whyUnsafe' df = vcat [ quotes pprMod <+> text "has been inferred as unsafe!"
  993. , text "Reason:"
  994. , nest 4 $ (vcat $ badFlags df) $+$
  995. (vcat $ pprErrMsgBagWithLoc whyUnsafe)
  996. ]
  997. badFlags df = concat $ map (badFlag df) unsafeFlags
  998. badFlag df (str,loc,on,_)
  999. | on df = [mkLocMessage SevOutput (loc df) $
  1000. text str <+> text "is not allowed in Safe Haskell"]
  1001. | otherwise = []
  1002. -- | Figure out the final correct safe haskell mode
  1003. hscGetSafeMode :: TcGblEnv -> Hsc SafeHaskellMode
  1004. hscGetSafeMode tcg_env = do
  1005. dflags <- getDynFlags
  1006. liftIO $ finalSafeMode dflags tcg_env
  1007. --------------------------------------------------------------
  1008. -- Simplifiers
  1009. --------------------------------------------------------------
  1010. hscSimplify :: HscEnv -> ModGuts -> IO ModGuts
  1011. hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts
  1012. hscSimplify' :: ModGuts -> Hsc ModGuts
  1013. hscSimplify' ds_result = do
  1014. hsc_env <- getHscEnv
  1015. {-# SCC "Core2Core" #-}
  1016. liftIO $ core2core hsc_env ds_result
  1017. --------------------------------------------------------------
  1018. -- Interface generators
  1019. --------------------------------------------------------------
  1020. hscSimpleIface :: TcGblEnv
  1021. -> Maybe Fingerprint
  1022. -> Hsc (ModIface, Bool, ModDetails)
  1023. hscSimpleIface tc_result mb_old_iface = do
  1024. hsc_env <- getHscEnv
  1025. details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
  1026. safe_mode <- hscGetSafeMode tc_result
  1027. (new_iface, no_change)
  1028. <- {-# SCC "MkFinalIface" #-}
  1029. ioMsgMaybe $
  1030. mkIfaceTc hsc_env mb_old_iface safe_mode details tc_result
  1031. -- And the answer is ...
  1032. liftIO $ dumpIfaceStats hsc_env
  1033. return (new_iface, no_change, details)
  1034. hscNormalIface :: ModGuts
  1035. -> Maybe Fingerprint
  1036. -> Hsc (ModIface, Bool, ModDetails, CgGuts)
  1037. hscNormalIface simpl_result mb_old_iface = do
  1038. hsc_env <- getHscEnv
  1039. (cg_guts, details) <- {-# SCC "CoreTidy" #-}
  1040. liftIO $ tidyProgram hsc_env simpl_result
  1041. -- BUILD THE NEW ModIface and ModDetails
  1042. -- and emit external core if necessary
  1043. -- This has to happen *after* code gen so that the back-end
  1044. -- info has been set. Not yet clear if it matters waiting
  1045. -- until after code output
  1046. (new_iface, no_change)
  1047. <- {-# SCC "MkFinalIface" #-}
  1048. ioMsgMaybe $
  1049. mkIface hsc_env mb_old_iface details simpl_result
  1050. -- Emit external core
  1051. -- This should definitely be here and not after CorePrep,
  1052. -- because CorePrep produces unqualified constructor wrapper declarations,
  1053. -- so its output isn't valid External Core (without some preprocessing).
  1054. liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts
  1055. liftIO $ dumpIfaceStats hsc_env
  1056. -- Return the prepared code.
  1057. return (new_iface, no_change, details, cg_guts)
  1058. --------------------------------------------------------------
  1059. -- BackEnd combinators
  1060. --------------------------------------------------------------
  1061. hscWriteIface :: ModIface -> Bool -> ModSummary -> Hsc ()
  1062. hscWriteIface iface no_change mod_summary = do
  1063. dflags <- getDynFlags
  1064. unless no_change $
  1065. {-# SCC "writeIface" #-}
  1066. liftIO $ writeIfaceFile dflags (ms_location mod_summary) iface
  1067. -- | Compile to hard-code.
  1068. hscGenHardCode :: CgGuts -> ModSummary
  1069. -> Hsc (Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f
  1070. hscGenHardCode cgguts mod_summary = do
  1071. hsc_env <- getHscEnv
  1072. liftIO $ do
  1073. let CgGuts{ -- This is the last use of the ModGuts in a compilation.
  1074. -- From now on, we just use the bits we need.
  1075. cg_module = this_mod,
  1076. cg_binds = core_binds,
  1077. cg_tycons = tycons,
  1078. cg_foreign = foreign_stubs0,
  1079. cg_dep_pkgs = dependencies,
  1080. cg_hpc_info = hpc_info } = cgguts
  1081. dflags = hsc_dflags hsc_env
  1082. location = ms_location mod_summary
  1083. data_tycons = filter isDataTyCon tycons
  1084. -- cg_tycons includes newtypes, for the benefit of External Core,

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