PageRenderTime 59ms CodeModel.GetById 15ms 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
  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,
  1085. -- but we don't generate any code for newtypes
  1086. -------------------
  1087. -- PREPARE FOR CODE GENERATION
  1088. -- Do saturation and convert to A-normal form
  1089. prepd_binds <- {-# SCC "CorePrep" #-}
  1090. corePrepPgm dflags hsc_env core_binds data_tycons ;
  1091. ----------------- Convert to STG ------------------
  1092. (stg_binds, cost_centre_info)
  1093. <- {-# SCC "CoreToStg" #-}
  1094. myCoreToStg dflags this_mod prepd_binds
  1095. let prof_init = profilingInitCode this_mod cost_centre_info
  1096. foreign_stubs = foreign_stubs0 `appendStubC` prof_init
  1097. ------------------ Code generation ------------------
  1098. cmms <- {-# SCC "NewCodeGen" #-}
  1099. tryNewCodeGen hsc_env this_mod data_tycons
  1100. cost_centre_info
  1101. stg_binds hpc_info
  1102. ------------------ Code output -----------------------
  1103. rawcmms0 <- {-# SCC "cmmToRawCmm" #-}
  1104. cmmToRawCmm dflags cmms
  1105. let dump a = do dumpIfSet_dyn dflags Opt_D_dump_raw_cmm "Raw Cmm"
  1106. (ppr a)
  1107. return a
  1108. rawcmms1 = Stream.mapM dump rawcmms0
  1109. (_stub_h_exists, stub_c_exists)
  1110. <- {-# SCC "codeOutput" #-}
  1111. codeOutput dflags this_mod location foreign_stubs
  1112. dependencies rawcmms1
  1113. return stub_c_exists
  1114. hscInteractive :: (ModIface, ModDetails, CgGuts)
  1115. -> ModSummary
  1116. -> Hsc (InteractiveStatus, ModIface, ModDetails)
  1117. #ifdef GHCI
  1118. hscInteractive (iface, details, cgguts) mod_summary = do
  1119. dflags <- getDynFlags
  1120. let CgGuts{ -- This is the last use of the ModGuts in a compilation.
  1121. -- From now on, we just use the bits we need.
  1122. cg_module = this_mod,
  1123. cg_binds = core_binds,
  1124. cg_tycons = tycons,
  1125. cg_foreign = foreign_stubs,
  1126. cg_modBreaks = mod_breaks } = cgguts
  1127. location = ms_location mod_summary
  1128. data_tycons = filter isDataTyCon tycons
  1129. -- cg_tycons includes newtypes, for the benefit of External Core,
  1130. -- but we don't generate any code for newtypes
  1131. -------------------
  1132. -- PREPARE FOR CODE GENERATION
  1133. -- Do saturation and convert to A-normal form
  1134. hsc_env <- getHscEnv
  1135. prepd_binds <- {-# SCC "CorePrep" #-}
  1136. liftIO $ corePrepPgm dflags hsc_env core_binds data_tycons
  1137. ----------------- Generate byte code ------------------
  1138. comp_bc <- liftIO $ byteCodeGen dflags this_mod prepd_binds
  1139. data_tycons mod_breaks
  1140. ------------------ Create f-x-dynamic C-side stuff ---
  1141. (_istub_h_exists, istub_c_exists)
  1142. <- liftIO $ outputForeignStubs dflags this_mod
  1143. location foreign_stubs
  1144. return (HscRecomp istub_c_exists (Just (comp_bc, mod_breaks))
  1145. , iface, details)
  1146. #else
  1147. hscInteractive _ _ = panic "GHC not compiled with interpreter"
  1148. #endif
  1149. ------------------------------
  1150. hscCompileCmmFile :: HscEnv -> FilePath -> IO ()
  1151. hscCompileCmmFile hsc_env filename = runHsc hsc_env $ do
  1152. let dflags = hsc_dflags hsc_env
  1153. cmm <- ioMsgMaybe $ parseCmmFile dflags filename
  1154. liftIO $ do
  1155. us <- mkSplitUniqSupply 'S'
  1156. let initTopSRT = initUs_ us emptySRT
  1157. dumpIfSet_dyn dflags Opt_D_dump_cmmz "Parsed Cmm" (ppr cmm)
  1158. (_, cmmgroup) <- cmmPipeline hsc_env initTopSRT cmm
  1159. rawCmms <- cmmToRawCmm dflags (Stream.yield (cmmOfZgraph cmmgroup))
  1160. _ <- codeOutput dflags no_mod no_loc NoStubs [] rawCmms
  1161. return ()
  1162. where
  1163. no_mod = panic "hscCmmFile: no_mod"
  1164. no_loc = ModLocation{ ml_hs_file = Just filename,
  1165. ml_hi_file = panic "hscCmmFile: no hi file",
  1166. ml_obj_file = panic "hscCmmFile: no obj file" }
  1167. -------------------- Stuff for new code gen ---------------------
  1168. tryNewCodeGen :: HscEnv -> Module -> [TyCon]
  1169. -> CollectedCCs
  1170. -> [StgBinding]
  1171. -> HpcInfo
  1172. -> IO (Stream IO Old.CmmGroup ())
  1173. -- Note we produce a 'Stream' of CmmGroups, so that the
  1174. -- backend can be run incrementally. Otherwise it generates all
  1175. -- the C-- up front, which has a significant space cost.
  1176. tryNewCodeGen hsc_env this_mod data_tycons
  1177. cost_centre_info stg_binds hpc_info = do
  1178. let dflags = hsc_dflags hsc_env
  1179. let cmm_stream :: Stream IO New.CmmGroup ()
  1180. cmm_stream = {-# SCC "StgCmm" #-}
  1181. StgCmm.codeGen dflags this_mod data_tycons
  1182. cost_centre_info stg_binds hpc_info
  1183. -- codegen consumes a stream of CmmGroup, and produces a new
  1184. -- stream of CmmGroup (not necessarily synchronised: one
  1185. -- CmmGroup on input may produce many CmmGroups on output due
  1186. -- to proc-point splitting).
  1187. let dump1 a = do dumpIfSet_dyn dflags Opt_D_dump_cmmz
  1188. "Cmm produced by new codegen" (ppr a)
  1189. return a
  1190. ppr_stream1 = Stream.mapM dump1 cmm_stream
  1191. -- We are building a single SRT for the entire module, so
  1192. -- we must thread it through all the procedures as we cps-convert them.
  1193. us <- mkSplitUniqSupply 'S'
  1194. -- When splitting, we generate one SRT per split chunk, otherwise
  1195. -- we generate one SRT for the whole module.
  1196. let
  1197. pipeline_stream
  1198. | dopt Opt_SplitObjs dflags
  1199. = {-# SCC "cmmPipeline" #-}
  1200. let run_pipeline us cmmgroup = do
  1201. let (topSRT', us') = initUs us emptySRT
  1202. (topSRT, cmmgroup) <- cmmPipeline hsc_env topSRT' cmmgroup
  1203. let srt | isEmptySRT topSRT = []
  1204. | otherwise = srtToData topSRT
  1205. return (us',cmmOfZgraph (srt ++ cmmgroup))
  1206. in do _ <- Stream.mapAccumL run_pipeline us ppr_stream1
  1207. return ()
  1208. | otherwise
  1209. = {-# SCC "cmmPipeline" #-}
  1210. let initTopSRT = initUs_ us emptySRT in
  1211. let run_pipeline topSRT cmmgroup = do
  1212. (topSRT, cmmgroup) <- cmmPipeline hsc_env topSRT cmmgroup
  1213. return (topSRT,cmmOfZgraph cmmgroup)
  1214. in do topSRT <- Stream.mapAccumL run_pipeline initTopSRT ppr_stream1
  1215. Stream.yield (cmmOfZgraph (srtToData topSRT))
  1216. let
  1217. dump2 a = do dumpIfSet_dyn dflags Opt_D_dump_cmmz "Output Cmm" $ ppr a
  1218. return a
  1219. ppr_stream2 = Stream.mapM dump2 pipeline_stream
  1220. return ppr_stream2
  1221. myCoreToStg :: DynFlags -> Module -> CoreProgram
  1222. -> IO ( [StgBinding] -- output program
  1223. , CollectedCCs) -- cost centre info (declared and used)
  1224. myCoreToStg dflags this_mod prepd_binds = do
  1225. stg_binds
  1226. <- {-# SCC "Core2Stg" #-}
  1227. coreToStg dflags prepd_binds
  1228. (stg_binds2, cost_centre_info)
  1229. <- {-# SCC "Stg2Stg" #-}
  1230. stg2stg dflags this_mod stg_binds
  1231. return (stg_binds2, cost_centre_info)
  1232. {- **********************************************************************
  1233. %* *
  1234. \subsection{Compiling a do-statement}
  1235. %* *
  1236. %********************************************************************* -}
  1237. {-
  1238. When the UnlinkedBCOExpr is linked you get an HValue of type *IO [HValue]* When
  1239. you run it you get a list of HValues that should be the same length as the list
  1240. of names; add them to the ClosureEnv.
  1241. A naked expression returns a singleton Name [it]. The stmt is lifted into the
  1242. IO monad as explained in Note [Interactively-bound Ids in GHCi] in TcRnDriver
  1243. -}
  1244. #ifdef GHCI
  1245. -- | Compile a stmt all the way to an HValue, but don't run it
  1246. --
  1247. -- We return Nothing to indicate an empty statement (or comment only), not a
  1248. -- parse error.
  1249. hscStmt :: HscEnv -> String -> IO (Maybe ([Id], IO [HValue], FixityEnv))
  1250. hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1
  1251. -- | Compile a stmt all the way to an HValue, but don't run it
  1252. --
  1253. -- We return Nothing to indicate an empty statement (or comment only), not a
  1254. -- parse error.
  1255. hscStmtWithLocation :: HscEnv
  1256. -> String -- ^ The statement
  1257. -> String -- ^ The source
  1258. -> Int -- ^ Starting line
  1259. -> IO (Maybe ([Id], IO [HValue], FixityEnv))
  1260. hscStmtWithLocation hsc_env0 stmt source linenumber =
  1261. runInteractiveHsc hsc_env0 $ do
  1262. hsc_env <- getHscEnv
  1263. maybe_stmt <- hscParseStmtWithLocation source linenumber stmt
  1264. case maybe_stmt of
  1265. Nothing -> return Nothing
  1266. Just parsed_stmt -> do
  1267. let icntxt = hsc_IC hsc_env
  1268. rdr_env = ic_rn_gbl_env icntxt
  1269. type_env = mkTypeEnvWithImplicits (ic_tythings icntxt)
  1270. src_span = srcLocSpan interactiveSrcLoc
  1271. -- Rename and typecheck it
  1272. -- Here we lift the stmt into the IO monad, see Note
  1273. -- [Interactively-bound Ids in GHCi] in TcRnDriver
  1274. (ids, tc_expr, fix_env) <- ioMsgMaybe $ tcRnStmt hsc_env icntxt parsed_stmt
  1275. -- Desugar it
  1276. ds_expr <- ioMsgMaybe $
  1277. deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
  1278. handleWarnings
  1279. -- Then code-gen, and link it
  1280. hsc_env <- getHscEnv
  1281. hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr
  1282. let hval_io = unsafeCoerce# hval :: IO [HValue]
  1283. return $ Just (ids, hval_io, fix_env)
  1284. -- | Compile a decls
  1285. hscDecls :: HscEnv
  1286. -> String -- ^ The statement
  1287. -> IO ([TyThing], InteractiveContext)
  1288. hscDecls hsc_env str = hscDeclsWithLocation hsc_env str "<interactive>" 1
  1289. -- | Compile a decls
  1290. hscDeclsWithLocation :: HscEnv
  1291. -> String -- ^ The statement
  1292. -> String -- ^ The source
  1293. -> Int -- ^ Starting line
  1294. -> IO ([TyThing], InteractiveContext)
  1295. hscDeclsWithLocation hsc_env0 str source linenumber =
  1296. runInteractiveHsc hsc_env0 $ do
  1297. hsc_env <- getHscEnv
  1298. L _ (HsModule{ hsmodDecls = decls }) <-
  1299. hscParseThingWithLocation source linenumber parseModule str
  1300. {- Rename and typecheck it -}
  1301. let icontext = hsc_IC hsc_env
  1302. tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env icontext decls
  1303. {- Grab the new instances -}
  1304. -- We grab the whole environment because of the overlapping that may have
  1305. -- been done. See the notes at the definition of InteractiveContext
  1306. -- (ic_instances) for more details.
  1307. let finsts = tcg_fam_insts tc_gblenv
  1308. insts = tcg_insts tc_gblenv
  1309. let defaults = tcg_default tc_gblenv
  1310. {- Desugar it -}
  1311. -- We use a basically null location for iNTERACTIVE
  1312. let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing,
  1313. ml_hi_file = panic "hsDeclsWithLocation:ml_hi_file",
  1314. ml_obj_file = panic "hsDeclsWithLocation:ml_hi_file"}
  1315. ds_result <- hscDesugar' iNTERACTIVELoc tc_gblenv
  1316. {- Simplify -}
  1317. simpl_mg <- liftIO $ hscSimplify hsc_env ds_result
  1318. {- Tidy -}
  1319. (tidy_cg, _mod_details) <- liftIO $ tidyProgram hsc_env simpl_mg
  1320. let dflags = hsc_dflags hsc_env
  1321. !CgGuts{ cg_module = this_mod,
  1322. cg_binds = core_binds,
  1323. cg_tycons = tycons,
  1324. cg_modBreaks = mod_breaks } = tidy_cg
  1325. data_tycons = filter isDataTyCon tycons
  1326. {- Prepare For Code Generation -}
  1327. -- Do saturation and convert to A-normal form
  1328. prepd_binds <- {-# SCC "CorePrep" #-}
  1329. liftIO $ corePrepPgm dflags hsc_env core_binds data_tycons
  1330. {- Generate byte code -}
  1331. cbc <- liftIO $ byteCodeGen dflags this_mod
  1332. prepd_binds data_tycons mod_breaks
  1333. let src_span = srcLocSpan interactiveSrcLoc
  1334. hsc_env <- getHscEnv
  1335. liftIO $ linkDecls hsc_env src_span cbc
  1336. let tcs = filter (not . isImplicitTyCon) $ (mg_tcs simpl_mg)
  1337. ext_vars = filter (isExternalName . idName) $
  1338. bindersOfBinds core_binds
  1339. (sys_vars, user_vars) = partition is_sys_var ext_vars
  1340. is_sys_var id = isDFunId id
  1341. || isRecordSelector id
  1342. || isJust (isClassOpId_maybe id)
  1343. -- we only need to keep around the external bindings
  1344. -- (as decided by TidyPgm), since those are the only ones
  1345. -- that might be referenced elsewhere.
  1346. tythings = map AnId user_vars
  1347. ++ map ATyCon tcs
  1348. let ictxt1 = extendInteractiveContext icontext tythings
  1349. ictxt = ictxt1 { ic_sys_vars = sys_vars ++ ic_sys_vars ictxt1,
  1350. ic_instances = (insts, finsts),
  1351. ic_default = defaults }
  1352. return (tythings, ictxt)
  1353. hscImport :: HscEnv -> String -> IO (ImportDecl RdrName)
  1354. hscImport hsc_env str = runInteractiveHsc hsc_env $ do
  1355. (L _ (HsModule{hsmodImports=is})) <-
  1356. hscParseThing parseModule str
  1357. case is of
  1358. [i] -> return (unLoc i)
  1359. _ -> liftIO $ throwOneError $
  1360. mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan $
  1361. ptext (sLit "parse error in import declaration")
  1362. -- | Typecheck an expression (but don't run it)
  1363. hscTcExpr :: HscEnv
  1364. -> String -- ^ The expression
  1365. -> IO Type
  1366. hscTcExpr hsc_env0 expr = runInteractiveHsc hsc_env0 $ do
  1367. hsc_env <- getHscEnv
  1368. maybe_stmt <- hscParseStmt expr
  1369. case maybe_stmt of
  1370. Just (L _ (BodyStmt expr _ _ _)) ->
  1371. ioMsgMaybe $ tcRnExpr hsc_env (hsc_IC hsc_env) expr
  1372. _ ->
  1373. throwErrors $ unitBag $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan
  1374. (text "not an expression:" <+> quotes (text expr))
  1375. -- | Find the kind of a type
  1376. hscKcType
  1377. :: HscEnv
  1378. -> Bool -- ^ Normalise the type
  1379. -> String -- ^ The type as a string
  1380. -> IO (Type, Kind) -- ^ Resulting type (possibly normalised) and kind
  1381. hscKcType hsc_env0 normalise str = runInteractiveHsc hsc_env0 $ do
  1382. hsc_env <- getHscEnv
  1383. ty <- hscParseType str
  1384. ioMsgMaybe $ tcRnType hsc_env (hsc_IC hsc_env) normalise ty
  1385. hscParseStmt :: String -> Hsc (Maybe (GhciLStmt RdrName))
  1386. hscParseStmt = hscParseThing parseStmt
  1387. hscParseStmtWithLocation :: String -> Int -> String
  1388. -> Hsc (Maybe (GhciLStmt RdrName))
  1389. hscParseStmtWithLocation source linenumber stmt =
  1390. hscParseThingWithLocation source linenumber parseStmt stmt
  1391. hscParseType :: String -> Hsc (LHsType RdrName)
  1392. hscParseType = hscParseThing parseType
  1393. #endif
  1394. hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName)
  1395. hscParseIdentifier hsc_env str =
  1396. runInteractiveHsc hsc_env $ hscParseThing parseIdentifier str
  1397. hscParseThing :: (Outputable thing) => Lexer.P thing -> String -> Hsc thing
  1398. hscParseThing = hscParseThingWithLocation "<interactive>" 1
  1399. hscParseThingWithLocation :: (Outputable thing) => String -> Int
  1400. -> Lexer.P thing -> String -> Hsc thing
  1401. hscParseThingWithLocation source linenumber parser str
  1402. = {-# SCC "Parser" #-} do
  1403. dflags <- getDynFlags
  1404. liftIO $ showPass dflags "Parser"
  1405. let buf = stringToStringBuffer str
  1406. loc = mkRealSrcLoc (fsLit source) linenumber 1
  1407. case unP parser (mkPState dflags buf loc) of
  1408. PFailed span err -> do
  1409. let msg = mkPlainErrMsg dflags span err
  1410. throwErrors $ unitBag msg
  1411. POk pst thing -> do
  1412. logWarningsReportErrors (getMessages pst)
  1413. liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
  1414. return thing
  1415. hscCompileCore :: HscEnv -> Bool -> SafeHaskellMode -> ModSummary
  1416. -> CoreProgram -> IO ()
  1417. hscCompileCore hsc_env simplify safe_mode mod_summary binds
  1418. = runHsc hsc_env $ do
  1419. guts <- maybe_simplify (mkModGuts (ms_mod mod_summary) safe_mode binds)
  1420. (iface, changed, _details, cgguts) <- hscNormalIface guts Nothing
  1421. hscWriteIface iface changed mod_summary
  1422. _ <- hscGenHardCode cgguts mod_summary
  1423. return ()
  1424. where
  1425. maybe_simplify mod_guts | simplify = hscSimplify' mod_guts
  1426. | otherwise = return mod_guts
  1427. -- Makes a "vanilla" ModGuts.
  1428. mkModGuts :: Module -> SafeHaskellMode -> CoreProgram -> ModGuts
  1429. mkModGuts mod safe binds =
  1430. ModGuts {
  1431. mg_module = mod,
  1432. mg_boot = False,
  1433. mg_exports = [],
  1434. mg_deps = noDependencies,
  1435. mg_dir_imps = emptyModuleEnv,
  1436. mg_used_names = emptyNameSet,
  1437. mg_used_th = False,
  1438. mg_rdr_env = emptyGlobalRdrEnv,
  1439. mg_fix_env = emptyFixityEnv,
  1440. mg_tcs = [],
  1441. mg_insts = [],
  1442. mg_fam_insts = [],
  1443. mg_rules = [],
  1444. mg_vect_decls = [],
  1445. mg_binds = binds,
  1446. mg_foreign = NoStubs,
  1447. mg_warns = NoWarnings,
  1448. mg_anns = [],
  1449. mg_hpc_info = emptyHpcInfo False,
  1450. mg_modBreaks = emptyModBreaks,
  1451. mg_vect_info = noVectInfo,
  1452. mg_inst_env = emptyInstEnv,
  1453. mg_fam_inst_env = emptyFamInstEnv,
  1454. mg_safe_haskell = safe,
  1455. mg_trust_pkg = False,
  1456. mg_dependent_files = []
  1457. }
  1458. {- **********************************************************************
  1459. %* *
  1460. Desugar, simplify, convert to bytecode, and link an expression
  1461. %* *
  1462. %********************************************************************* -}
  1463. #ifdef GHCI
  1464. hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
  1465. hscCompileCoreExpr hsc_env srcspan ds_expr
  1466. | rtsIsProfiled
  1467. = throwIO (InstallationError "You can't call hscCompileCoreExpr in a profiled compiler")
  1468. -- Otherwise you get a seg-fault when you run it
  1469. | otherwise = do
  1470. let dflags = hsc_dflags hsc_env
  1471. let lint_on = dopt Opt_DoCoreLinting dflags
  1472. {- Simplify it -}
  1473. simpl_expr <- simplifyExpr dflags ds_expr
  1474. {- Tidy it (temporary, until coreSat does cloning) -}
  1475. let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
  1476. {- Prepare for codegen -}
  1477. prepd_expr <- corePrepExpr dflags hsc_env tidy_expr
  1478. {- Lint if necessary -}
  1479. -- ToDo: improve SrcLoc
  1480. when lint_on $
  1481. let ictxt = hsc_IC hsc_env
  1482. te = mkTypeEnvWithImplicits (ic_tythings ictxt ++ map AnId (ic_sys_vars ictxt))
  1483. tyvars = varSetElems $ tyThingsTyVars $ typeEnvElts $ te
  1484. vars = typeEnvIds te
  1485. in case lintUnfolding noSrcLoc (tyvars ++ vars) prepd_expr of
  1486. Just err -> pprPanic "hscCompileCoreExpr" err
  1487. Nothing -> return ()
  1488. {- Convert to BCOs -}
  1489. bcos <- coreExprToBCOs dflags iNTERACTIVE prepd_expr
  1490. {- link it -}
  1491. hval <- linkExpr hsc_env srcspan bcos
  1492. return hval
  1493. #endif
  1494. {- **********************************************************************
  1495. %* *
  1496. Statistics on reading interfaces
  1497. %* *
  1498. %********************************************************************* -}
  1499. dumpIfaceStats :: HscEnv -> IO ()
  1500. dumpIfaceStats hsc_env = do
  1501. eps <- readIORef (hsc_EPS hsc_env)
  1502. dumpIfSet dflags (dump_if_trace || dump_rn_stats)
  1503. "Interface statistics"
  1504. (ifaceStats eps)
  1505. where
  1506. dflags = hsc_dflags hsc_env
  1507. dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
  1508. dump_if_trace = dopt Opt_D_dump_if_trace dflags
  1509. {- **********************************************************************
  1510. %* *
  1511. Progress Messages: Module i of n
  1512. %* *
  1513. %********************************************************************* -}
  1514. showModuleIndex :: Maybe (Int, Int) -> String
  1515. showModuleIndex Nothing = ""
  1516. showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
  1517. where
  1518. n_str = show n
  1519. i_str = show i
  1520. padded = replicate (length n_str - length i_str) ' ' ++ i_str