PageRenderTime 85ms CodeModel.GetById 35ms RepoModel.GetById 2ms app.codeStats 0ms

/compiler/main/HscTypes.hs

http://github.com/ghc/ghc
Haskell | 2903 lines | 1394 code | 371 blank | 1138 comment | 22 complexity | 44b3ff6530491897c9c42f3695c3acc6 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0

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

  1. {-
  2. (c) The University of Glasgow, 2006
  3. \section[HscTypes]{Types for the per-module compiler}
  4. -}
  5. {-# LANGUAGE CPP, ScopedTypeVariables #-}
  6. -- | Types for the per-module compiler
  7. module HscTypes (
  8. -- * compilation state
  9. HscEnv(..), hscEPS,
  10. FinderCache, FindResult(..),
  11. Target(..), TargetId(..), pprTarget, pprTargetId,
  12. ModuleGraph, emptyMG,
  13. HscStatus(..),
  14. #ifdef GHCI
  15. IServ(..),
  16. #endif
  17. -- * Hsc monad
  18. Hsc(..), runHsc, runInteractiveHsc,
  19. -- * Information about modules
  20. ModDetails(..), emptyModDetails,
  21. ModGuts(..), CgGuts(..), ForeignStubs(..), appendStubC,
  22. ImportedMods, ImportedModsVal(..),
  23. ModSummary(..), ms_imps, ms_mod_name, showModMsg, isBootSummary,
  24. msHsFilePath, msHiFilePath, msObjFilePath,
  25. SourceModified(..),
  26. -- * Information about the module being compiled
  27. -- (re-exported from DriverPhases)
  28. HscSource(..), isHsBootOrSig, hscSourceString,
  29. -- * State relating to modules in this package
  30. HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
  31. lookupHpt, eltsHpt, filterHpt, allHpt, mapHpt, delFromHpt,
  32. addToHpt, addListToHpt, lookupHptDirectly, listToHpt,
  33. hptInstances, hptRules, hptVectInfo, pprHPT,
  34. hptObjs,
  35. -- * State relating to known packages
  36. ExternalPackageState(..), EpsStats(..), addEpsInStats,
  37. PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
  38. lookupIfaceByModule, emptyModIface, lookupHptByModule,
  39. PackageInstEnv, PackageFamInstEnv, PackageRuleBase,
  40. mkSOName, mkHsSOName, soExt,
  41. -- * Metaprogramming
  42. MetaRequest(..),
  43. MetaResult, -- data constructors not exported to ensure correct response type
  44. metaRequestE, metaRequestP, metaRequestT, metaRequestD, metaRequestAW,
  45. MetaHook,
  46. -- * Annotations
  47. prepareAnnotations,
  48. -- * Interactive context
  49. InteractiveContext(..), emptyInteractiveContext,
  50. icPrintUnqual, icInScopeTTs, icExtendGblRdrEnv,
  51. extendInteractiveContext, extendInteractiveContextWithIds,
  52. substInteractiveContext,
  53. setInteractivePrintName, icInteractiveModule,
  54. InteractiveImport(..), setInteractivePackage,
  55. mkPrintUnqualified, pprModulePrefix,
  56. mkQualPackage, mkQualModule, pkgQual,
  57. -- * Interfaces
  58. ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache,
  59. emptyIfaceWarnCache, mi_boot, mi_fix,
  60. -- * Fixity
  61. FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
  62. -- * TyThings and type environments
  63. TyThing(..), tyThingAvailInfo,
  64. tyThingTyCon, tyThingDataCon,
  65. tyThingId, tyThingCoAxiom, tyThingParent_maybe, tyThingsTyCoVars,
  66. implicitTyThings, implicitTyConThings, implicitClassThings,
  67. isImplicitTyThing,
  68. TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv,
  69. typeEnvFromEntities, mkTypeEnvWithImplicits,
  70. extendTypeEnv, extendTypeEnvList,
  71. extendTypeEnvWithIds, plusTypeEnv,
  72. lookupTypeEnv,
  73. typeEnvElts, typeEnvTyCons, typeEnvIds, typeEnvPatSyns,
  74. typeEnvDataCons, typeEnvCoAxioms, typeEnvClasses,
  75. -- * MonadThings
  76. MonadThings(..),
  77. -- * Information on imports and exports
  78. WhetherHasOrphans, IsBootInterface, Usage(..),
  79. Dependencies(..), noDependencies,
  80. NameCache(..), OrigNameCache, updNameCacheIO,
  81. IfaceExport,
  82. -- * Warnings
  83. Warnings(..), WarningTxt(..), plusWarns,
  84. -- * Linker stuff
  85. Linkable(..), isObjectLinkable, linkableObjs,
  86. Unlinked(..), CompiledByteCode,
  87. isObject, nameOfObject, isInterpretable, byteCodeOfObject,
  88. -- * Program coverage
  89. HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
  90. -- * Breakpoints
  91. ModBreaks (..), emptyModBreaks,
  92. -- * Vectorisation information
  93. VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo,
  94. noIfaceVectInfo, isNoIfaceVectInfo,
  95. -- * Safe Haskell information
  96. IfaceTrustInfo, getSafeMode, setSafeMode, noIfaceTrustInfo,
  97. trustInfoToNum, numToTrustInfo, IsSafeImport,
  98. -- * result of the parser
  99. HsParsedModule(..),
  100. -- * Compilation errors and warnings
  101. SourceError, GhcApiError, mkSrcErr, srcErrorMessages, mkApiErr,
  102. throwOneError, handleSourceError,
  103. handleFlagWarnings, printOrThrowWarnings,
  104. ) where
  105. #include "HsVersions.h"
  106. #ifdef GHCI
  107. import ByteCodeTypes
  108. import InteractiveEvalTypes ( Resume )
  109. import GHCi.Message ( Pipe )
  110. import GHCi.RemoteTypes
  111. #endif
  112. import UniqFM
  113. import HsSyn
  114. import RdrName
  115. import Avail
  116. import Module
  117. import InstEnv ( InstEnv, ClsInst, identicalClsInstHead )
  118. import FamInstEnv
  119. import CoreSyn ( CoreProgram, RuleBase )
  120. import Name
  121. import NameEnv
  122. import NameSet
  123. import VarEnv
  124. import VarSet
  125. import Var
  126. import Id
  127. import IdInfo ( IdDetails(..), RecSelParent(..))
  128. import Type
  129. import ApiAnnotation ( ApiAnns )
  130. import Annotations ( Annotation, AnnEnv, mkAnnEnv, plusAnnEnv )
  131. import Class
  132. import TyCon
  133. import CoAxiom
  134. import ConLike
  135. import DataCon
  136. import PatSyn
  137. import PrelNames ( gHC_PRIM, ioTyConName, printName, mkInteractiveModule
  138. , eqTyConName )
  139. import TysWiredIn
  140. import Packages hiding ( Version(..) )
  141. import DynFlags
  142. import DriverPhases ( Phase, HscSource(..), isHsBootOrSig, hscSourceString )
  143. import BasicTypes
  144. import IfaceSyn
  145. import CoreSyn ( CoreRule, CoreVect )
  146. import Maybes
  147. import Outputable
  148. import SrcLoc
  149. import Unique
  150. import UniqDFM
  151. import UniqSupply
  152. import FastString
  153. import StringBuffer ( StringBuffer )
  154. import Fingerprint
  155. import MonadUtils
  156. import Bag
  157. import Binary
  158. import ErrUtils
  159. import Platform
  160. import Util
  161. import GHC.Serialized ( Serialized )
  162. import Foreign
  163. import Control.Monad ( guard, liftM, when, ap )
  164. import Data.IORef
  165. import Data.Time
  166. import Exception
  167. import System.FilePath
  168. #ifdef GHCI
  169. import Control.Concurrent
  170. import System.Process ( ProcessHandle )
  171. #endif
  172. -- -----------------------------------------------------------------------------
  173. -- Compilation state
  174. -- -----------------------------------------------------------------------------
  175. -- | Status of a compilation to hard-code
  176. data HscStatus
  177. = HscNotGeneratingCode
  178. | HscUpToDate
  179. | HscUpdateBoot
  180. | HscUpdateSig
  181. | HscRecomp CgGuts ModSummary
  182. -- -----------------------------------------------------------------------------
  183. -- The Hsc monad: Passing an environment and warning state
  184. newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))
  185. instance Functor Hsc where
  186. fmap = liftM
  187. instance Applicative Hsc where
  188. pure a = Hsc $ \_ w -> return (a, w)
  189. (<*>) = ap
  190. instance Monad Hsc where
  191. Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
  192. case k a of
  193. Hsc k' -> k' e w1
  194. instance MonadIO Hsc where
  195. liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)
  196. instance HasDynFlags Hsc where
  197. getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
  198. runHsc :: HscEnv -> Hsc a -> IO a
  199. runHsc hsc_env (Hsc hsc) = do
  200. (a, w) <- hsc hsc_env emptyBag
  201. printOrThrowWarnings (hsc_dflags hsc_env) w
  202. return a
  203. runInteractiveHsc :: HscEnv -> Hsc a -> IO a
  204. -- A variant of runHsc that switches in the DynFlags from the
  205. -- InteractiveContext before running the Hsc computation.
  206. runInteractiveHsc hsc_env
  207. = runHsc (hsc_env { hsc_dflags = interactive_dflags })
  208. where
  209. interactive_dflags = ic_dflags (hsc_IC hsc_env)
  210. -- -----------------------------------------------------------------------------
  211. -- Source Errors
  212. -- When the compiler (HscMain) discovers errors, it throws an
  213. -- exception in the IO monad.
  214. mkSrcErr :: ErrorMessages -> SourceError
  215. mkSrcErr = SourceError
  216. srcErrorMessages :: SourceError -> ErrorMessages
  217. srcErrorMessages (SourceError msgs) = msgs
  218. mkApiErr :: DynFlags -> SDoc -> GhcApiError
  219. mkApiErr dflags msg = GhcApiError (showSDoc dflags msg)
  220. throwOneError :: MonadIO m => ErrMsg -> m ab
  221. throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err
  222. -- | A source error is an error that is caused by one or more errors in the
  223. -- source code. A 'SourceError' is thrown by many functions in the
  224. -- compilation pipeline. Inside GHC these errors are merely printed via
  225. -- 'log_action', but API clients may treat them differently, for example,
  226. -- insert them into a list box. If you want the default behaviour, use the
  227. -- idiom:
  228. --
  229. -- > handleSourceError printExceptionAndWarnings $ do
  230. -- > ... api calls that may fail ...
  231. --
  232. -- The 'SourceError's error messages can be accessed via 'srcErrorMessages'.
  233. -- This list may be empty if the compiler failed due to @-Werror@
  234. -- ('Opt_WarnIsError').
  235. --
  236. -- See 'printExceptionAndWarnings' for more information on what to take care
  237. -- of when writing a custom error handler.
  238. newtype SourceError = SourceError ErrorMessages
  239. instance Show SourceError where
  240. show (SourceError msgs) = unlines . map show . bagToList $ msgs
  241. instance Exception SourceError
  242. -- | Perform the given action and call the exception handler if the action
  243. -- throws a 'SourceError'. See 'SourceError' for more information.
  244. handleSourceError :: (ExceptionMonad m) =>
  245. (SourceError -> m a) -- ^ exception handler
  246. -> m a -- ^ action to perform
  247. -> m a
  248. handleSourceError handler act =
  249. gcatch act (\(e :: SourceError) -> handler e)
  250. -- | An error thrown if the GHC API is used in an incorrect fashion.
  251. newtype GhcApiError = GhcApiError String
  252. instance Show GhcApiError where
  253. show (GhcApiError msg) = msg
  254. instance Exception GhcApiError
  255. -- | Given a bag of warnings, turn them into an exception if
  256. -- -Werror is enabled, or print them out otherwise.
  257. printOrThrowWarnings :: DynFlags -> Bag WarnMsg -> IO ()
  258. printOrThrowWarnings dflags warns
  259. | gopt Opt_WarnIsError dflags
  260. = when (not (isEmptyBag warns)) $ do
  261. throwIO $ mkSrcErr $ warns `snocBag` warnIsErrorMsg dflags
  262. | otherwise
  263. = printBagOfErrors dflags warns
  264. handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
  265. handleFlagWarnings dflags warns
  266. = when (wopt Opt_WarnDeprecatedFlags dflags) $ do
  267. -- It would be nicer if warns :: [Located MsgDoc], but that
  268. -- has circular import problems.
  269. let bag = listToBag [ mkPlainWarnMsg dflags loc (text warn)
  270. | L loc warn <- warns ]
  271. printOrThrowWarnings dflags bag
  272. {-
  273. ************************************************************************
  274. * *
  275. \subsection{HscEnv}
  276. * *
  277. ************************************************************************
  278. -}
  279. -- | HscEnv is like 'Session', except that some of the fields are immutable.
  280. -- An HscEnv is used to compile a single module from plain Haskell source
  281. -- code (after preprocessing) to either C, assembly or C--. Things like
  282. -- the module graph don't change during a single compilation.
  283. --
  284. -- Historical note: \"hsc\" used to be the name of the compiler binary,
  285. -- when there was a separate driver and compiler. To compile a single
  286. -- module, the driver would invoke hsc on the source code... so nowadays
  287. -- we think of hsc as the layer of the compiler that deals with compiling
  288. -- a single module.
  289. data HscEnv
  290. = HscEnv {
  291. hsc_dflags :: DynFlags,
  292. -- ^ The dynamic flag settings
  293. hsc_targets :: [Target],
  294. -- ^ The targets (or roots) of the current session
  295. hsc_mod_graph :: ModuleGraph,
  296. -- ^ The module graph of the current session
  297. hsc_IC :: InteractiveContext,
  298. -- ^ The context for evaluating interactive statements
  299. hsc_HPT :: HomePackageTable,
  300. -- ^ The home package table describes already-compiled
  301. -- home-package modules, /excluding/ the module we
  302. -- are compiling right now.
  303. -- (In one-shot mode the current module is the only
  304. -- home-package module, so hsc_HPT is empty. All other
  305. -- modules count as \"external-package\" modules.
  306. -- However, even in GHCi mode, hi-boot interfaces are
  307. -- demand-loaded into the external-package table.)
  308. --
  309. -- 'hsc_HPT' is not mutable because we only demand-load
  310. -- external packages; the home package is eagerly
  311. -- loaded, module by module, by the compilation manager.
  312. --
  313. -- The HPT may contain modules compiled earlier by @--make@
  314. -- but not actually below the current module in the dependency
  315. -- graph.
  316. --
  317. -- (This changes a previous invariant: changed Jan 05.)
  318. hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
  319. -- ^ Information about the currently loaded external packages.
  320. -- This is mutable because packages will be demand-loaded during
  321. -- a compilation run as required.
  322. hsc_NC :: {-# UNPACK #-} !(IORef NameCache),
  323. -- ^ As with 'hsc_EPS', this is side-effected by compiling to
  324. -- reflect sucking in interface files. They cache the state of
  325. -- external interface files, in effect.
  326. hsc_FC :: {-# UNPACK #-} !(IORef FinderCache),
  327. -- ^ The cached result of performing finding in the file system
  328. hsc_type_env_var :: Maybe (Module, IORef TypeEnv)
  329. -- ^ Used for one-shot compilation only, to initialise
  330. -- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for
  331. -- 'TcRnTypes.TcGblEnv'
  332. #ifdef GHCI
  333. , hsc_iserv :: MVar (Maybe IServ)
  334. -- ^ interactive server process. Created the first
  335. -- time it is needed.
  336. #endif
  337. }
  338. #ifdef GHCI
  339. data IServ = IServ
  340. { iservPipe :: Pipe
  341. , iservProcess :: ProcessHandle
  342. , iservLookupSymbolCache :: IORef (UniqFM (Ptr ()))
  343. , iservPendingFrees :: [HValueRef]
  344. }
  345. #endif
  346. -- | Retrieve the ExternalPackageState cache.
  347. hscEPS :: HscEnv -> IO ExternalPackageState
  348. hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
  349. -- | A compilation target.
  350. --
  351. -- A target may be supplied with the actual text of the
  352. -- module. If so, use this instead of the file contents (this
  353. -- is for use in an IDE where the file hasn't been saved by
  354. -- the user yet).
  355. data Target
  356. = Target {
  357. targetId :: TargetId, -- ^ module or filename
  358. targetAllowObjCode :: Bool, -- ^ object code allowed?
  359. targetContents :: Maybe (StringBuffer,UTCTime)
  360. -- ^ in-memory text buffer?
  361. }
  362. data TargetId
  363. = TargetModule ModuleName
  364. -- ^ A module name: search for the file
  365. | TargetFile FilePath (Maybe Phase)
  366. -- ^ A filename: preprocess & parse it to find the module name.
  367. -- If specified, the Phase indicates how to compile this file
  368. -- (which phase to start from). Nothing indicates the starting phase
  369. -- should be determined from the suffix of the filename.
  370. deriving Eq
  371. pprTarget :: Target -> SDoc
  372. pprTarget (Target id obj _) =
  373. (if obj then char '*' else empty) <> pprTargetId id
  374. instance Outputable Target where
  375. ppr = pprTarget
  376. pprTargetId :: TargetId -> SDoc
  377. pprTargetId (TargetModule m) = ppr m
  378. pprTargetId (TargetFile f _) = text f
  379. instance Outputable TargetId where
  380. ppr = pprTargetId
  381. {-
  382. ************************************************************************
  383. * *
  384. \subsection{Package and Module Tables}
  385. * *
  386. ************************************************************************
  387. -}
  388. -- | Helps us find information about modules in the home package
  389. type HomePackageTable = DModuleNameEnv HomeModInfo
  390. -- Domain = modules in the home package that have been fully compiled
  391. -- "home" unit id cached here for convenience
  392. -- | Helps us find information about modules in the imported packages
  393. type PackageIfaceTable = ModuleEnv ModIface
  394. -- Domain = modules in the imported packages
  395. -- | Constructs an empty HomePackageTable
  396. emptyHomePackageTable :: HomePackageTable
  397. emptyHomePackageTable = emptyUDFM
  398. -- | Constructs an empty PackageIfaceTable
  399. emptyPackageIfaceTable :: PackageIfaceTable
  400. emptyPackageIfaceTable = emptyModuleEnv
  401. pprHPT :: HomePackageTable -> SDoc
  402. -- A bit aribitrary for now
  403. pprHPT hpt = pprUDFM hpt $ \hms ->
  404. vcat [ hang (ppr (mi_module (hm_iface hm)))
  405. 2 (ppr (md_types (hm_details hm)))
  406. | hm <- hms ]
  407. lookupHpt :: HomePackageTable -> ModuleName -> Maybe HomeModInfo
  408. lookupHpt = lookupUDFM
  409. lookupHptDirectly :: HomePackageTable -> Unique -> Maybe HomeModInfo
  410. lookupHptDirectly = lookupUDFM_Directly
  411. eltsHpt :: HomePackageTable -> [HomeModInfo]
  412. eltsHpt = eltsUDFM
  413. filterHpt :: (HomeModInfo -> Bool) -> HomePackageTable -> HomePackageTable
  414. filterHpt = filterUDFM
  415. allHpt :: (HomeModInfo -> Bool) -> HomePackageTable -> Bool
  416. allHpt = allUDFM
  417. mapHpt :: (HomeModInfo -> HomeModInfo) -> HomePackageTable -> HomePackageTable
  418. mapHpt = mapUDFM
  419. delFromHpt :: HomePackageTable -> ModuleName -> HomePackageTable
  420. delFromHpt = delFromUDFM
  421. addToHpt :: HomePackageTable -> ModuleName -> HomeModInfo -> HomePackageTable
  422. addToHpt = addToUDFM
  423. addListToHpt
  424. :: HomePackageTable -> [(ModuleName, HomeModInfo)] -> HomePackageTable
  425. addListToHpt = addListToUDFM
  426. listToHpt :: [(ModuleName, HomeModInfo)] -> HomePackageTable
  427. listToHpt = listToUDFM
  428. lookupHptByModule :: HomePackageTable -> Module -> Maybe HomeModInfo
  429. -- The HPT is indexed by ModuleName, not Module,
  430. -- we must check for a hit on the right Module
  431. lookupHptByModule hpt mod
  432. = case lookupHpt hpt (moduleName mod) of
  433. Just hm | mi_module (hm_iface hm) == mod -> Just hm
  434. _otherwise -> Nothing
  435. -- | Information about modules in the package being compiled
  436. data HomeModInfo
  437. = HomeModInfo {
  438. hm_iface :: !ModIface,
  439. -- ^ The basic loaded interface file: every loaded module has one of
  440. -- these, even if it is imported from another package
  441. hm_details :: !ModDetails,
  442. -- ^ Extra information that has been created from the 'ModIface' for
  443. -- the module, typically during typechecking
  444. hm_linkable :: !(Maybe Linkable)
  445. -- ^ The actual artifact we would like to link to access things in
  446. -- this module.
  447. --
  448. -- 'hm_linkable' might be Nothing:
  449. --
  450. -- 1. If this is an .hs-boot module
  451. --
  452. -- 2. Temporarily during compilation if we pruned away
  453. -- the old linkable because it was out of date.
  454. --
  455. -- After a complete compilation ('GHC.load'), all 'hm_linkable' fields
  456. -- in the 'HomePackageTable' will be @Just@.
  457. --
  458. -- When re-linking a module ('HscMain.HscNoRecomp'), we construct the
  459. -- 'HomeModInfo' by building a new 'ModDetails' from the old
  460. -- 'ModIface' (only).
  461. }
  462. -- | Find the 'ModIface' for a 'Module', searching in both the loaded home
  463. -- and external package module information
  464. lookupIfaceByModule
  465. :: DynFlags
  466. -> HomePackageTable
  467. -> PackageIfaceTable
  468. -> Module
  469. -> Maybe ModIface
  470. lookupIfaceByModule _dflags hpt pit mod
  471. = case lookupHptByModule hpt mod of
  472. Just hm -> Just (hm_iface hm)
  473. Nothing -> lookupModuleEnv pit mod
  474. -- If the module does come from the home package, why do we look in the PIT as well?
  475. -- (a) In OneShot mode, even home-package modules accumulate in the PIT
  476. -- (b) Even in Batch (--make) mode, there is *one* case where a home-package
  477. -- module is in the PIT, namely GHC.Prim when compiling the base package.
  478. -- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
  479. -- of its own, but it doesn't seem worth the bother.
  480. -- | Find all the instance declarations (of classes and families) from
  481. -- the Home Package Table filtered by the provided predicate function.
  482. -- Used in @tcRnImports@, to select the instances that are in the
  483. -- transitive closure of imports from the currently compiled module.
  484. hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([ClsInst], [FamInst])
  485. hptInstances hsc_env want_this_module
  486. = let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do
  487. guard (want_this_module (moduleName (mi_module (hm_iface mod_info))))
  488. let details = hm_details mod_info
  489. return (md_insts details, md_fam_insts details)
  490. in (concat insts, concat famInsts)
  491. -- | Get the combined VectInfo of all modules in the home package table. In
  492. -- contrast to instances and rules, we don't care whether the modules are
  493. -- "below" us in the dependency sense. The VectInfo of those modules not "below"
  494. -- us does not affect the compilation of the current module.
  495. hptVectInfo :: HscEnv -> VectInfo
  496. hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details)
  497. -- | Get rules from modules "below" this one (in the dependency sense)
  498. hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
  499. hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False
  500. -- | Get annotations from modules "below" this one (in the dependency sense)
  501. hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation]
  502. hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps
  503. hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env
  504. hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a]
  505. hptAllThings extract hsc_env = concatMap extract (eltsHpt (hsc_HPT hsc_env))
  506. -- | Get things from modules "below" this one (in the dependency sense)
  507. -- C.f Inst.hptInstances
  508. hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a]
  509. hptSomeThingsBelowUs extract include_hi_boot hsc_env deps
  510. | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
  511. | otherwise
  512. = let hpt = hsc_HPT hsc_env
  513. in
  514. [ thing
  515. | -- Find each non-hi-boot module below me
  516. (mod, is_boot_mod) <- deps
  517. , include_hi_boot || not is_boot_mod
  518. -- unsavoury: when compiling the base package with --make, we
  519. -- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't
  520. -- be in the HPT, because we never compile it; it's in the EPT
  521. -- instead. ToDo: clean up, and remove this slightly bogus filter:
  522. , mod /= moduleName gHC_PRIM
  523. -- Look it up in the HPT
  524. , let things = case lookupHpt hpt mod of
  525. Just info -> extract info
  526. Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg []
  527. msg = vcat [text "missing module" <+> ppr mod,
  528. text "Probable cause: out-of-date interface files"]
  529. -- This really shouldn't happen, but see Trac #962
  530. -- And get its dfuns
  531. , thing <- things ]
  532. hptObjs :: HomePackageTable -> [FilePath]
  533. hptObjs hpt = concat (map (maybe [] linkableObjs . hm_linkable) (eltsHpt hpt))
  534. {-
  535. ************************************************************************
  536. * *
  537. \subsection{Metaprogramming}
  538. * *
  539. ************************************************************************
  540. -}
  541. -- | The supported metaprogramming result types
  542. data MetaRequest
  543. = MetaE (LHsExpr RdrName -> MetaResult)
  544. | MetaP (LPat RdrName -> MetaResult)
  545. | MetaT (LHsType RdrName -> MetaResult)
  546. | MetaD ([LHsDecl RdrName] -> MetaResult)
  547. | MetaAW (Serialized -> MetaResult)
  548. -- | data constructors not exported to ensure correct result type
  549. data MetaResult
  550. = MetaResE { unMetaResE :: LHsExpr RdrName }
  551. | MetaResP { unMetaResP :: LPat RdrName }
  552. | MetaResT { unMetaResT :: LHsType RdrName }
  553. | MetaResD { unMetaResD :: [LHsDecl RdrName] }
  554. | MetaResAW { unMetaResAW :: Serialized }
  555. type MetaHook f = MetaRequest -> LHsExpr Id -> f MetaResult
  556. metaRequestE :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsExpr RdrName)
  557. metaRequestE h = fmap unMetaResE . h (MetaE MetaResE)
  558. metaRequestP :: Functor f => MetaHook f -> LHsExpr Id -> f (LPat RdrName)
  559. metaRequestP h = fmap unMetaResP . h (MetaP MetaResP)
  560. metaRequestT :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsType RdrName)
  561. metaRequestT h = fmap unMetaResT . h (MetaT MetaResT)
  562. metaRequestD :: Functor f => MetaHook f -> LHsExpr Id -> f [LHsDecl RdrName]
  563. metaRequestD h = fmap unMetaResD . h (MetaD MetaResD)
  564. metaRequestAW :: Functor f => MetaHook f -> LHsExpr Id -> f Serialized
  565. metaRequestAW h = fmap unMetaResAW . h (MetaAW MetaResAW)
  566. {-
  567. ************************************************************************
  568. * *
  569. \subsection{Dealing with Annotations}
  570. * *
  571. ************************************************************************
  572. -}
  573. -- | Deal with gathering annotations in from all possible places
  574. -- and combining them into a single 'AnnEnv'
  575. prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv
  576. prepareAnnotations hsc_env mb_guts = do
  577. eps <- hscEPS hsc_env
  578. let -- Extract annotations from the module being compiled if supplied one
  579. mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts
  580. -- Extract dependencies of the module if we are supplied one,
  581. -- otherwise load annotations from all home package table
  582. -- entries regardless of dependency ordering.
  583. home_pkg_anns = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts
  584. other_pkg_anns = eps_ann_env eps
  585. ann_env = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns,
  586. Just home_pkg_anns,
  587. Just other_pkg_anns]
  588. return ann_env
  589. {-
  590. ************************************************************************
  591. * *
  592. \subsection{The Finder cache}
  593. * *
  594. ************************************************************************
  595. -}
  596. -- | The 'FinderCache' maps modules to the result of
  597. -- searching for that module. It records the results of searching for
  598. -- modules along the search path. On @:load@, we flush the entire
  599. -- contents of this cache.
  600. --
  601. -- Although the @FinderCache@ range is 'FindResult' for convenience,
  602. -- in fact it will only ever contain 'Found' or 'NotFound' entries.
  603. --
  604. type FinderCache = ModuleEnv FindResult
  605. -- | The result of searching for an imported module.
  606. data FindResult
  607. = Found ModLocation Module
  608. -- ^ The module was found
  609. | NoPackage UnitId
  610. -- ^ The requested package was not found
  611. | FoundMultiple [(Module, ModuleOrigin)]
  612. -- ^ _Error_: both in multiple packages
  613. -- | Not found
  614. | NotFound
  615. { fr_paths :: [FilePath] -- Places where I looked
  616. , fr_pkg :: Maybe UnitId -- Just p => module is in this package's
  617. -- manifest, but couldn't find
  618. -- the .hi file
  619. , fr_mods_hidden :: [UnitId] -- Module is in these packages,
  620. -- but the *module* is hidden
  621. , fr_pkgs_hidden :: [UnitId] -- Module is in these packages,
  622. -- but the *package* is hidden
  623. , fr_suggestions :: [ModuleSuggestion] -- Possible mis-spelled modules
  624. }
  625. {-
  626. ************************************************************************
  627. * *
  628. \subsection{Symbol tables and Module details}
  629. * *
  630. ************************************************************************
  631. -}
  632. -- | A 'ModIface' plus a 'ModDetails' summarises everything we know
  633. -- about a compiled module. The 'ModIface' is the stuff *before* linking,
  634. -- and can be written out to an interface file. The 'ModDetails is after
  635. -- linking and can be completely recovered from just the 'ModIface'.
  636. --
  637. -- When we read an interface file, we also construct a 'ModIface' from it,
  638. -- except that we explicitly make the 'mi_decls' and a few other fields empty;
  639. -- as when reading we consolidate the declarations etc. into a number of indexed
  640. -- maps and environments in the 'ExternalPackageState'.
  641. data ModIface
  642. = ModIface {
  643. mi_module :: !Module, -- ^ Name of the module we are for
  644. mi_sig_of :: !(Maybe Module), -- ^ Are we a sig of another mod?
  645. mi_iface_hash :: !Fingerprint, -- ^ Hash of the whole interface
  646. mi_mod_hash :: !Fingerprint, -- ^ Hash of the ABI only
  647. mi_flag_hash :: !Fingerprint, -- ^ Hash of the important flags
  648. -- used when compiling this module
  649. mi_orphan :: !WhetherHasOrphans, -- ^ Whether this module has orphans
  650. mi_finsts :: !WhetherHasFamInst, -- ^ Whether this module has family instances
  651. mi_hsc_src :: !HscSource, -- ^ Boot? Signature?
  652. mi_deps :: Dependencies,
  653. -- ^ The dependencies of the module. This is
  654. -- consulted for directly-imported modules, but not
  655. -- for anything else (hence lazy)
  656. mi_usages :: [Usage],
  657. -- ^ Usages; kept sorted so that it's easy to decide
  658. -- whether to write a new iface file (changing usages
  659. -- doesn't affect the hash of this module)
  660. -- NOT STRICT! we read this field lazily from the interface file
  661. -- It is *only* consulted by the recompilation checker
  662. mi_exports :: ![IfaceExport],
  663. -- ^ Exports
  664. -- Kept sorted by (mod,occ), to make version comparisons easier
  665. -- Records the modules that are the declaration points for things
  666. -- exported by this module, and the 'OccName's of those things
  667. mi_exp_hash :: !Fingerprint,
  668. -- ^ Hash of export list
  669. mi_used_th :: !Bool,
  670. -- ^ Module required TH splices when it was compiled.
  671. -- This disables recompilation avoidance (see #481).
  672. mi_fixities :: [(OccName,Fixity)],
  673. -- ^ Fixities
  674. -- NOT STRICT! we read this field lazily from the interface file
  675. mi_warns :: Warnings,
  676. -- ^ Warnings
  677. -- NOT STRICT! we read this field lazily from the interface file
  678. mi_anns :: [IfaceAnnotation],
  679. -- ^ Annotations
  680. -- NOT STRICT! we read this field lazily from the interface file
  681. mi_decls :: [(Fingerprint,IfaceDecl)],
  682. -- ^ Type, class and variable declarations
  683. -- The hash of an Id changes if its fixity or deprecations change
  684. -- (as well as its type of course)
  685. -- Ditto data constructors, class operations, except that
  686. -- the hash of the parent class/tycon changes
  687. mi_globals :: !(Maybe GlobalRdrEnv),
  688. -- ^ Binds all the things defined at the top level in
  689. -- the /original source/ code for this module. which
  690. -- is NOT the same as mi_exports, nor mi_decls (which
  691. -- may contains declarations for things not actually
  692. -- defined by the user). Used for GHCi and for inspecting
  693. -- the contents of modules via the GHC API only.
  694. --
  695. -- (We need the source file to figure out the
  696. -- top-level environment, if we didn't compile this module
  697. -- from source then this field contains @Nothing@).
  698. --
  699. -- Strictly speaking this field should live in the
  700. -- 'HomeModInfo', but that leads to more plumbing.
  701. -- Instance declarations and rules
  702. mi_insts :: [IfaceClsInst], -- ^ Sorted class instance
  703. mi_fam_insts :: [IfaceFamInst], -- ^ Sorted family instances
  704. mi_rules :: [IfaceRule], -- ^ Sorted rules
  705. mi_orphan_hash :: !Fingerprint, -- ^ Hash for orphan rules, class and family
  706. -- instances, and vectorise pragmas combined
  707. mi_vect_info :: !IfaceVectInfo, -- ^ Vectorisation information
  708. -- Cached environments for easy lookup
  709. -- These are computed (lazily) from other fields
  710. -- and are not put into the interface file
  711. mi_warn_fn :: OccName -> Maybe WarningTxt,
  712. -- ^ Cached lookup for 'mi_warns'
  713. mi_fix_fn :: OccName -> Maybe Fixity,
  714. -- ^ Cached lookup for 'mi_fixities'
  715. mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint),
  716. -- ^ Cached lookup for 'mi_decls'.
  717. -- The @Nothing@ in 'mi_hash_fn' means that the thing
  718. -- isn't in decls. It's useful to know that when
  719. -- seeing if we are up to date wrt. the old interface.
  720. -- The 'OccName' is the parent of the name, if it has one.
  721. mi_hpc :: !AnyHpcUsage,
  722. -- ^ True if this program uses Hpc at any point in the program.
  723. mi_trust :: !IfaceTrustInfo,
  724. -- ^ Safe Haskell Trust information for this module.
  725. mi_trust_pkg :: !Bool
  726. -- ^ Do we require the package this module resides in be trusted
  727. -- to trust this module? This is used for the situation where a
  728. -- module is Safe (so doesn't require the package be trusted
  729. -- itself) but imports some trustworthy modules from its own
  730. -- package (which does require its own package be trusted).
  731. -- See Note [RnNames . Trust Own Package]
  732. }
  733. -- | Old-style accessor for whether or not the ModIface came from an hs-boot
  734. -- file.
  735. mi_boot :: ModIface -> Bool
  736. mi_boot iface = mi_hsc_src iface == HsBootFile
  737. -- | Lookups up a (possibly cached) fixity from a 'ModIface'. If one cannot be
  738. -- found, 'defaultFixity' is returned instead.
  739. mi_fix :: ModIface -> OccName -> Fixity
  740. mi_fix iface name = mi_fix_fn iface name `orElse` defaultFixity
  741. instance Binary ModIface where
  742. put_ bh (ModIface {
  743. mi_module = mod,
  744. mi_sig_of = sig_of,
  745. mi_hsc_src = hsc_src,
  746. mi_iface_hash= iface_hash,
  747. mi_mod_hash = mod_hash,
  748. mi_flag_hash = flag_hash,
  749. mi_orphan = orphan,
  750. mi_finsts = hasFamInsts,
  751. mi_deps = deps,
  752. mi_usages = usages,
  753. mi_exports = exports,
  754. mi_exp_hash = exp_hash,
  755. mi_used_th = used_th,
  756. mi_fixities = fixities,
  757. mi_warns = warns,
  758. mi_anns = anns,
  759. mi_decls = decls,
  760. mi_insts = insts,
  761. mi_fam_insts = fam_insts,
  762. mi_rules = rules,
  763. mi_orphan_hash = orphan_hash,
  764. mi_vect_info = vect_info,
  765. mi_hpc = hpc_info,
  766. mi_trust = trust,
  767. mi_trust_pkg = trust_pkg }) = do
  768. put_ bh mod
  769. put_ bh hsc_src
  770. put_ bh iface_hash
  771. put_ bh mod_hash
  772. put_ bh flag_hash
  773. put_ bh orphan
  774. put_ bh hasFamInsts
  775. lazyPut bh deps
  776. lazyPut bh usages
  777. put_ bh exports
  778. put_ bh exp_hash
  779. put_ bh used_th
  780. put_ bh fixities
  781. lazyPut bh warns
  782. lazyPut bh anns
  783. put_ bh decls
  784. put_ bh insts
  785. put_ bh fam_insts
  786. lazyPut bh rules
  787. put_ bh orphan_hash
  788. put_ bh vect_info
  789. put_ bh hpc_info
  790. put_ bh trust
  791. put_ bh trust_pkg
  792. put_ bh sig_of
  793. get bh = do
  794. mod_name <- get bh
  795. hsc_src <- get bh
  796. iface_hash <- get bh
  797. mod_hash <- get bh
  798. flag_hash <- get bh
  799. orphan <- get bh
  800. hasFamInsts <- get bh
  801. deps <- lazyGet bh
  802. usages <- {-# SCC "bin_usages" #-} lazyGet bh
  803. exports <- {-# SCC "bin_exports" #-} get bh
  804. exp_hash <- get bh
  805. used_th <- get bh
  806. fixities <- {-# SCC "bin_fixities" #-} get bh
  807. warns <- {-# SCC "bin_warns" #-} lazyGet bh
  808. anns <- {-# SCC "bin_anns" #-} lazyGet bh
  809. decls <- {-# SCC "bin_tycldecls" #-} get bh
  810. insts <- {-# SCC "bin_insts" #-} get bh
  811. fam_insts <- {-# SCC "bin_fam_insts" #-} get bh
  812. rules <- {-# SCC "bin_rules" #-} lazyGet bh
  813. orphan_hash <- get bh
  814. vect_info <- get bh
  815. hpc_info <- get bh
  816. trust <- get bh
  817. trust_pkg <- get bh
  818. sig_of <- get bh
  819. return (ModIface {
  820. mi_module = mod_name,
  821. mi_sig_of = sig_of,
  822. mi_hsc_src = hsc_src,
  823. mi_iface_hash = iface_hash,
  824. mi_mod_hash = mod_hash,
  825. mi_flag_hash = flag_hash,
  826. mi_orphan = orphan,
  827. mi_finsts = hasFamInsts,
  828. mi_deps = deps,
  829. mi_usages = usages,
  830. mi_exports = exports,
  831. mi_exp_hash = exp_hash,
  832. mi_used_th = used_th,
  833. mi_anns = anns,
  834. mi_fixities = fixities,
  835. mi_warns = warns,
  836. mi_decls = decls,
  837. mi_globals = Nothing,
  838. mi_insts = insts,
  839. mi_fam_insts = fam_insts,
  840. mi_rules = rules,
  841. mi_orphan_hash = orphan_hash,
  842. mi_vect_info = vect_info,
  843. mi_hpc = hpc_info,
  844. mi_trust = trust,
  845. mi_trust_pkg = trust_pkg,
  846. -- And build the cached values
  847. mi_warn_fn = mkIfaceWarnCache warns,
  848. mi_fix_fn = mkIfaceFixCache fixities,
  849. mi_hash_fn = mkIfaceHashCache decls })
  850. -- | The original names declared of a certain module that are exported
  851. type IfaceExport = AvailInfo
  852. -- | Constructs an empty ModIface
  853. emptyModIface :: Module -> ModIface
  854. emptyModIface mod
  855. = ModIface { mi_module = mod,
  856. mi_sig_of = Nothing,
  857. mi_iface_hash = fingerprint0,
  858. mi_mod_hash = fingerprint0,
  859. mi_flag_hash = fingerprint0,
  860. mi_orphan = False,
  861. mi_finsts = False,
  862. mi_hsc_src = HsSrcFile,
  863. mi_deps = noDependencies,
  864. mi_usages = [],
  865. mi_exports = [],
  866. mi_exp_hash = fingerprint0,
  867. mi_used_th = False,
  868. mi_fixities = [],
  869. mi_warns = NoWarnings,
  870. mi_anns = [],
  871. mi_insts = [],
  872. mi_fam_insts = [],
  873. mi_rules = [],
  874. mi_decls = [],
  875. mi_globals = Nothing,
  876. mi_orphan_hash = fingerprint0,
  877. mi_vect_info = noIfaceVectInfo,
  878. mi_warn_fn = emptyIfaceWarnCache,
  879. mi_fix_fn = emptyIfaceFixCache,
  880. mi_hash_fn = emptyIfaceHashCache,
  881. mi_hpc = False,
  882. mi_trust = noIfaceTrustInfo,
  883. mi_trust_pkg = False }
  884. -- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
  885. mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
  886. -> (OccName -> Maybe (OccName, Fingerprint))
  887. mkIfaceHashCache pairs
  888. = \occ -> lookupOccEnv env occ
  889. where
  890. env = foldr add_decl emptyOccEnv pairs
  891. add_decl (v,d) env0 = foldr add env0 (ifaceDeclFingerprints v d)
  892. where
  893. add (occ,hash) env0 = extendOccEnv env0 occ (occ,hash)
  894. emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
  895. emptyIfaceHashCache _occ = Nothing
  896. -- | The 'ModDetails' is essentially a cache for information in the 'ModIface'
  897. -- for home modules only. Information relating to packages will be loaded into
  898. -- global environments in 'ExternalPackageState'.
  899. data ModDetails
  900. = ModDetails {
  901. -- The next two fields are created by the typechecker
  902. md_exports :: [AvailInfo],
  903. md_types :: !TypeEnv, -- ^ Local type environment for this particular module
  904. -- Includes Ids, TyCons, PatSyns
  905. md_insts :: ![ClsInst], -- ^ 'DFunId's for the instances in this module
  906. md_fam_insts :: ![FamInst],
  907. md_rules :: ![CoreRule], -- ^ Domain may include 'Id's from other modules
  908. md_anns :: ![Annotation], -- ^ Annotations present in this module: currently
  909. -- they only annotate things also declared in this module
  910. md_vect_info :: !VectInfo -- ^ Module vectorisation information
  911. }
  912. -- | Constructs an empty ModDetails
  913. emptyModDetails :: ModDetails
  914. emptyModDetails
  915. = ModDetails { md_types = emptyTypeEnv,
  916. md_exports = [],
  917. md_insts = [],
  918. md_rules = [],
  919. md_fam_insts = [],
  920. md_anns = [],
  921. md_vect_info = noVectInfo }
  922. -- | Records the modules directly imported by a module for extracting e.g.
  923. -- usage information, and also to give better error message
  924. type ImportedMods = ModuleEnv [ImportedModsVal]
  925. data ImportedModsVal
  926. = ImportedModsVal {
  927. imv_name :: ModuleName, -- ^ The name the module is imported with
  928. imv_span :: SrcSpan, -- ^ the source span of the whole import
  929. imv_is_safe :: IsSafeImport, -- ^ whether this is a safe import
  930. imv_is_hiding :: Bool, -- ^ whether this is an "hiding" import
  931. imv_all_exports :: GlobalRdrEnv, -- ^ all the things the module could provide
  932. imv_qualified :: Bool -- ^ whether this is a qualified import
  933. }
  934. -- | A ModGuts is carried through the compiler, accumulating stuff as it goes
  935. -- There is only one ModGuts at any time, the one for the module
  936. -- being compiled right now. Once it is compiled, a 'ModIface' and
  937. -- 'ModDetails' are extracted and the ModGuts is discarded.
  938. data ModGuts
  939. = ModGuts {
  940. mg_module :: !Module, -- ^ Module being compiled
  941. mg_hsc_src :: HscSource, -- ^ Whether it's an hs-boot module
  942. mg_loc :: SrcSpan, -- ^ For error messages from inner passes
  943. mg_exports :: ![AvailInfo], -- ^ What it exports
  944. mg_deps :: !Dependencies, -- ^ What it depends on, directly or
  945. -- otherwise
  946. mg_usages :: ![Usage], -- ^ What was used? Used for interfaces.
  947. mg_used_th :: !Bool, -- ^ Did we run a TH splice?
  948. mg_rdr_env :: !GlobalRdrEnv, -- ^ Top-level lexical environment
  949. -- These fields all describe the things **declared in this module**
  950. mg_fix_env :: !FixityEnv, -- ^ Fixities declared in this module.
  951. -- Used for creating interface files.
  952. mg_tcs :: ![TyCon], -- ^ TyCons declared in this module
  953. -- (includes TyCons for classes)
  954. mg_insts :: ![ClsInst], -- ^ Class instances declared in this module
  955. mg_fam_insts :: ![FamInst],
  956. -- ^ Family instances declared in this module
  957. mg_patsyns :: ![PatSyn], -- ^ Pattern synonyms declared in this module
  958. mg_rules :: ![CoreRule], -- ^ Before the core pipeline starts, contains
  959. -- See Note [Overall plumbing for rules] in Rules.hs
  960. mg_binds :: !CoreProgram, -- ^ Bindings for this module
  961. mg_foreign :: !ForeignStubs, -- ^ Foreign exports declared in this module
  962. mg_warns :: !Warnings, -- ^ Warnings declared in the module
  963. mg_anns :: [Annotation], -- ^ Annotations declared in this module
  964. mg_hpc_info :: !HpcInfo, -- ^ Coverage tick boxes in the module
  965. mg_modBreaks :: !(Maybe ModBreaks), -- ^ Breakpoints for the module
  966. mg_vect_decls:: ![CoreVect], -- ^ Vectorisation declarations in this module
  967. -- (produced by desugarer & consumed by vectoriser)
  968. mg_vect_info :: !VectInfo, -- ^ Pool of vectorised declarations in the module
  969. -- The next two fields are unusual, because they give instance
  970. -- environments for *all* modules in the home package, including
  971. -- this module, rather than for *just* this module.
  972. -- Reason: when looking up an instance we don't want to have to
  973. -- look at each module in the home package in turn
  974. mg_inst_env :: InstEnv, -- ^ Class instance environment for
  975. -- /home-package/ modules (including this
  976. -- one); c.f. 'tcg_inst_env'
  977. mg_fam_inst_env :: FamInstEnv, -- ^ Type-family instance environment for
  978. -- /home-package/ modules (including this
  979. -- one); c.f. 'tcg_fam_inst_env'
  980. mg_safe_haskell :: SafeHaskellMode, -- ^ Safe Haskell mode
  981. mg_trust_pkg :: Bool -- ^ Do we need to trust our
  982. -- own package for Safe Haskell?
  983. -- See Note [RnNames . Trust Own Package]
  984. }
  985. -- The ModGuts takes on several slightly different forms:
  986. --
  987. -- After simplification, the following fields change slightly:
  988. -- mg_rules Orphan rules only (local ones now attached to binds)
  989. -- mg_binds With rules attached
  990. ---------------------------------------------------------
  991. -- The Tidy pass forks the information about this module:
  992. -- * one lot goes to interface file generation (ModIface)
  993. -- and later compilations (ModDetails)
  994. -- * the other lot goes to code generation (CgGuts)
  995. -- | A restricted form of 'ModGuts' for code generation purposes
  996. data CgGuts
  997. = CgGuts {
  998. cg_module :: !Module,
  999. -- ^ Module being compiled
  1000. cg_tycons :: [TyCon],
  1001. -- ^ Algebraic data types (including ones that started
  1002. -- life as classes); generate constructors and info
  1003. -- tables. Includes newtypes, just for the benefit of
  1004. -- External Core
  1005. cg_binds :: CoreProgram,
  1006. -- ^ The tidied main bindings, including
  1007. -- previously-implicit bindings for record and class
  1008. -- selectors, and data constructor wrappers. But *not*
  1009. -- data constructor workers; reason: we we regard them
  1010. -- as part of the code-gen of tycons
  1011. cg_foreign :: !ForeignStubs, -- ^ Foreign export stubs
  1012. cg_dep_pkgs :: ![UnitId], -- ^ Dependent packages, used to
  1013. -- generate #includes for C code gen
  1014. cg_hpc_info :: !HpcInfo, -- ^ Program coverage tick box information
  1015. cg_modBreaks :: !(Maybe ModBreaks) -- ^ Module breakpoints
  1016. }
  1017. -----------------------------------
  1018. -- | Foreign export stubs
  1019. data ForeignStubs
  1020. = NoStubs
  1021. -- ^ We don't have any stubs
  1022. | ForeignStubs SDoc SDoc
  1023. -- ^ There are some stubs. Parameters:
  1024. --
  1025. -- 1) Header file prototypes for
  1026. -- "foreign exported" functions
  1027. --
  1028. -- 2) C stubs to use when calling
  1029. -- "foreign exported" functions
  1030. appendStubC :: ForeignStubs -> SDoc -> ForeignStubs
  1031. appendStubC NoStubs c_code = ForeignStubs empty c_code
  1032. appendStubC (ForeignStubs h c) c_code = ForeignStubs h (c $$ c_code)
  1033. {-
  1034. ************************************************************************
  1035. * *
  1036. The interactive context
  1037. * *
  1038. ************************************************************************
  1039. Note [The interactive package]
  1040. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1041. Type, class, and value declarations at the command prompt are treated
  1042. as if they were defined in modules
  1043. interactive:Ghci1
  1044. interactive:Ghci2
  1045. ...etc...
  1046. with each bunch of declarations using a new module, all sharing a
  1047. common package 'interactive' (see Module.interactiveUnitId, and
  1048. PrelNames.mkInteractiv

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