PageRenderTime 35ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/main/HscTypes.lhs

https://bitbucket.org/carter/ghc
Haskell | 2240 lines | 1199 code | 332 blank | 709 comment | 31 complexity | c511ba096725089092d851859c70f704 MD5 | raw file
  1. %
  2. % (c) The University of Glasgow, 2006
  3. %
  4. \section[HscTypes]{Types for the per-module compiler}
  5. \begin{code}
  6. -- | Types for the per-module compiler
  7. module HscTypes (
  8. -- * compilation state
  9. HscEnv(..), hscEPS,
  10. FinderCache, FindResult(..), ModLocationCache,
  11. Target(..), TargetId(..), pprTarget, pprTargetId,
  12. ModuleGraph, emptyMG,
  13. -- * Information about modules
  14. ModDetails(..), emptyModDetails,
  15. ModGuts(..), CgGuts(..), ForeignStubs(..), appendStubC,
  16. ImportedMods, ImportedModsVal,
  17. ModSummary(..), ms_imps, ms_mod_name, showModMsg, isBootSummary,
  18. msHsFilePath, msHiFilePath, msObjFilePath,
  19. SourceModified(..),
  20. -- * Information about the module being compiled
  21. HscSource(..), isHsBoot, hscSourceString, -- Re-exported from DriverPhases
  22. -- * State relating to modules in this package
  23. HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
  24. hptInstances, hptRules, hptVectInfo,
  25. hptObjs,
  26. -- * State relating to known packages
  27. ExternalPackageState(..), EpsStats(..), addEpsInStats,
  28. PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
  29. lookupIfaceByModule, emptyModIface,
  30. PackageInstEnv, PackageRuleBase,
  31. mkSOName,
  32. -- * Annotations
  33. prepareAnnotations,
  34. -- * Interactive context
  35. InteractiveContext(..), emptyInteractiveContext,
  36. icPrintUnqual, icInScopeTTs, icPlusGblRdrEnv,
  37. extendInteractiveContext, substInteractiveContext,
  38. setInteractivePrintName,
  39. InteractiveImport(..),
  40. mkPrintUnqualified, pprModulePrefix,
  41. -- * Interfaces
  42. ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache,
  43. emptyIfaceWarnCache,
  44. -- * Fixity
  45. FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
  46. -- * TyThings and type environments
  47. TyThing(..), tyThingAvailInfo,
  48. tyThingTyCon, tyThingDataCon,
  49. tyThingId, tyThingCoAxiom, tyThingParent_maybe, tyThingsTyVars,
  50. implicitTyThings, implicitTyConThings, implicitClassThings,
  51. isImplicitTyThing,
  52. TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv,
  53. typeEnvFromEntities, mkTypeEnvWithImplicits,
  54. extendTypeEnv, extendTypeEnvList, extendTypeEnvWithIds, lookupTypeEnv,
  55. typeEnvElts, typeEnvTyCons, typeEnvIds,
  56. typeEnvDataCons, typeEnvCoAxioms, typeEnvClasses,
  57. -- * MonadThings
  58. MonadThings(..),
  59. -- * Information on imports and exports
  60. WhetherHasOrphans, IsBootInterface, Usage(..),
  61. Dependencies(..), noDependencies,
  62. NameCache(..), OrigNameCache,
  63. IfaceExport,
  64. -- * Warnings
  65. Warnings(..), WarningTxt(..), plusWarns,
  66. -- * Linker stuff
  67. Linkable(..), isObjectLinkable, linkableObjs,
  68. Unlinked(..), CompiledByteCode,
  69. isObject, nameOfObject, isInterpretable, byteCodeOfObject,
  70. -- * Program coverage
  71. HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
  72. -- * Breakpoints
  73. ModBreaks (..), BreakIndex, emptyModBreaks,
  74. -- * Vectorisation information
  75. VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo,
  76. noIfaceVectInfo, isNoIfaceVectInfo,
  77. -- * Safe Haskell information
  78. IfaceTrustInfo, getSafeMode, setSafeMode, noIfaceTrustInfo,
  79. trustInfoToNum, numToTrustInfo, IsSafeImport,
  80. -- * result of the parser
  81. HsParsedModule(..),
  82. -- * Compilation errors and warnings
  83. SourceError, GhcApiError, mkSrcErr, srcErrorMessages, mkApiErr,
  84. throwOneError, handleSourceError,
  85. handleFlagWarnings, printOrThrowWarnings,
  86. ) where
  87. #include "HsVersions.h"
  88. #ifdef GHCI
  89. import ByteCodeAsm ( CompiledByteCode )
  90. import {-# SOURCE #-} InteractiveEval ( Resume )
  91. #endif
  92. import HsSyn
  93. import RdrName
  94. import Avail
  95. import Module
  96. import InstEnv ( InstEnv, ClsInst )
  97. import FamInstEnv
  98. import Rules ( RuleBase )
  99. import CoreSyn ( CoreProgram )
  100. import Name
  101. import NameEnv
  102. import NameSet
  103. import VarEnv
  104. import VarSet
  105. import Var
  106. import Id
  107. import IdInfo ( IdDetails(..) )
  108. import Type
  109. import Annotations
  110. import Class
  111. import TyCon
  112. import DataCon
  113. import PrelNames ( gHC_PRIM, ioTyConName, printName )
  114. import Packages hiding ( Version(..) )
  115. import DynFlags
  116. import DriverPhases
  117. import BasicTypes
  118. import IfaceSyn
  119. import CoreSyn ( CoreRule, CoreVect )
  120. import Maybes
  121. import Outputable
  122. import BreakArray
  123. import SrcLoc
  124. import Unique
  125. import UniqFM
  126. import UniqSupply
  127. import FastString
  128. import StringBuffer ( StringBuffer )
  129. import Fingerprint
  130. import MonadUtils
  131. import Bag
  132. import ErrUtils
  133. import Platform
  134. import Util
  135. import Control.Monad ( mplus, guard, liftM, when )
  136. import Data.Array ( Array, array )
  137. import Data.IORef
  138. import Data.Time
  139. import Data.Word
  140. import Data.Typeable ( Typeable )
  141. import Exception
  142. import System.FilePath
  143. -- -----------------------------------------------------------------------------
  144. -- Source Errors
  145. -- When the compiler (HscMain) discovers errors, it throws an
  146. -- exception in the IO monad.
  147. mkSrcErr :: ErrorMessages -> SourceError
  148. mkSrcErr = SourceError
  149. srcErrorMessages :: SourceError -> ErrorMessages
  150. srcErrorMessages (SourceError msgs) = msgs
  151. mkApiErr :: DynFlags -> SDoc -> GhcApiError
  152. mkApiErr dflags msg = GhcApiError (showSDoc dflags msg)
  153. throwOneError :: MonadIO m => ErrMsg -> m ab
  154. throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err
  155. -- | A source error is an error that is caused by one or more errors in the
  156. -- source code. A 'SourceError' is thrown by many functions in the
  157. -- compilation pipeline. Inside GHC these errors are merely printed via
  158. -- 'log_action', but API clients may treat them differently, for example,
  159. -- insert them into a list box. If you want the default behaviour, use the
  160. -- idiom:
  161. --
  162. -- > handleSourceError printExceptionAndWarnings $ do
  163. -- > ... api calls that may fail ...
  164. --
  165. -- The 'SourceError's error messages can be accessed via 'srcErrorMessages'.
  166. -- This list may be empty if the compiler failed due to @-Werror@
  167. -- ('Opt_WarnIsError').
  168. --
  169. -- See 'printExceptionAndWarnings' for more information on what to take care
  170. -- of when writing a custom error handler.
  171. newtype SourceError = SourceError ErrorMessages
  172. deriving Typeable
  173. instance Show SourceError where
  174. show (SourceError msgs) = unlines . map show . bagToList $ msgs
  175. instance Exception SourceError
  176. -- | Perform the given action and call the exception handler if the action
  177. -- throws a 'SourceError'. See 'SourceError' for more information.
  178. handleSourceError :: (ExceptionMonad m) =>
  179. (SourceError -> m a) -- ^ exception handler
  180. -> m a -- ^ action to perform
  181. -> m a
  182. handleSourceError handler act =
  183. gcatch act (\(e :: SourceError) -> handler e)
  184. -- | An error thrown if the GHC API is used in an incorrect fashion.
  185. newtype GhcApiError = GhcApiError String
  186. deriving Typeable
  187. instance Show GhcApiError where
  188. show (GhcApiError msg) = msg
  189. instance Exception GhcApiError
  190. -- | Given a bag of warnings, turn them into an exception if
  191. -- -Werror is enabled, or print them out otherwise.
  192. printOrThrowWarnings :: DynFlags -> Bag WarnMsg -> IO ()
  193. printOrThrowWarnings dflags warns
  194. | dopt Opt_WarnIsError dflags
  195. = when (not (isEmptyBag warns)) $ do
  196. throwIO $ mkSrcErr $ warns `snocBag` warnIsErrorMsg dflags
  197. | otherwise
  198. = printBagOfErrors dflags warns
  199. handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
  200. handleFlagWarnings dflags warns
  201. = when (wopt Opt_WarnDeprecatedFlags dflags) $ do
  202. -- It would be nicer if warns :: [Located MsgDoc], but that
  203. -- has circular import problems.
  204. let bag = listToBag [ mkPlainWarnMsg dflags loc (text warn)
  205. | L loc warn <- warns ]
  206. printOrThrowWarnings dflags bag
  207. \end{code}
  208. %************************************************************************
  209. %* *
  210. \subsection{HscEnv}
  211. %* *
  212. %************************************************************************
  213. \begin{code}
  214. -- | Hscenv is like 'Session', except that some of the fields are immutable.
  215. -- An HscEnv is used to compile a single module from plain Haskell source
  216. -- code (after preprocessing) to either C, assembly or C--. Things like
  217. -- the module graph don't change during a single compilation.
  218. --
  219. -- Historical note: \"hsc\" used to be the name of the compiler binary,
  220. -- when there was a separate driver and compiler. To compile a single
  221. -- module, the driver would invoke hsc on the source code... so nowadays
  222. -- we think of hsc as the layer of the compiler that deals with compiling
  223. -- a single module.
  224. data HscEnv
  225. = HscEnv {
  226. hsc_dflags :: DynFlags,
  227. -- ^ The dynamic flag settings
  228. hsc_targets :: [Target],
  229. -- ^ The targets (or roots) of the current session
  230. hsc_mod_graph :: ModuleGraph,
  231. -- ^ The module graph of the current session
  232. hsc_IC :: InteractiveContext,
  233. -- ^ The context for evaluating interactive statements
  234. hsc_HPT :: HomePackageTable,
  235. -- ^ The home package table describes already-compiled
  236. -- home-package modules, /excluding/ the module we
  237. -- are compiling right now.
  238. -- (In one-shot mode the current module is the only
  239. -- home-package module, so hsc_HPT is empty. All other
  240. -- modules count as \"external-package\" modules.
  241. -- However, even in GHCi mode, hi-boot interfaces are
  242. -- demand-loaded into the external-package table.)
  243. --
  244. -- 'hsc_HPT' is not mutable because we only demand-load
  245. -- external packages; the home package is eagerly
  246. -- loaded, module by module, by the compilation manager.
  247. --
  248. -- The HPT may contain modules compiled earlier by @--make@
  249. -- but not actually below the current module in the dependency
  250. -- graph.
  251. --
  252. -- (This changes a previous invariant: changed Jan 05.)
  253. hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
  254. -- ^ Information about the currently loaded external packages.
  255. -- This is mutable because packages will be demand-loaded during
  256. -- a compilation run as required.
  257. hsc_NC :: {-# UNPACK #-} !(IORef NameCache),
  258. -- ^ As with 'hsc_EPS', this is side-effected by compiling to
  259. -- reflect sucking in interface files. They cache the state of
  260. -- external interface files, in effect.
  261. hsc_FC :: {-# UNPACK #-} !(IORef FinderCache),
  262. -- ^ The cached result of performing finding in the file system
  263. hsc_MLC :: {-# UNPACK #-} !(IORef ModLocationCache),
  264. -- ^ This caches the location of modules, so we don't have to
  265. -- search the filesystem multiple times. See also 'hsc_FC'.
  266. hsc_type_env_var :: Maybe (Module, IORef TypeEnv)
  267. -- ^ Used for one-shot compilation only, to initialise
  268. -- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for
  269. -- 'TcRunTypes.TcGblEnv'
  270. }
  271. -- | Retrieve the ExternalPackageState cache.
  272. hscEPS :: HscEnv -> IO ExternalPackageState
  273. hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
  274. -- | A compilation target.
  275. --
  276. -- A target may be supplied with the actual text of the
  277. -- module. If so, use this instead of the file contents (this
  278. -- is for use in an IDE where the file hasn't been saved by
  279. -- the user yet).
  280. data Target
  281. = Target {
  282. targetId :: TargetId, -- ^ module or filename
  283. targetAllowObjCode :: Bool, -- ^ object code allowed?
  284. targetContents :: Maybe (StringBuffer,UTCTime)
  285. -- ^ in-memory text buffer?
  286. }
  287. data TargetId
  288. = TargetModule ModuleName
  289. -- ^ A module name: search for the file
  290. | TargetFile FilePath (Maybe Phase)
  291. -- ^ A filename: preprocess & parse it to find the module name.
  292. -- If specified, the Phase indicates how to compile this file
  293. -- (which phase to start from). Nothing indicates the starting phase
  294. -- should be determined from the suffix of the filename.
  295. deriving Eq
  296. pprTarget :: Target -> SDoc
  297. pprTarget (Target id obj _) =
  298. (if obj then char '*' else empty) <> pprTargetId id
  299. instance Outputable Target where
  300. ppr = pprTarget
  301. pprTargetId :: TargetId -> SDoc
  302. pprTargetId (TargetModule m) = ppr m
  303. pprTargetId (TargetFile f _) = text f
  304. instance Outputable TargetId where
  305. ppr = pprTargetId
  306. \end{code}
  307. %************************************************************************
  308. %* *
  309. \subsection{Package and Module Tables}
  310. %* *
  311. %************************************************************************
  312. \begin{code}
  313. -- | Helps us find information about modules in the home package
  314. type HomePackageTable = ModuleNameEnv HomeModInfo
  315. -- Domain = modules in the home package that have been fully compiled
  316. -- "home" package name cached here for convenience
  317. -- | Helps us find information about modules in the imported packages
  318. type PackageIfaceTable = ModuleEnv ModIface
  319. -- Domain = modules in the imported packages
  320. -- | Constructs an empty HomePackageTable
  321. emptyHomePackageTable :: HomePackageTable
  322. emptyHomePackageTable = emptyUFM
  323. -- | Constructs an empty PackageIfaceTable
  324. emptyPackageIfaceTable :: PackageIfaceTable
  325. emptyPackageIfaceTable = emptyModuleEnv
  326. -- | Information about modules in the package being compiled
  327. data HomeModInfo
  328. = HomeModInfo {
  329. hm_iface :: !ModIface,
  330. -- ^ The basic loaded interface file: every loaded module has one of
  331. -- these, even if it is imported from another package
  332. hm_details :: !ModDetails,
  333. -- ^ Extra information that has been created from the 'ModIface' for
  334. -- the module, typically during typechecking
  335. hm_linkable :: !(Maybe Linkable)
  336. -- ^ The actual artifact we would like to link to access things in
  337. -- this module.
  338. --
  339. -- 'hm_linkable' might be Nothing:
  340. --
  341. -- 1. If this is an .hs-boot module
  342. --
  343. -- 2. Temporarily during compilation if we pruned away
  344. -- the old linkable because it was out of date.
  345. --
  346. -- After a complete compilation ('GHC.load'), all 'hm_linkable' fields
  347. -- in the 'HomePackageTable' will be @Just@.
  348. --
  349. -- When re-linking a module ('HscMain.HscNoRecomp'), we construct the
  350. -- 'HomeModInfo' by building a new 'ModDetails' from the old
  351. -- 'ModIface' (only).
  352. }
  353. -- | Find the 'ModIface' for a 'Module', searching in both the loaded home
  354. -- and external package module information
  355. lookupIfaceByModule
  356. :: DynFlags
  357. -> HomePackageTable
  358. -> PackageIfaceTable
  359. -> Module
  360. -> Maybe ModIface
  361. lookupIfaceByModule dflags hpt pit mod
  362. | modulePackageId mod == thisPackage dflags
  363. -- The module comes from the home package, so look first
  364. -- in the HPT. If it's not from the home package it's wrong to look
  365. -- in the HPT, because the HPT is indexed by *ModuleName* not Module
  366. = fmap hm_iface (lookupUFM hpt (moduleName mod))
  367. `mplus` lookupModuleEnv pit mod
  368. | otherwise = lookupModuleEnv pit mod -- Look in PIT only
  369. -- If the module does come from the home package, why do we look in the PIT as well?
  370. -- (a) In OneShot mode, even home-package modules accumulate in the PIT
  371. -- (b) Even in Batch (--make) mode, there is *one* case where a home-package
  372. -- module is in the PIT, namely GHC.Prim when compiling the base package.
  373. -- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
  374. -- of its own, but it doesn't seem worth the bother.
  375. -- | Find all the instance declarations (of classes and families) that are in
  376. -- modules imported by this one, directly or indirectly, and are in the Home
  377. -- Package Table. This ensures that we don't see instances from modules @--make@
  378. -- compiled before this one, but which are not below this one.
  379. hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([ClsInst], [FamInst])
  380. hptInstances hsc_env want_this_module
  381. = let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do
  382. guard (want_this_module (moduleName (mi_module (hm_iface mod_info))))
  383. let details = hm_details mod_info
  384. return (md_insts details, md_fam_insts details)
  385. in (concat insts, concat famInsts)
  386. -- | Get the combined VectInfo of all modules in the home package table. In
  387. -- contrast to instances and rules, we don't care whether the modules are
  388. -- "below" us in the dependency sense. The VectInfo of those modules not "below"
  389. -- us does not affect the compilation of the current module.
  390. hptVectInfo :: HscEnv -> VectInfo
  391. hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details)
  392. -- | Get rules from modules "below" this one (in the dependency sense)
  393. hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
  394. hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False
  395. -- | Get annotations from modules "below" this one (in the dependency sense)
  396. hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation]
  397. hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps
  398. hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env
  399. hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a]
  400. hptAllThings extract hsc_env = concatMap extract (eltsUFM (hsc_HPT hsc_env))
  401. -- | Get things from modules "below" this one (in the dependency sense)
  402. -- C.f Inst.hptInstances
  403. hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a]
  404. hptSomeThingsBelowUs extract include_hi_boot hsc_env deps
  405. | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
  406. | otherwise
  407. = let hpt = hsc_HPT hsc_env
  408. in
  409. [ thing
  410. | -- Find each non-hi-boot module below me
  411. (mod, is_boot_mod) <- deps
  412. , include_hi_boot || not is_boot_mod
  413. -- unsavoury: when compiling the base package with --make, we
  414. -- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't
  415. -- be in the HPT, because we never compile it; it's in the EPT
  416. -- instead. ToDo: clean up, and remove this slightly bogus filter:
  417. , mod /= moduleName gHC_PRIM
  418. -- Look it up in the HPT
  419. , let things = case lookupUFM hpt mod of
  420. Just info -> extract info
  421. Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg []
  422. msg = vcat [ptext (sLit "missing module") <+> ppr mod,
  423. ptext (sLit "Probable cause: out-of-date interface files")]
  424. -- This really shouldn't happen, but see Trac #962
  425. -- And get its dfuns
  426. , thing <- things ]
  427. hptObjs :: HomePackageTable -> [FilePath]
  428. hptObjs hpt = concat (map (maybe [] linkableObjs . hm_linkable) (eltsUFM hpt))
  429. \end{code}
  430. %************************************************************************
  431. %* *
  432. \subsection{Dealing with Annotations}
  433. %* *
  434. %************************************************************************
  435. \begin{code}
  436. -- | Deal with gathering annotations in from all possible places
  437. -- and combining them into a single 'AnnEnv'
  438. prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv
  439. prepareAnnotations hsc_env mb_guts = do
  440. eps <- hscEPS hsc_env
  441. let -- Extract annotations from the module being compiled if supplied one
  442. mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts
  443. -- Extract dependencies of the module if we are supplied one,
  444. -- otherwise load annotations from all home package table
  445. -- entries regardless of dependency ordering.
  446. home_pkg_anns = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts
  447. other_pkg_anns = eps_ann_env eps
  448. ann_env = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns,
  449. Just home_pkg_anns,
  450. Just other_pkg_anns]
  451. return ann_env
  452. \end{code}
  453. %************************************************************************
  454. %* *
  455. \subsection{The Finder cache}
  456. %* *
  457. %************************************************************************
  458. \begin{code}
  459. -- | The 'FinderCache' maps home module names to the result of
  460. -- searching for that module. It records the results of searching for
  461. -- modules along the search path. On @:load@, we flush the entire
  462. -- contents of this cache.
  463. --
  464. -- Although the @FinderCache@ range is 'FindResult' for convenience,
  465. -- in fact it will only ever contain 'Found' or 'NotFound' entries.
  466. --
  467. type FinderCache = ModuleNameEnv FindResult
  468. -- | The result of searching for an imported module.
  469. data FindResult
  470. = Found ModLocation Module
  471. -- ^ The module was found
  472. | NoPackage PackageId
  473. -- ^ The requested package was not found
  474. | FoundMultiple [PackageId]
  475. -- ^ _Error_: both in multiple packages
  476. -- | Not found
  477. | NotFound
  478. { fr_paths :: [FilePath] -- Places where I looked
  479. , fr_pkg :: Maybe PackageId -- Just p => module is in this package's
  480. -- manifest, but couldn't find
  481. -- the .hi file
  482. , fr_mods_hidden :: [PackageId] -- Module is in these packages,
  483. -- but the *module* is hidden
  484. , fr_pkgs_hidden :: [PackageId] -- Module is in these packages,
  485. -- but the *package* is hidden
  486. , fr_suggestions :: [Module] -- Possible mis-spelled modules
  487. }
  488. -- | Cache that remembers where we found a particular module. Contains both
  489. -- home modules and package modules. On @:load@, only home modules are
  490. -- purged from this cache.
  491. type ModLocationCache = ModuleEnv ModLocation
  492. \end{code}
  493. %************************************************************************
  494. %* *
  495. \subsection{Symbol tables and Module details}
  496. %* *
  497. %************************************************************************
  498. \begin{code}
  499. -- | A 'ModIface' plus a 'ModDetails' summarises everything we know
  500. -- about a compiled module. The 'ModIface' is the stuff *before* linking,
  501. -- and can be written out to an interface file. The 'ModDetails is after
  502. -- linking and can be completely recovered from just the 'ModIface'.
  503. --
  504. -- When we read an interface file, we also construct a 'ModIface' from it,
  505. -- except that we explicitly make the 'mi_decls' and a few other fields empty;
  506. -- as when reading we consolidate the declarations etc. into a number of indexed
  507. -- maps and environments in the 'ExternalPackageState'.
  508. data ModIface
  509. = ModIface {
  510. mi_module :: !Module, -- ^ Name of the module we are for
  511. mi_iface_hash :: !Fingerprint, -- ^ Hash of the whole interface
  512. mi_mod_hash :: !Fingerprint, -- ^ Hash of the ABI only
  513. mi_flag_hash :: !Fingerprint, -- ^ Hash of the important flags
  514. -- used when compiling this module
  515. mi_orphan :: !WhetherHasOrphans, -- ^ Whether this module has orphans
  516. mi_finsts :: !WhetherHasFamInst, -- ^ Whether this module has family instances
  517. mi_boot :: !IsBootInterface, -- ^ Read from an hi-boot file?
  518. mi_deps :: Dependencies,
  519. -- ^ The dependencies of the module. This is
  520. -- consulted for directly-imported modules, but not
  521. -- for anything else (hence lazy)
  522. mi_usages :: [Usage],
  523. -- ^ Usages; kept sorted so that it's easy to decide
  524. -- whether to write a new iface file (changing usages
  525. -- doesn't affect the hash of this module)
  526. -- NOT STRICT! we read this field lazily from the interface file
  527. -- It is *only* consulted by the recompilation checker
  528. mi_exports :: ![IfaceExport],
  529. -- ^ Exports
  530. -- Kept sorted by (mod,occ), to make version comparisons easier
  531. -- Records the modules that are the declaration points for things
  532. -- exported by this module, and the 'OccName's of those things
  533. mi_exp_hash :: !Fingerprint,
  534. -- ^ Hash of export list
  535. mi_used_th :: !Bool,
  536. -- ^ Module required TH splices when it was compiled.
  537. -- This disables recompilation avoidance (see #481).
  538. mi_fixities :: [(OccName,Fixity)],
  539. -- ^ Fixities
  540. -- NOT STRICT! we read this field lazily from the interface file
  541. mi_warns :: Warnings,
  542. -- ^ Warnings
  543. -- NOT STRICT! we read this field lazily from the interface file
  544. mi_anns :: [IfaceAnnotation],
  545. -- ^ Annotations
  546. -- NOT STRICT! we read this field lazily from the interface file
  547. mi_decls :: [(Fingerprint,IfaceDecl)],
  548. -- ^ Type, class and variable declarations
  549. -- The hash of an Id changes if its fixity or deprecations change
  550. -- (as well as its type of course)
  551. -- Ditto data constructors, class operations, except that
  552. -- the hash of the parent class/tycon changes
  553. mi_globals :: !(Maybe GlobalRdrEnv),
  554. -- ^ Binds all the things defined at the top level in
  555. -- the /original source/ code for this module. which
  556. -- is NOT the same as mi_exports, nor mi_decls (which
  557. -- may contains declarations for things not actually
  558. -- defined by the user). Used for GHCi and for inspecting
  559. -- the contents of modules via the GHC API only.
  560. --
  561. -- (We need the source file to figure out the
  562. -- top-level environment, if we didn't compile this module
  563. -- from source then this field contains @Nothing@).
  564. --
  565. -- Strictly speaking this field should live in the
  566. -- 'HomeModInfo', but that leads to more plumbing.
  567. -- Instance declarations and rules
  568. mi_insts :: [IfaceClsInst], -- ^ Sorted class instance
  569. mi_fam_insts :: [IfaceFamInst], -- ^ Sorted family instances
  570. mi_rules :: [IfaceRule], -- ^ Sorted rules
  571. mi_orphan_hash :: !Fingerprint, -- ^ Hash for orphan rules, class and family
  572. -- instances, and vectorise pragmas combined
  573. mi_vect_info :: !IfaceVectInfo, -- ^ Vectorisation information
  574. -- Cached environments for easy lookup
  575. -- These are computed (lazily) from other fields
  576. -- and are not put into the interface file
  577. mi_warn_fn :: Name -> Maybe WarningTxt, -- ^ Cached lookup for 'mi_warns'
  578. mi_fix_fn :: OccName -> Fixity, -- ^ Cached lookup for 'mi_fixities'
  579. mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint),
  580. -- ^ Cached lookup for 'mi_decls'.
  581. -- The @Nothing@ in 'mi_hash_fn' means that the thing
  582. -- isn't in decls. It's useful to know that when
  583. -- seeing if we are up to date wrt. the old interface.
  584. -- The 'OccName' is the parent of the name, if it has one.
  585. mi_hpc :: !AnyHpcUsage,
  586. -- ^ True if this program uses Hpc at any point in the program.
  587. mi_trust :: !IfaceTrustInfo,
  588. -- ^ Safe Haskell Trust information for this module.
  589. mi_trust_pkg :: !Bool
  590. -- ^ Do we require the package this module resides in be trusted
  591. -- to trust this module? This is used for the situation where a
  592. -- module is Safe (so doesn't require the package be trusted
  593. -- itself) but imports some trustworthy modules from its own
  594. -- package (which does require its own package be trusted).
  595. -- See Note [RnNames . Trust Own Package]
  596. }
  597. -- | The original names declared of a certain module that are exported
  598. type IfaceExport = AvailInfo
  599. -- | Constructs an empty ModIface
  600. emptyModIface :: Module -> ModIface
  601. emptyModIface mod
  602. = ModIface { mi_module = mod,
  603. mi_iface_hash = fingerprint0,
  604. mi_mod_hash = fingerprint0,
  605. mi_flag_hash = fingerprint0,
  606. mi_orphan = False,
  607. mi_finsts = False,
  608. mi_boot = False,
  609. mi_deps = noDependencies,
  610. mi_usages = [],
  611. mi_exports = [],
  612. mi_exp_hash = fingerprint0,
  613. mi_used_th = False,
  614. mi_fixities = [],
  615. mi_warns = NoWarnings,
  616. mi_anns = [],
  617. mi_insts = [],
  618. mi_fam_insts = [],
  619. mi_rules = [],
  620. mi_decls = [],
  621. mi_globals = Nothing,
  622. mi_orphan_hash = fingerprint0,
  623. mi_vect_info = noIfaceVectInfo,
  624. mi_warn_fn = emptyIfaceWarnCache,
  625. mi_fix_fn = emptyIfaceFixCache,
  626. mi_hash_fn = emptyIfaceHashCache,
  627. mi_hpc = False,
  628. mi_trust = noIfaceTrustInfo,
  629. mi_trust_pkg = False }
  630. -- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
  631. mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
  632. -> (OccName -> Maybe (OccName, Fingerprint))
  633. mkIfaceHashCache pairs
  634. = \occ -> lookupOccEnv env occ
  635. where
  636. env = foldr add_decl emptyOccEnv pairs
  637. add_decl (v,d) env0 = foldr add env0 (ifaceDeclFingerprints v d)
  638. where
  639. add (occ,hash) env0 = extendOccEnv env0 occ (occ,hash)
  640. emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
  641. emptyIfaceHashCache _occ = Nothing
  642. -- | The 'ModDetails' is essentially a cache for information in the 'ModIface'
  643. -- for home modules only. Information relating to packages will be loaded into
  644. -- global environments in 'ExternalPackageState'.
  645. data ModDetails
  646. = ModDetails {
  647. -- The next two fields are created by the typechecker
  648. md_exports :: [AvailInfo],
  649. md_types :: !TypeEnv, -- ^ Local type environment for this particular module
  650. md_insts :: ![ClsInst], -- ^ 'DFunId's for the instances in this module
  651. md_fam_insts :: ![FamInst],
  652. md_rules :: ![CoreRule], -- ^ Domain may include 'Id's from other modules
  653. md_anns :: ![Annotation], -- ^ Annotations present in this module: currently
  654. -- they only annotate things also declared in this module
  655. md_vect_info :: !VectInfo -- ^ Module vectorisation information
  656. }
  657. -- | Constructs an empty ModDetails
  658. emptyModDetails :: ModDetails
  659. emptyModDetails
  660. = ModDetails { md_types = emptyTypeEnv,
  661. md_exports = [],
  662. md_insts = [],
  663. md_rules = [],
  664. md_fam_insts = [],
  665. md_anns = [],
  666. md_vect_info = noVectInfo }
  667. -- | Records the modules directly imported by a module for extracting e.g. usage information
  668. type ImportedMods = ModuleEnv [ImportedModsVal]
  669. type ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
  670. -- | A ModGuts is carried through the compiler, accumulating stuff as it goes
  671. -- There is only one ModGuts at any time, the one for the module
  672. -- being compiled right now. Once it is compiled, a 'ModIface' and
  673. -- 'ModDetails' are extracted and the ModGuts is discarded.
  674. data ModGuts
  675. = ModGuts {
  676. mg_module :: !Module, -- ^ Module being compiled
  677. mg_boot :: IsBootInterface, -- ^ Whether it's an hs-boot module
  678. mg_exports :: ![AvailInfo], -- ^ What it exports
  679. mg_deps :: !Dependencies, -- ^ What it depends on, directly or
  680. -- otherwise
  681. mg_dir_imps :: !ImportedMods, -- ^ Directly-imported modules; used to
  682. -- generate initialisation code
  683. mg_used_names:: !NameSet, -- ^ What the module needed (used in 'MkIface.mkIface')
  684. mg_used_th :: !Bool, -- ^ Did we run a TH splice?
  685. mg_rdr_env :: !GlobalRdrEnv, -- ^ Top-level lexical environment
  686. -- These fields all describe the things **declared in this module**
  687. mg_fix_env :: !FixityEnv, -- ^ Fixities declared in this module
  688. -- ToDo: I'm unconvinced this is actually used anywhere
  689. mg_tcs :: ![TyCon], -- ^ TyCons declared in this module
  690. -- (includes TyCons for classes)
  691. mg_insts :: ![ClsInst], -- ^ Class instances declared in this module
  692. mg_fam_insts :: ![FamInst], -- ^ Family instances declared in this module
  693. mg_rules :: ![CoreRule], -- ^ Before the core pipeline starts, contains
  694. -- See Note [Overall plumbing for rules] in Rules.lhs
  695. mg_binds :: !CoreProgram, -- ^ Bindings for this module
  696. mg_foreign :: !ForeignStubs, -- ^ Foreign exports declared in this module
  697. mg_warns :: !Warnings, -- ^ Warnings declared in the module
  698. mg_anns :: [Annotation], -- ^ Annotations declared in this module
  699. mg_hpc_info :: !HpcInfo, -- ^ Coverage tick boxes in the module
  700. mg_modBreaks :: !ModBreaks, -- ^ Breakpoints for the module
  701. mg_vect_decls:: ![CoreVect], -- ^ Vectorisation declarations in this module
  702. -- (produced by desugarer & consumed by vectoriser)
  703. mg_vect_info :: !VectInfo, -- ^ Pool of vectorised declarations in the module
  704. -- The next two fields are unusual, because they give instance
  705. -- environments for *all* modules in the home package, including
  706. -- this module, rather than for *just* this module.
  707. -- Reason: when looking up an instance we don't want to have to
  708. -- look at each module in the home package in turn
  709. mg_inst_env :: InstEnv,
  710. -- ^ Class instance environment from /home-package/ modules (including
  711. -- this one); c.f. 'tcg_inst_env'
  712. mg_fam_inst_env :: FamInstEnv,
  713. -- ^ Type-family instance enviroment for /home-package/ modules
  714. -- (including this one); c.f. 'tcg_fam_inst_env'
  715. mg_safe_haskell :: SafeHaskellMode,
  716. -- ^ Safe Haskell mode
  717. mg_trust_pkg :: Bool,
  718. -- ^ Do we need to trust our own package for Safe Haskell?
  719. -- See Note [RnNames . Trust Own Package]
  720. mg_dependent_files :: [FilePath] -- ^ dependencies from addDependentFile
  721. }
  722. -- The ModGuts takes on several slightly different forms:
  723. --
  724. -- After simplification, the following fields change slightly:
  725. -- mg_rules Orphan rules only (local ones now attached to binds)
  726. -- mg_binds With rules attached
  727. ---------------------------------------------------------
  728. -- The Tidy pass forks the information about this module:
  729. -- * one lot goes to interface file generation (ModIface)
  730. -- and later compilations (ModDetails)
  731. -- * the other lot goes to code generation (CgGuts)
  732. -- | A restricted form of 'ModGuts' for code generation purposes
  733. data CgGuts
  734. = CgGuts {
  735. cg_module :: !Module,
  736. -- ^ Module being compiled
  737. cg_tycons :: [TyCon],
  738. -- ^ Algebraic data types (including ones that started
  739. -- life as classes); generate constructors and info
  740. -- tables. Includes newtypes, just for the benefit of
  741. -- External Core
  742. cg_binds :: CoreProgram,
  743. -- ^ The tidied main bindings, including
  744. -- previously-implicit bindings for record and class
  745. -- selectors, and data construtor wrappers. But *not*
  746. -- data constructor workers; reason: we we regard them
  747. -- as part of the code-gen of tycons
  748. cg_foreign :: !ForeignStubs, -- ^ Foreign export stubs
  749. cg_dep_pkgs :: ![PackageId], -- ^ Dependent packages, used to
  750. -- generate #includes for C code gen
  751. cg_hpc_info :: !HpcInfo, -- ^ Program coverage tick box information
  752. cg_modBreaks :: !ModBreaks -- ^ Module breakpoints
  753. }
  754. -----------------------------------
  755. -- | Foreign export stubs
  756. data ForeignStubs
  757. = NoStubs
  758. -- ^ We don't have any stubs
  759. | ForeignStubs SDoc SDoc
  760. -- ^ There are some stubs. Parameters:
  761. --
  762. -- 1) Header file prototypes for
  763. -- "foreign exported" functions
  764. --
  765. -- 2) C stubs to use when calling
  766. -- "foreign exported" functions
  767. appendStubC :: ForeignStubs -> SDoc -> ForeignStubs
  768. appendStubC NoStubs c_code = ForeignStubs empty c_code
  769. appendStubC (ForeignStubs h c) c_code = ForeignStubs h (c $$ c_code)
  770. \end{code}
  771. %************************************************************************
  772. %* *
  773. \subsection{The interactive context}
  774. %* *
  775. %************************************************************************
  776. \begin{code}
  777. -- | Interactive context, recording information about the state of the
  778. -- context in which statements are executed in a GHC session.
  779. data InteractiveContext
  780. = InteractiveContext {
  781. ic_dflags :: DynFlags,
  782. -- ^ The 'DynFlags' used to evaluate interative expressions
  783. -- and statements.
  784. ic_monad :: Name,
  785. -- ^ The monad that GHCi is executing in
  786. ic_imports :: [InteractiveImport],
  787. -- ^ The GHCi context is extended with these imports
  788. --
  789. -- This field is only stored here so that the client
  790. -- can retrieve it with GHC.getContext. GHC itself doesn't
  791. -- use it, but does reset it to empty sometimes (such
  792. -- as before a GHC.load). The context is set with GHC.setContext.
  793. ic_rn_gbl_env :: GlobalRdrEnv,
  794. -- ^ The cached 'GlobalRdrEnv', built by
  795. -- 'InteractiveEval.setContext' and updated regularly
  796. ic_tythings :: [TyThing],
  797. -- ^ TyThings defined by the user, in reverse order of
  798. -- definition. At a breakpoint, this list includes the
  799. -- local variables in scope at that point
  800. ic_sys_vars :: [Id],
  801. -- ^ Variables defined automatically by the system (e.g.
  802. -- record field selectors). See Notes [ic_sys_vars]
  803. ic_instances :: ([ClsInst], [FamInst]),
  804. -- ^ All instances and family instances created during
  805. -- this session. These are grabbed en masse after each
  806. -- update to be sure that proper overlapping is retained.
  807. -- That is, rather than re-check the overlapping each
  808. -- time we update the context, we just take the results
  809. -- from the instance code that already does that.
  810. ic_fix_env :: FixityEnv,
  811. -- ^ Fixities declared in let statements
  812. ic_int_print :: Name,
  813. -- ^ The function that is used for printing results
  814. -- of expressions in ghci and -e mode.
  815. ic_default :: Maybe [Type],
  816. -- ^ The current default types, set by a 'default' declaration
  817. #ifdef GHCI
  818. ic_resume :: [Resume],
  819. -- ^ The stack of breakpoint contexts
  820. #endif
  821. ic_cwd :: Maybe FilePath
  822. -- virtual CWD of the program
  823. }
  824. {-
  825. Note [ic_sys_vars]
  826. ~~~~~~~~~~~~~~~~~~
  827. This list constains any Ids that arise from TyCons, Classes or
  828. instances defined interactively, but that are not given by
  829. 'implicitTyThings'. This includes record selectors, default methods,
  830. and dfuns.
  831. We *could* get rid of this list and generate these Ids from
  832. ic_tythings:
  833. - dfuns come from Instances
  834. - record selectors from TyCons
  835. - default methods from Classes
  836. For record selectors the TyCon gives the Name, but in order to make an
  837. Id we would have to construct the type ourselves. Similarly for
  838. default methods. So for now we collect the Ids after tidying (see
  839. hscDeclsWithLocation) and save them in ic_sys_vars.
  840. -}
  841. -- | Constructs an empty InteractiveContext.
  842. emptyInteractiveContext :: DynFlags -> InteractiveContext
  843. emptyInteractiveContext dflags
  844. = InteractiveContext { ic_dflags = dflags,
  845. -- IO monad by default
  846. ic_monad = ioTyConName,
  847. ic_imports = [],
  848. ic_rn_gbl_env = emptyGlobalRdrEnv,
  849. ic_tythings = [],
  850. ic_sys_vars = [],
  851. ic_instances = ([],[]),
  852. ic_fix_env = emptyNameEnv,
  853. -- System.IO.print by default
  854. ic_int_print = printName,
  855. ic_default = Nothing,
  856. #ifdef GHCI
  857. ic_resume = [],
  858. #endif
  859. ic_cwd = Nothing }
  860. -- | This function returns the list of visible TyThings (useful for
  861. -- e.g. showBindings)
  862. icInScopeTTs :: InteractiveContext -> [TyThing]
  863. icInScopeTTs = ic_tythings
  864. -- | Get the PrintUnqualified function based on the flags and this InteractiveContext
  865. icPrintUnqual :: DynFlags -> InteractiveContext -> PrintUnqualified
  866. icPrintUnqual dflags InteractiveContext{ ic_rn_gbl_env = grenv } =
  867. mkPrintUnqualified dflags grenv
  868. -- | This function is called with new TyThings recently defined to update the
  869. -- InteractiveContext to include them. Ids are easily removed when shadowed,
  870. -- but Classes and TyCons are not. Some work could be done to determine
  871. -- whether they are entirely shadowed, but as you could still have references
  872. -- to them (e.g. instances for classes or values of the type for TyCons), it's
  873. -- not clear whether removing them is even the appropriate behavior.
  874. extendInteractiveContext :: InteractiveContext -> [TyThing] -> InteractiveContext
  875. extendInteractiveContext ictxt new_tythings
  876. = ictxt { ic_tythings = new_tythings ++ old_tythings
  877. , ic_rn_gbl_env = new_tythings `icPlusGblRdrEnv` ic_rn_gbl_env ictxt
  878. }
  879. where
  880. old_tythings = filter (not . shadowed) (ic_tythings ictxt)
  881. shadowed (AnId id) = ((`elem` new_names) . nameOccName . idName) id
  882. shadowed _ = False
  883. new_names = [ nameOccName (getName id) | AnId id <- new_tythings ]
  884. setInteractivePrintName :: InteractiveContext -> Name -> InteractiveContext
  885. setInteractivePrintName ic n = ic{ic_int_print = n}
  886. -- ToDo: should not add Ids to the gbl env here
  887. -- | Add TyThings to the GlobalRdrEnv, earlier ones in the list shadowing
  888. -- later ones, and shadowing existing entries in the GlobalRdrEnv.
  889. icPlusGblRdrEnv :: [TyThing] -> GlobalRdrEnv -> GlobalRdrEnv
  890. icPlusGblRdrEnv tythings env = extendOccEnvList env list
  891. where new_gres = gresFromAvails LocalDef (map tyThingAvailInfo tythings)
  892. list = [ (nameOccName (gre_name gre), [gre]) | gre <- new_gres ]
  893. substInteractiveContext :: InteractiveContext -> TvSubst -> InteractiveContext
  894. substInteractiveContext ictxt subst
  895. | isEmptyTvSubst subst = ictxt
  896. substInteractiveContext ictxt@InteractiveContext{ ic_tythings = tts } subst
  897. = ictxt { ic_tythings = map subst_ty tts }
  898. where subst_ty (AnId id) = AnId $ id `setIdType` substTy subst (idType id)
  899. subst_ty tt = tt
  900. data InteractiveImport
  901. = IIDecl (ImportDecl RdrName)
  902. -- ^ Bring the exports of a particular module
  903. -- (filtered by an import decl) into scope
  904. | IIModule ModuleName
  905. -- ^ Bring into scope the entire top-level envt of
  906. -- of this module, including the things imported
  907. -- into it.
  908. instance Outputable InteractiveImport where
  909. ppr (IIModule m) = char '*' <> ppr m
  910. ppr (IIDecl d) = ppr d
  911. \end{code}
  912. %************************************************************************
  913. %* *
  914. Building a PrintUnqualified
  915. %* *
  916. %************************************************************************
  917. Note [Printing original names]
  918. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  919. Deciding how to print names is pretty tricky. We are given a name
  920. P:M.T, where P is the package name, M is the defining module, and T is
  921. the occurrence name, and we have to decide in which form to display
  922. the name given a GlobalRdrEnv describing the current scope.
  923. Ideally we want to display the name in the form in which it is in
  924. scope. However, the name might not be in scope at all, and that's
  925. where it gets tricky. Here are the cases:
  926. 1. T uniquely maps to P:M.T ---> "T" NameUnqual
  927. 2. There is an X for which X.T
  928. uniquely maps to P:M.T ---> "X.T" NameQual X
  929. 3. There is no binding for "M.T" ---> "M.T" NameNotInScope1
  930. 4. Otherwise ---> "P:M.T" NameNotInScope2
  931. (3) and (4) apply when the entity P:M.T is not in the GlobalRdrEnv at
  932. all. In these cases we still want to refer to the name as "M.T", *but*
  933. "M.T" might mean something else in the current scope (e.g. if there's
  934. an "import X as M"), so to avoid confusion we avoid using "M.T" if
  935. there's already a binding for it. Instead we write P:M.T.
  936. There's one further subtlety: in case (3), what if there are two
  937. things around, P1:M.T and P2:M.T? Then we don't want to print both of
  938. them as M.T! However only one of the modules P1:M and P2:M can be
  939. exposed (say P2), so we use M.T for that, and P1:M.T for the other one.
  940. This is handled by the qual_mod component of PrintUnqualified, inside
  941. the (ppr mod) of case (3), in Name.pprModulePrefix
  942. \begin{code}
  943. -- | Creates some functions that work out the best ways to format
  944. -- names for the user according to a set of heuristics
  945. mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified
  946. mkPrintUnqualified dflags env = (qual_name, qual_mod)
  947. where
  948. qual_name name
  949. | [gre] <- unqual_gres, right_name gre = NameUnqual
  950. -- If there's a unique entity that's in scope unqualified with 'occ'
  951. -- AND that entity is the right one, then we can use the unqualified name
  952. | [gre] <- qual_gres = NameQual (get_qual_mod (gre_prov gre))
  953. | null qual_gres =
  954. if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env)
  955. then NameNotInScope1
  956. else NameNotInScope2
  957. | otherwise = NameNotInScope1 -- Can happen if 'f' is bound twice in the module
  958. -- Eg f = True; g = 0; f = False
  959. where
  960. mod = nameModule name
  961. occ = nameOccName name
  962. is_rdr_orig = nameUnique name == mkUniqueGrimily 0
  963. -- Note [Outputable Orig RdrName]
  964. right_name gre
  965. | is_rdr_orig = nameModule_maybe (gre_name gre) == Just mod
  966. | otherwise = gre_name gre == name
  967. unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
  968. qual_gres = filter right_name (lookupGlobalRdrEnv env occ)
  969. get_qual_mod LocalDef = moduleName mod
  970. get_qual_mod (Imported is) = ASSERT( not (null is) ) is_as (is_decl (head is))
  971. -- we can mention a module P:M without the P: qualifier iff
  972. -- "import M" would resolve unambiguously to P:M. (if P is the
  973. -- current package we can just assume it is unqualified).
  974. qual_mod mod
  975. | modulePackageId mod == thisPackage dflags = False
  976. | [pkgconfig] <- [pkg | (pkg,exposed_module) <- lookup,
  977. exposed pkg && exposed_module],
  978. packageConfigId pkgconfig == modulePackageId mod
  979. -- this says: we are given a module P:M, is there just one exposed package
  980. -- that exposes a module M, and is it package P?
  981. = False
  982. | otherwise = True
  983. where lookup = lookupModuleInAllPackages dflags (moduleName mod)
  984. -- Note [Outputable Orig RdrName]
  985. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  986. -- This is a Grotesque Hack. The Outputable instance for RdrEnv wants
  987. -- to print Orig names, which are just pairs of (Module,OccName). But
  988. -- we want to use full Names here, because in GHCi we might have Ids
  989. -- that have the same (Module,OccName) pair but a different Unique
  990. -- (this happens when you shadow a TyCon or Class in GHCi).
  991. --
  992. -- So in Outputable RdrName we just use a dummy Unique (0), and check
  993. -- for it here.
  994. --
  995. -- Arguably GHCi is invalidating the assumption that (Module,OccName)
  996. -- uniquely identifies an entity. But we do want to be able to shadow
  997. -- old declarations with new ones in GHCi, and it would be hard to
  998. -- delete all references to the old declaration when that happened.
  999. -- See also Note [interactive name cache] in IfaceEnv for somewhere
  1000. -- else that this broken assumption bites.
  1001. --
  1002. \end{code}
  1003. %************************************************************************
  1004. %* *
  1005. Implicit TyThings
  1006. %* *
  1007. %************************************************************************
  1008. Note [Implicit TyThings]
  1009. ~~~~~~~~~~~~~~~~~~~~~~~~
  1010. DEFINITION: An "implicit" TyThing is one that does not have its own
  1011. IfaceDecl in an interface file. Instead, its binding in the type
  1012. environment is created as part of typechecking the IfaceDecl for
  1013. some other thing.
  1014. Examples:
  1015. * All DataCons are implicit, because they are generated from the
  1016. IfaceDecl for the data/newtype. Ditto class methods.
  1017. * Record selectors are *not* implicit, because they get their own
  1018. free-standing IfaceDecl.
  1019. * Associated data/type families are implicit because they are
  1020. included in the IfaceDecl of the parent class. (NB: the
  1021. IfaceClass decl happens to use IfaceDecl recursively for the
  1022. associated types, but that's irrelevant here.)
  1023. * Dictionary function Ids are not implict.
  1024. * Axioms for newtypes are implicit (same as above), but axioms
  1025. for data/type family instances are *not* implicit (like DFunIds).
  1026. \begin{code}
  1027. -- | Determine the 'TyThing's brought into scope by another 'TyThing'
  1028. -- /other/ than itself. For example, Id's don't have any implicit TyThings
  1029. -- as they just bring themselves into scope, but classes bring their
  1030. -- dictionary datatype, type constructor and some selector functions into
  1031. -- scope, just for a start!
  1032. -- N.B. the set of TyThings returned here *must* match the set of
  1033. -- names returned by LoadIface.ifaceDeclImplicitBndrs, in the sense that
  1034. -- TyThing.getOccName should define a bijection between the two lists.
  1035. -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
  1036. -- The order of the list does not matter.
  1037. implicitTyThings :: TyThing -> [TyThing]
  1038. implicitTyThings (AnId _) = []
  1039. implicitTyThings (ACoAxiom _cc) = []
  1040. implicitTyThings (ATyCon tc) = implicitTyConThings tc
  1041. implicitTyThings (ADataCon dc) = map AnId (dataConImplicitIds dc)
  1042. -- For data cons add the worker and (possibly) wrapper
  1043. implicitClassThings :: Class -> [TyThing]
  1044. implicitClassThings cl
  1045. = -- Does not include default methods, because those Ids may have
  1046. -- their own pragmas, unfoldings etc, not derived from the Class object
  1047. -- associated types
  1048. -- No extras_plus (recursive call) for the classATs, because they
  1049. -- are only the family decls; they have no implicit things
  1050. map ATyCon (classATs cl) ++
  1051. -- superclass and operation selectors
  1052. map AnId (classAllSelIds cl)
  1053. implicitTyConThings :: TyCon -> [TyThing]
  1054. implicitTyConThings tc
  1055. = class_stuff ++
  1056. -- fields (names of selectors)
  1057. -- (possibly) implicit newtype coercion
  1058. implicitCoTyCon tc ++
  1059. -- for each data constructor in order,
  1060. -- the contructor, worker, and (possibly) wrapper
  1061. concatMap (extras_plus . ADataCon) (tyConDataCons tc)
  1062. -- NB. record selectors are *not* implicit, they have fully-fledged
  1063. -- bindings that pass through the compilation pipeline as normal.
  1064. where
  1065. class_stuff = case tyConClass_maybe tc of
  1066. Nothing -> []
  1067. Just cl -> implicitClassThings cl
  1068. -- add a thing and recursive call
  1069. extras_plus :: TyThing -> [TyThing]
  1070. extras_plus thing = thing : implicitTyThings thing
  1071. -- For newtypes (only) add the implicit coercion tycon
  1072. implicitCoTyCon :: TyCon -> [TyThing]
  1073. implicitCoTyCon tc
  1074. | Just co <- newTyConCo_maybe tc = [ACoAxiom co]
  1075. | otherwise = []
  1076. -- | Returns @True@ if there should be no interface-file declaration
  1077. -- for this thing on its own: either it is built-in, or it is part
  1078. -- of some other declaration, or it is generated implicitly by some
  1079. -- other declaration.
  1080. isImplicitTyThing :: TyThing -> Bool
  1081. isImplicitTyThing (ADataCon {}) = True
  1082. isImplicitTyThing (AnId id) = isImplicitId id
  1083. isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc
  1084. isImplicitTyThing (ACoAxiom ax) = isImplicitCoAxiom ax
  1085. -- | tyThingParent_maybe x returns (Just p)
  1086. -- when pprTyThingInContext sould print a declaration for p
  1087. -- (albeit with some "..." in it) when asked to show x
  1088. -- It returns the *immediate* parent. So a datacon returns its tycon
  1089. -- but the tycon could be the associated type of a class, so it in turn
  1090. -- might have a parent.
  1091. tyThingParent_maybe :: TyThing -> Maybe TyThing
  1092. tyThingParent_maybe (ADataCon dc) = Just (ATyCon (dataConTyCon dc))
  1093. tyThingParent_maybe (ATyCon tc) = case tyConAssoc_maybe tc of
  1094. Just cls -> Just (ATyCon (classTyCon cls))
  1095. Nothing -> Nothing
  1096. tyThingParent_maybe (AnId id) = case idDetails id of
  1097. RecSelId { sel_tycon = tc } -> Just (ATyCon tc)
  1098. ClassOpId cls -> Just (ATyCon (classTyCon cls))
  1099. _other -> Nothing
  1100. tyThingParent_maybe _other = Nothing
  1101. tyThingsTyVars :: [TyThing] -> TyVarSet
  1102. tyThingsTyVars tts =
  1103. unionVarSets $ map ttToVarSet tts
  1104. where
  1105. ttToVarSet (AnId id) = tyVarsOfType $ idType id
  1106. ttToVarSet (ADataCon dc) = tyVarsOfType $ dataConRepType dc
  1107. ttToVarSet (ATyCon tc)
  1108. = case tyConClass_maybe tc of
  1109. Just cls -> (mkVarSet . fst . classTvsFds) cls
  1110. Nothing -> tyVarsOfType $ tyConKind tc
  1111. ttToVarSet _ = emptyVarSet
  1112. -- | The Names that a TyThing should bring into scope. Used to build
  1113. -- the GlobalRdrEnv for the InteractiveContext.
  1114. tyThingAvailInfo :: TyThing -> AvailInfo
  1115. tyThingAvailInfo (ATyCon t)
  1116. = case tyConClass_maybe t of
  1117. Just c -> AvailTC n (n : map getName (classMethods c)
  1118. ++ map getName (classATs c))
  1119. where n = getName c
  1120. Nothing -> AvailTC n (n : map getName dcs ++
  1121. concatMap dataConFieldLabels dcs)
  1122. where n = getName t
  1123. dcs = tyConDataCons t
  1124. tyThingAvailInfo t
  1125. = Avail (getName t)
  1126. \end{code}
  1127. %************************************************************************
  1128. %* *
  1129. TypeEnv
  1130. %* *
  1131. %************************************************************************
  1132. \begin{code}
  1133. -- | A map from 'Name's to 'TyThing's, constructed by typechecking
  1134. -- local declarations or interface files
  1135. type TypeEnv = NameEnv TyThing
  1136. emptyTypeEnv :: TypeEnv
  1137. typeEnvElts :: TypeEnv -> [TyThing]
  1138. typeEnvTyCons :: TypeEnv -> [TyCon]
  1139. typeEnvCoAxioms :: TypeEnv -> [CoAxiom]
  1140. typeEnvIds :: TypeEnv -> [Id]
  1141. typeEnvDataCons :: TypeEnv -> [DataCon]
  1142. typeEnvClasses :: TypeEnv -> [Class]
  1143. lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
  1144. emptyTypeEnv = emptyNameEnv
  1145. typeEnvElts env = nameEnvElts env
  1146. typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
  1147. typeEnvCoAxioms env = [ax | ACoAxiom ax <- typeEnvElts env]
  1148. typeEnvIds env = [id | AnId id <- typeEnvElts env]
  1149. typeEnvDataCons env = [dc | ADataCon dc <- typeEnvElts env]
  1150. typeEnvClasses env = [cl | tc <- typeEnvTyCons env,
  1151. Just cl <- [tyConClass_maybe tc]]
  1152. mkTypeEnv :: [TyThing] -> TypeEnv
  1153. mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
  1154. mkTypeEnvWithImplicits :: [TyThing] -> TypeEnv
  1155. mkTypeEnvWithImplicits things =
  1156. mkTypeEnv things
  1157. `plusNameEnv`
  1158. mkTypeEnv (concatMap implicitTyThings things)
  1159. typeEnvFromEntities :: [Id] -> [TyCon] -> [FamInst] -> TypeEnv
  1160. typeEnvFromEntities ids tcs famInsts =
  1161. mkTypeEnv ( map AnId ids
  1162. ++ map ATyCon all_tcs
  1163. ++ concatMap implicitTyConThings all_tcs
  1164. ++ map (ACoAxiom . famInstAxiom) famInsts
  1165. )
  1166. where
  1167. all_tcs = tcs ++ famInstsRepTyCons famInsts
  1168. lookupTypeEnv = lookupNameEnv
  1169. -- Extend the type environment
  1170. extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
  1171. extendTypeEnv env thing = extendNameEnv env (getName thing) thing
  1172. extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
  1173. extendTypeEnvList env things = foldl extendTypeEnv env things
  1174. extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
  1175. extendTypeEnvWithIds env ids
  1176. = extendNameEnvList env [(getName id, AnId id) | id <- ids]
  1177. \end{code}
  1178. \begin{code}
  1179. -- | Find the 'TyThing' for the given 'Name' by using all the resources
  1180. -- at our disposal: the compiled modules in the 'HomePackageTable' and the
  1181. -- compiled modules in other packages that live in 'PackageTypeEnv'. Note
  1182. -- that this does NOT look up the 'TyThing' in the module being compiled: you
  1183. -- have to do that yourself, if desired
  1184. lookupType :: DynFlags
  1185. -> HomePackageTable
  1186. -> PackageTypeEnv
  1187. -> Name
  1188. -> Maybe TyThing
  1189. lookupType dflags hpt pte name
  1190. -- in one-shot, we don't use the HPT
  1191. | not (isOneShot (ghcMode dflags)) && modulePackageId mod == this_pkg
  1192. = do hm <- lookupUFM hpt (moduleName mod) -- Maybe monad
  1193. lookupNameEnv (md_types (hm_details hm)) name
  1194. | otherwise
  1195. = lookupNameEnv pte name
  1196. where
  1197. mod = ASSERT2( isExternalName name, ppr name ) nameModule name
  1198. this_pkg = thisPackage dflags
  1199. -- | As 'lookupType', but with a marginally easier-to-use interface
  1200. -- if you have a 'HscEnv'
  1201. lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing)
  1202. lookupTypeHscEnv hsc_env name = do
  1203. eps <- readIORef (hsc_EPS hsc_env)
  1204. return $! lookupType dflags hpt (eps_PTE eps) name
  1205. where
  1206. dflags = hsc_dflags hsc_env
  1207. hpt = hsc_HPT hsc_env
  1208. \end{code}
  1209. \begin{code}
  1210. -- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise
  1211. tyThingTyCon :: TyThing -> TyCon
  1212. tyThingTyCon (ATyCon tc) = tc
  1213. tyThingTyCon other = pprPanic "tyThingTyCon" (pprTyThing other)
  1214. -- | Get the 'CoAxiom' from a 'TyThing' if it is a coercion axiom thing. Panics otherwise
  1215. tyThingCoAxiom :: TyThing -> CoAxiom
  1216. tyThingCoAxiom (ACoAxiom ax) = ax
  1217. tyThingCoAxiom other = pprPanic "tyThingCoAxiom" (pprTyThing other)
  1218. -- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise
  1219. tyThingDataCon :: TyThing -> DataCon
  1220. tyThingDataCon (ADataCon dc) = dc
  1221. tyThingDataCon other = pprPanic "tyThingDataCon" (pprTyThing other)
  1222. -- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise
  1223. tyThingId :: TyThing -> Id
  1224. tyThingId (AnId id) = id
  1225. tyThingId (ADataCon dc) = dataConWrapId dc
  1226. tyThingId other = pprPanic "tyThingId" (pprTyThing other)
  1227. \end{code}
  1228. %************************************************************************
  1229. %* *
  1230. \subsection{MonadThings and friends}
  1231. %* *
  1232. %************************************************************************
  1233. \begin{code}
  1234. -- | Class that abstracts out the common ability of the monads in GHC
  1235. -- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides
  1236. -- a number of related convenience functions for accessing particular
  1237. -- kinds of 'TyThing'
  1238. class Monad m => MonadThings m where
  1239. lookupThing :: Name -> m TyThing
  1240. lookupId :: Name -> m Id
  1241. lookupId = liftM tyThingId . lookupThing
  1242. lookupDataCon :: Name -> m DataCon
  1243. lookupDataCon = liftM tyThingDataCon . lookupThing
  1244. lookupTyCon :: Name -> m TyCon
  1245. lookupTyCon = liftM tyThingTyCon . lookupThing
  1246. \end{code}
  1247. %************************************************************************
  1248. %* *
  1249. \subsection{Auxiliary types}
  1250. %* *
  1251. %************************************************************************
  1252. These types are defined here because they are mentioned in ModDetails,
  1253. but they are mostly elaborated elsewhere
  1254. \begin{code}
  1255. ------------------ Warnings -------------------------
  1256. -- | Warning information for a module
  1257. data Warnings
  1258. = NoWarnings -- ^ Nothing deprecated
  1259. | WarnAll WarningTxt -- ^ Whole module deprecated
  1260. | WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated
  1261. -- Only an OccName is needed because
  1262. -- (1) a deprecation always applies to a binding
  1263. -- defined in the module in which the deprecation appears.
  1264. -- (2) deprecations are only reported outside the defining module.
  1265. -- this is important because, otherwise, if we saw something like
  1266. --
  1267. -- {-# DEPRECATED f "" #-}
  1268. -- f = ...
  1269. -- h = f
  1270. -- g = let f = undefined in f
  1271. --
  1272. -- we'd need more information than an OccName to know to say something
  1273. -- about the use of f in h but not the use of the locally bound f in g
  1274. --
  1275. -- however, because we only report about deprecations from the outside,
  1276. -- and a module can only export one value called f,
  1277. -- an OccName suffices.
  1278. --
  1279. -- this is in contrast with fixity declarations, where we need to map
  1280. -- a Name to its fixity declaration.
  1281. deriving( Eq )
  1282. -- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface'
  1283. mkIfaceWarnCache :: Warnings -> Name -> Maybe WarningTxt
  1284. mkIfaceWarnCache NoWarnings = \_ -> Nothing
  1285. mkIfaceWarnCache (WarnAll t) = \_ -> Just t
  1286. mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
  1287. emptyIfaceWarnCache :: Name -> Maybe WarningTxt
  1288. emptyIfaceWarnCache _ = Nothing
  1289. plusWarns :: Warnings -> Warnings -> Warnings
  1290. plusWarns d NoWarnings = d
  1291. plusWarns NoWarnings d = d
  1292. plusWarns _ (WarnAll t) = WarnAll t
  1293. plusWarns (WarnAll t) _ = WarnAll t
  1294. plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2)
  1295. \end{code}
  1296. \begin{code}
  1297. -- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface'
  1298. mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
  1299. mkIfaceFixCache pairs
  1300. = \n -> lookupOccEnv env n `orElse` defaultFixity
  1301. where
  1302. env = mkOccEnv pairs
  1303. emptyIfaceFixCache :: OccName -> Fixity
  1304. emptyIfaceFixCache _ = defaultFixity
  1305. -- | Fixity environment mapping names to their fixities
  1306. type FixityEnv = NameEnv FixItem
  1307. -- | Fixity information for an 'Name'. We keep the OccName in the range
  1308. -- so that we can generate an interface from it
  1309. data FixItem = FixItem OccName Fixity
  1310. instance Outputable FixItem where
  1311. ppr (FixItem occ fix) = ppr fix <+> ppr occ
  1312. emptyFixityEnv :: FixityEnv
  1313. emptyFixityEnv = emptyNameEnv
  1314. lookupFixity :: FixityEnv -> Name -> Fixity
  1315. lookupFixity env n = case lookupNameEnv env n of
  1316. Just (FixItem _ fix) -> fix
  1317. Nothing -> defaultFixity
  1318. \end{code}
  1319. %************************************************************************
  1320. %* *
  1321. \subsection{WhatsImported}
  1322. %* *
  1323. %************************************************************************
  1324. \begin{code}
  1325. -- | Records whether a module has orphans. An \"orphan\" is one of:
  1326. --
  1327. -- * An instance declaration in a module other than the definition
  1328. -- module for one of the type constructors or classes in the instance head
  1329. --
  1330. -- * A transformation rule in a module other than the one defining
  1331. -- the function in the head of the rule
  1332. --
  1333. -- * A vectorisation pragma
  1334. type WhetherHasOrphans = Bool
  1335. -- | Does this module define family instances?
  1336. type WhetherHasFamInst = Bool
  1337. -- | Did this module originate from a *-boot file?
  1338. type IsBootInterface = Bool
  1339. -- | Dependency information about modules and packages below this one
  1340. -- in the import hierarchy.
  1341. --
  1342. -- Invariant: the dependencies of a module @M@ never includes @M@.
  1343. --
  1344. -- Invariant: none of the lists contain duplicates.
  1345. data Dependencies
  1346. = Deps { dep_mods :: [(ModuleName, IsBootInterface)]
  1347. -- ^ Home-package module dependencies
  1348. , dep_pkgs :: [(PackageId, Bool)]
  1349. -- ^ External package dependencies. The bool indicates
  1350. -- if the package is required to be trusted when the
  1351. -- module is imported as a safe import (Safe Haskell).
  1352. -- See Note [RnNames . Tracking Trust Transitively]
  1353. , dep_orphs :: [Module]
  1354. -- ^ Orphan modules (whether home or external pkg),
  1355. -- *not* including family instance orphans as they
  1356. -- are anyway included in 'dep_finsts'
  1357. , dep_finsts :: [Module]
  1358. -- ^ Modules that contain family instances (whether the
  1359. -- instances are from the home or an external package)
  1360. }
  1361. deriving( Eq )
  1362. -- Equality used only for old/new comparison in MkIface.addFingerprints
  1363. -- See 'TcRnTypes.ImportAvails' for details on dependencies.
  1364. noDependencies :: Dependencies
  1365. noDependencies = Deps [] [] [] []
  1366. -- | Records modules that we depend on by making a direct import from
  1367. data Usage
  1368. -- | Module from another package
  1369. = UsagePackageModule {
  1370. usg_mod :: Module,
  1371. -- ^ External package module depended on
  1372. usg_mod_hash :: Fingerprint,
  1373. -- ^ Cached module fingerprint
  1374. usg_safe :: IsSafeImport
  1375. -- ^ Was this module imported as a safe import
  1376. }
  1377. -- | Module from the current package
  1378. | UsageHomeModule {
  1379. usg_mod_name :: ModuleName,
  1380. -- ^ Name of the module
  1381. usg_mod_hash :: Fingerprint,
  1382. -- ^ Cached module fingerprint
  1383. usg_entities :: [(OccName,Fingerprint)],
  1384. -- ^ Entities we depend on, sorted by occurrence name and fingerprinted.
  1385. -- NB: usages are for parent names only, e.g. type constructors
  1386. -- but not the associated data constructors.
  1387. usg_exports :: Maybe Fingerprint,
  1388. -- ^ Fingerprint for the export list we used to depend on this module,
  1389. -- if we depend on the export list
  1390. usg_safe :: IsSafeImport
  1391. -- ^ Was this module imported as a safe import
  1392. } -- ^ Module from the current package
  1393. | UsageFile {
  1394. usg_file_path :: FilePath,
  1395. usg_mtime :: UTCTime
  1396. -- ^ External file dependency. From a CPP #include or TH addDependentFile. Should be absolute.
  1397. }
  1398. deriving( Eq )
  1399. -- The export list field is (Just v) if we depend on the export list:
  1400. -- i.e. we imported the module directly, whether or not we
  1401. -- enumerated the things we imported, or just imported
  1402. -- everything
  1403. -- We need to recompile if M's exports change, because
  1404. -- if the import was import M, we might now have a name clash
  1405. -- in the importing module.
  1406. -- if the import was import M(x) M might no longer export x
  1407. -- The only way we don't depend on the export list is if we have
  1408. -- import M()
  1409. -- And of course, for modules that aren't imported directly we don't
  1410. -- depend on their export lists
  1411. \end{code}
  1412. %************************************************************************
  1413. %* *
  1414. The External Package State
  1415. %* *
  1416. %************************************************************************
  1417. \begin{code}
  1418. type PackageTypeEnv = TypeEnv
  1419. type PackageRuleBase = RuleBase
  1420. type PackageInstEnv = InstEnv
  1421. type PackageFamInstEnv = FamInstEnv
  1422. type PackageVectInfo = VectInfo
  1423. type PackageAnnEnv = AnnEnv
  1424. -- | Information about other packages that we have slurped in by reading
  1425. -- their interface files
  1426. data ExternalPackageState
  1427. = EPS {
  1428. eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
  1429. -- ^ In OneShot mode (only), home-package modules
  1430. -- accumulate in the external package state, and are
  1431. -- sucked in lazily. For these home-pkg modules
  1432. -- (only) we need to record which are boot modules.
  1433. -- We set this field after loading all the
  1434. -- explicitly-imported interfaces, but before doing
  1435. -- anything else
  1436. --
  1437. -- The 'ModuleName' part is not necessary, but it's useful for
  1438. -- debug prints, and it's convenient because this field comes
  1439. -- direct from 'TcRnTypes.imp_dep_mods'
  1440. eps_PIT :: !PackageIfaceTable,
  1441. -- ^ The 'ModIface's for modules in external packages
  1442. -- whose interfaces we have opened.
  1443. -- The declarations in these interface files are held in the
  1444. -- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules'
  1445. -- fields of this record, not in the 'mi_decls' fields of the
  1446. -- interface we have sucked in.
  1447. --
  1448. -- What /is/ in the PIT is:
  1449. --
  1450. -- * The Module
  1451. --
  1452. -- * Fingerprint info
  1453. --
  1454. -- * Its exports
  1455. --
  1456. -- * Fixities
  1457. --
  1458. -- * Deprecations and warnings
  1459. eps_PTE :: !PackageTypeEnv,
  1460. -- ^ Result of typechecking all the external package
  1461. -- interface files we have sucked in. The domain of
  1462. -- the mapping is external-package modules
  1463. eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated
  1464. -- from all the external-package modules
  1465. eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated
  1466. -- from all the external-package modules
  1467. eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated
  1468. -- from all the external-package modules
  1469. eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated
  1470. -- from all the external-package modules
  1471. eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated
  1472. -- from all the external-package modules
  1473. eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external
  1474. -- packages, keyed off the module that declared them
  1475. eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages
  1476. }
  1477. -- | Accumulated statistics about what we are putting into the 'ExternalPackageState'.
  1478. -- \"In\" means stuff that is just /read/ from interface files,
  1479. -- \"Out\" means actually sucked in and type-checked
  1480. data EpsStats = EpsStats { n_ifaces_in
  1481. , n_decls_in, n_decls_out
  1482. , n_rules_in, n_rules_out
  1483. , n_insts_in, n_insts_out :: !Int }
  1484. addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
  1485. -- ^ Add stats for one newly-read interface
  1486. addEpsInStats stats n_decls n_insts n_rules
  1487. = stats { n_ifaces_in = n_ifaces_in stats + 1
  1488. , n_decls_in = n_decls_in stats + n_decls
  1489. , n_insts_in = n_insts_in stats + n_insts
  1490. , n_rules_in = n_rules_in stats + n_rules }
  1491. \end{code}
  1492. Names in a NameCache are always stored as a Global, and have the SrcLoc
  1493. of their binding locations.
  1494. Actually that's not quite right. When we first encounter the original
  1495. name, we might not be at its binding site (e.g. we are reading an
  1496. interface file); so we give it 'noSrcLoc' then. Later, when we find
  1497. its binding site, we fix it up.
  1498. \begin{code}
  1499. -- | The NameCache makes sure that there is just one Unique assigned for
  1500. -- each original name; i.e. (module-name, occ-name) pair and provides
  1501. -- something of a lookup mechanism for those names.
  1502. data NameCache
  1503. = NameCache { nsUniqs :: UniqSupply,
  1504. -- ^ Supply of uniques
  1505. nsNames :: OrigNameCache
  1506. -- ^ Ensures that one original name gets one unique
  1507. }
  1508. -- | Per-module cache of original 'OccName's given 'Name's
  1509. type OrigNameCache = ModuleEnv (OccEnv Name)
  1510. \end{code}
  1511. \begin{code}
  1512. mkSOName :: Platform -> FilePath -> FilePath
  1513. mkSOName platform root
  1514. = case platformOS platform of
  1515. OSDarwin -> ("lib" ++ root) <.> "dylib"
  1516. OSMinGW32 -> root <.> "dll"
  1517. _ -> ("lib" ++ root) <.> "so"
  1518. \end{code}
  1519. %************************************************************************
  1520. %* *
  1521. The module graph and ModSummary type
  1522. A ModSummary is a node in the compilation manager's
  1523. dependency graph, and it's also passed to hscMain
  1524. %* *
  1525. %************************************************************************
  1526. \begin{code}
  1527. -- | A ModuleGraph contains all the nodes from the home package (only).
  1528. -- There will be a node for each source module, plus a node for each hi-boot
  1529. -- module.
  1530. --
  1531. -- The graph is not necessarily stored in topologically-sorted order. Use
  1532. -- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this.
  1533. type ModuleGraph = [ModSummary]
  1534. emptyMG :: ModuleGraph
  1535. emptyMG = []
  1536. -- | A single node in a 'ModuleGraph. The nodes of the module graph are one of:
  1537. --
  1538. -- * A regular Haskell source module
  1539. --
  1540. -- * A hi-boot source module
  1541. --
  1542. -- * An external-core source module
  1543. data ModSummary
  1544. = ModSummary {
  1545. ms_mod :: Module, -- ^ Identity of the module
  1546. ms_hsc_src :: HscSource, -- ^ The module source either plain Haskell, hs-boot or external core
  1547. ms_location :: ModLocation, -- ^ Location of the various files belonging to the module
  1548. ms_hs_date :: UTCTime, -- ^ Timestamp of source file
  1549. ms_obj_date :: Maybe UTCTime, -- ^ Timestamp of object, if we have one
  1550. ms_srcimps :: [Located (ImportDecl RdrName)], -- ^ Source imports of the module
  1551. ms_textual_imps :: [Located (ImportDecl RdrName)], -- ^ Non-source imports of the module from the module *text*
  1552. ms_hspp_file :: FilePath, -- ^ Filename of preprocessed source file
  1553. ms_hspp_opts :: DynFlags, -- ^ Cached flags from @OPTIONS@, @INCLUDE@
  1554. -- and @LANGUAGE@ pragmas in the modules source code
  1555. ms_hspp_buf :: Maybe StringBuffer -- ^ The actual preprocessed source, if we have it
  1556. }
  1557. ms_mod_name :: ModSummary -> ModuleName
  1558. ms_mod_name = moduleName . ms_mod
  1559. ms_imps :: ModSummary -> [Located (ImportDecl RdrName)]
  1560. ms_imps ms = ms_textual_imps ms ++ map mk_additional_import (dynFlagDependencies (ms_hspp_opts ms))
  1561. where
  1562. -- This is a not-entirely-satisfactory means of creating an import that corresponds to an
  1563. -- import that did not occur in the program text, such as those induced by the use of
  1564. -- plugins (the -plgFoo flag)
  1565. mk_additional_import mod_nm = noLoc $ ImportDecl {
  1566. ideclName = noLoc mod_nm,
  1567. ideclPkgQual = Nothing,
  1568. ideclSource = False,
  1569. ideclImplicit = True, -- Maybe implicit because not "in the program text"
  1570. ideclQualified = False,
  1571. ideclAs = Nothing,
  1572. ideclHiding = Nothing,
  1573. ideclSafe = False
  1574. }
  1575. -- The ModLocation contains both the original source filename and the
  1576. -- filename of the cleaned-up source file after all preprocessing has been
  1577. -- done. The point is that the summariser will have to cpp/unlit/whatever
  1578. -- all files anyway, and there's no point in doing this twice -- just
  1579. -- park the result in a temp file, put the name of it in the location,
  1580. -- and let @compile@ read from that file on the way back up.
  1581. -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
  1582. -- the ms_hs_date and imports can, of course, change
  1583. msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
  1584. msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
  1585. msHiFilePath ms = ml_hi_file (ms_location ms)
  1586. msObjFilePath ms = ml_obj_file (ms_location ms)
  1587. -- | Did this 'ModSummary' originate from a hs-boot file?
  1588. isBootSummary :: ModSummary -> Bool
  1589. isBootSummary ms = isHsBoot (ms_hsc_src ms)
  1590. instance Outputable ModSummary where
  1591. ppr ms
  1592. = sep [text "ModSummary {",
  1593. nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
  1594. text "ms_mod =" <+> ppr (ms_mod ms)
  1595. <> text (hscSourceString (ms_hsc_src ms)) <> comma,
  1596. text "ms_textual_imps =" <+> ppr (ms_textual_imps ms),
  1597. text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
  1598. char '}'
  1599. ]
  1600. showModMsg :: DynFlags -> HscTarget -> Bool -> ModSummary -> String
  1601. showModMsg dflags target recomp mod_summary
  1602. = showSDoc dflags $
  1603. hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
  1604. char '(', text (normalise $ msHsFilePath mod_summary) <> comma,
  1605. case target of
  1606. HscInterpreted | recomp
  1607. -> text "interpreted"
  1608. HscNothing -> text "nothing"
  1609. _ -> text (normalise $ msObjFilePath mod_summary),
  1610. char ')']
  1611. where
  1612. mod = moduleName (ms_mod mod_summary)
  1613. mod_str = showPpr dflags mod ++ hscSourceString (ms_hsc_src mod_summary)
  1614. \end{code}
  1615. %************************************************************************
  1616. %* *
  1617. \subsection{Recmpilation}
  1618. %* *
  1619. %************************************************************************
  1620. \begin{code}
  1621. -- | Indicates whether a given module's source has been modified since it
  1622. -- was last compiled.
  1623. data SourceModified
  1624. = SourceModified
  1625. -- ^ the source has been modified
  1626. | SourceUnmodified
  1627. -- ^ the source has not been modified. Compilation may or may
  1628. -- not be necessary, depending on whether any dependencies have
  1629. -- changed since we last compiled.
  1630. | SourceUnmodifiedAndStable
  1631. -- ^ the source has not been modified, and furthermore all of
  1632. -- its (transitive) dependencies are up to date; it definitely
  1633. -- does not need to be recompiled. This is important for two
  1634. -- reasons: (a) we can omit the version check in checkOldIface,
  1635. -- and (b) if the module used TH splices we don't need to force
  1636. -- recompilation.
  1637. \end{code}
  1638. %************************************************************************
  1639. %* *
  1640. \subsection{Hpc Support}
  1641. %* *
  1642. %************************************************************************
  1643. \begin{code}
  1644. -- | Information about a modules use of Haskell Program Coverage
  1645. data HpcInfo
  1646. = HpcInfo
  1647. { hpcInfoTickCount :: Int
  1648. , hpcInfoHash :: Int
  1649. }
  1650. | NoHpcInfo
  1651. { hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*?
  1652. }
  1653. -- | This is used to signal if one of my imports used HPC instrumentation
  1654. -- even if there is no module-local HPC usage
  1655. type AnyHpcUsage = Bool
  1656. emptyHpcInfo :: AnyHpcUsage -> HpcInfo
  1657. emptyHpcInfo = NoHpcInfo
  1658. -- | Find out if HPC is used by this module or any of the modules
  1659. -- it depends upon
  1660. isHpcUsed :: HpcInfo -> AnyHpcUsage
  1661. isHpcUsed (HpcInfo {}) = True
  1662. isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
  1663. \end{code}
  1664. %************************************************************************
  1665. %* *
  1666. \subsection{Vectorisation Support}
  1667. %* *
  1668. %************************************************************************
  1669. The following information is generated and consumed by the vectorisation
  1670. subsystem. It communicates the vectorisation status of declarations from one
  1671. module to another.
  1672. Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
  1673. below? We need to know `f' when converting to IfaceVectInfo. However, during
  1674. vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
  1675. on just the OccName easily in a Core pass.
  1676. \begin{code}
  1677. -- |Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'; see also
  1678. -- documentation at 'Vectorise.Env.GlobalEnv'.
  1679. --
  1680. -- NB: The following tables may also include 'Var's, 'TyCon's and 'DataCon's from imported modules,
  1681. -- which have been subsequently vectorised in the current module.
  1682. --
  1683. data VectInfo
  1684. = VectInfo
  1685. { vectInfoVar :: VarEnv (Var , Var ) -- ^ @(f, f_v)@ keyed on @f@
  1686. , vectInfoTyCon :: NameEnv (TyCon , TyCon) -- ^ @(T, T_v)@ keyed on @T@
  1687. , vectInfoDataCon :: NameEnv (DataCon, DataCon) -- ^ @(C, C_v)@ keyed on @C@
  1688. , vectInfoScalarVars :: VarSet -- ^ set of purely scalar variables
  1689. , vectInfoScalarTyCons :: NameSet -- ^ set of scalar type constructors
  1690. }
  1691. -- |Vectorisation information for 'ModIface'; i.e, the vectorisation information propagated
  1692. -- across module boundaries.
  1693. --
  1694. -- NB: The field 'ifaceVectInfoVar' explicitly contains the workers of data constructors as well as
  1695. -- class selectors — i.e., their mappings are /not/ implicitly generated from the data types.
  1696. -- Moreover, whether the worker of a data constructor is in 'ifaceVectInfoVar' determines
  1697. -- whether that data constructor was vectorised (or is part of an abstractly vectorised type
  1698. -- constructor).
  1699. --
  1700. data IfaceVectInfo
  1701. = IfaceVectInfo
  1702. { ifaceVectInfoVar :: [Name] -- ^ All variables in here have a vectorised variant
  1703. , ifaceVectInfoTyCon :: [Name] -- ^ All 'TyCon's in here have a vectorised variant;
  1704. -- the name of the vectorised variant and those of its
  1705. -- data constructors are determined by
  1706. -- 'OccName.mkVectTyConOcc' and
  1707. -- 'OccName.mkVectDataConOcc'; the names of the
  1708. -- isomorphisms are determined by 'OccName.mkVectIsoOcc'
  1709. , ifaceVectInfoTyConReuse :: [Name] -- ^ The vectorised form of all the 'TyCon's in here
  1710. -- coincides with the unconverted form; the name of the
  1711. -- isomorphisms is determined by 'OccName.mkVectIsoOcc'
  1712. , ifaceVectInfoScalarVars :: [Name] -- iface version of 'vectInfoScalarVar'
  1713. , ifaceVectInfoScalarTyCons :: [Name] -- iface version of 'vectInfoScalarTyCon'
  1714. }
  1715. noVectInfo :: VectInfo
  1716. noVectInfo
  1717. = VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyVarSet emptyNameSet
  1718. plusVectInfo :: VectInfo -> VectInfo -> VectInfo
  1719. plusVectInfo vi1 vi2 =
  1720. VectInfo (vectInfoVar vi1 `plusVarEnv` vectInfoVar vi2)
  1721. (vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2)
  1722. (vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
  1723. (vectInfoScalarVars vi1 `unionVarSet` vectInfoScalarVars vi2)
  1724. (vectInfoScalarTyCons vi1 `unionNameSets` vectInfoScalarTyCons vi2)
  1725. concatVectInfo :: [VectInfo] -> VectInfo
  1726. concatVectInfo = foldr plusVectInfo noVectInfo
  1727. noIfaceVectInfo :: IfaceVectInfo
  1728. noIfaceVectInfo = IfaceVectInfo [] [] [] [] []
  1729. isNoIfaceVectInfo :: IfaceVectInfo -> Bool
  1730. isNoIfaceVectInfo (IfaceVectInfo l1 l2 l3 l4 l5)
  1731. = null l1 && null l2 && null l3 && null l4 && null l5
  1732. instance Outputable VectInfo where
  1733. ppr info = vcat
  1734. [ ptext (sLit "variables :") <+> ppr (vectInfoVar info)
  1735. , ptext (sLit "tycons :") <+> ppr (vectInfoTyCon info)
  1736. , ptext (sLit "datacons :") <+> ppr (vectInfoDataCon info)
  1737. , ptext (sLit "scalar vars :") <+> ppr (vectInfoScalarVars info)
  1738. , ptext (sLit "scalar tycons :") <+> ppr (vectInfoScalarTyCons info)
  1739. ]
  1740. \end{code}
  1741. %************************************************************************
  1742. %* *
  1743. \subsection{Safe Haskell Support}
  1744. %* *
  1745. %************************************************************************
  1746. This stuff here is related to supporting the Safe Haskell extension,
  1747. primarily about storing under what trust type a module has been compiled.
  1748. \begin{code}
  1749. -- | Is an import a safe import?
  1750. type IsSafeImport = Bool
  1751. -- | Safe Haskell information for 'ModIface'
  1752. -- Simply a wrapper around SafeHaskellMode to sepperate iface and flags
  1753. newtype IfaceTrustInfo = TrustInfo SafeHaskellMode
  1754. getSafeMode :: IfaceTrustInfo -> SafeHaskellMode
  1755. getSafeMode (TrustInfo x) = x
  1756. setSafeMode :: SafeHaskellMode -> IfaceTrustInfo
  1757. setSafeMode = TrustInfo
  1758. noIfaceTrustInfo :: IfaceTrustInfo
  1759. noIfaceTrustInfo = setSafeMode Sf_None
  1760. trustInfoToNum :: IfaceTrustInfo -> Word8
  1761. trustInfoToNum it
  1762. = case getSafeMode it of
  1763. Sf_None -> 0
  1764. Sf_Unsafe -> 1
  1765. Sf_Trustworthy -> 2
  1766. Sf_Safe -> 3
  1767. Sf_SafeInferred -> 4
  1768. numToTrustInfo :: Word8 -> IfaceTrustInfo
  1769. numToTrustInfo 0 = setSafeMode Sf_None
  1770. numToTrustInfo 1 = setSafeMode Sf_Unsafe
  1771. numToTrustInfo 2 = setSafeMode Sf_Trustworthy
  1772. numToTrustInfo 3 = setSafeMode Sf_Safe
  1773. numToTrustInfo 4 = setSafeMode Sf_SafeInferred
  1774. numToTrustInfo n = error $ "numToTrustInfo: bad input number! (" ++ show n ++ ")"
  1775. instance Outputable IfaceTrustInfo where
  1776. ppr (TrustInfo Sf_None) = ptext $ sLit "none"
  1777. ppr (TrustInfo Sf_Unsafe) = ptext $ sLit "unsafe"
  1778. ppr (TrustInfo Sf_Trustworthy) = ptext $ sLit "trustworthy"
  1779. ppr (TrustInfo Sf_Safe) = ptext $ sLit "safe"
  1780. ppr (TrustInfo Sf_SafeInferred) = ptext $ sLit "safe-inferred"
  1781. \end{code}
  1782. %************************************************************************
  1783. %* *
  1784. \subsection{Parser result}
  1785. %* *
  1786. %************************************************************************
  1787. \begin{code}
  1788. data HsParsedModule = HsParsedModule {
  1789. hpm_module :: Located (HsModule RdrName),
  1790. hpm_src_files :: [FilePath]
  1791. -- ^ extra source files (e.g. from #includes). The lexer collects
  1792. -- these from '# <file> <line>' pragmas, which the C preprocessor
  1793. -- leaves behind. These files and their timestamps are stored in
  1794. -- the .hi file, so that we can force recompilation if any of
  1795. -- them change (#3589)
  1796. }
  1797. \end{code}
  1798. %************************************************************************
  1799. %* *
  1800. \subsection{Linkable stuff}
  1801. %* *
  1802. %************************************************************************
  1803. This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
  1804. stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
  1805. \begin{code}
  1806. -- | Information we can use to dynamically link modules into the compiler
  1807. data Linkable = LM {
  1808. linkableTime :: UTCTime, -- ^ Time at which this linkable was built
  1809. -- (i.e. when the bytecodes were produced,
  1810. -- or the mod date on the files)
  1811. linkableModule :: Module, -- ^ The linkable module itself
  1812. linkableUnlinked :: [Unlinked]
  1813. -- ^ Those files and chunks of code we have yet to link.
  1814. --
  1815. -- INVARIANT: A valid linkable always has at least one 'Unlinked' item.
  1816. -- If this list is empty, the Linkable represents a fake linkable, which
  1817. -- is generated in HscNothing mode to avoid recompiling modules.
  1818. --
  1819. -- ToDo: Do items get removed from this list when they get linked?
  1820. }
  1821. isObjectLinkable :: Linkable -> Bool
  1822. isObjectLinkable l = not (null unlinked) && all isObject unlinked
  1823. where unlinked = linkableUnlinked l
  1824. -- A linkable with no Unlinked's is treated as a BCO. We can
  1825. -- generate a linkable with no Unlinked's as a result of
  1826. -- compiling a module in HscNothing mode, and this choice
  1827. -- happens to work well with checkStability in module GHC.
  1828. linkableObjs :: Linkable -> [FilePath]
  1829. linkableObjs l = [ f | DotO f <- linkableUnlinked l ]
  1830. instance Outputable Linkable where
  1831. ppr (LM when_made mod unlinkeds)
  1832. = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
  1833. $$ nest 3 (ppr unlinkeds)
  1834. -------------------------------------------
  1835. -- | Objects which have yet to be linked by the compiler
  1836. data Unlinked
  1837. = DotO FilePath -- ^ An object file (.o)
  1838. | DotA FilePath -- ^ Static archive file (.a)
  1839. | DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib)
  1840. | BCOs CompiledByteCode ModBreaks -- ^ A byte-code object, lives only in memory
  1841. #ifndef GHCI
  1842. data CompiledByteCode = CompiledByteCodeUndefined
  1843. _unused :: CompiledByteCode
  1844. _unused = CompiledByteCodeUndefined
  1845. #endif
  1846. instance Outputable Unlinked where
  1847. ppr (DotO path) = text "DotO" <+> text path
  1848. ppr (DotA path) = text "DotA" <+> text path
  1849. ppr (DotDLL path) = text "DotDLL" <+> text path
  1850. #ifdef GHCI
  1851. ppr (BCOs bcos _) = text "BCOs" <+> ppr bcos
  1852. #else
  1853. ppr (BCOs _ _) = text "No byte code"
  1854. #endif
  1855. -- | Is this an actual file on disk we can link in somehow?
  1856. isObject :: Unlinked -> Bool
  1857. isObject (DotO _) = True
  1858. isObject (DotA _) = True
  1859. isObject (DotDLL _) = True
  1860. isObject _ = False
  1861. -- | Is this a bytecode linkable with no file on disk?
  1862. isInterpretable :: Unlinked -> Bool
  1863. isInterpretable = not . isObject
  1864. -- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object
  1865. nameOfObject :: Unlinked -> FilePath
  1866. nameOfObject (DotO fn) = fn
  1867. nameOfObject (DotA fn) = fn
  1868. nameOfObject (DotDLL fn) = fn
  1869. nameOfObject other = pprPanic "nameOfObject" (ppr other)
  1870. -- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable
  1871. byteCodeOfObject :: Unlinked -> CompiledByteCode
  1872. byteCodeOfObject (BCOs bc _) = bc
  1873. byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
  1874. \end{code}
  1875. %************************************************************************
  1876. %* *
  1877. \subsection{Breakpoint Support}
  1878. %* *
  1879. %************************************************************************
  1880. \begin{code}
  1881. -- | Breakpoint index
  1882. type BreakIndex = Int
  1883. -- | All the information about the breakpoints for a given module
  1884. data ModBreaks
  1885. = ModBreaks
  1886. { modBreaks_flags :: BreakArray
  1887. -- ^ The array of flags, one per breakpoint,
  1888. -- indicating which breakpoints are enabled.
  1889. , modBreaks_locs :: !(Array BreakIndex SrcSpan)
  1890. -- ^ An array giving the source span of each breakpoint.
  1891. , modBreaks_vars :: !(Array BreakIndex [OccName])
  1892. -- ^ An array giving the names of the free variables at each breakpoint.
  1893. , modBreaks_decls :: !(Array BreakIndex [String])
  1894. -- ^ An array giving the names of the declarations enclosing each breakpoint.
  1895. }
  1896. -- | Construct an empty ModBreaks
  1897. emptyModBreaks :: ModBreaks
  1898. emptyModBreaks = ModBreaks
  1899. { modBreaks_flags = error "ModBreaks.modBreaks_array not initialised"
  1900. -- ToDo: can we avoid this?
  1901. , modBreaks_locs = array (0,-1) []
  1902. , modBreaks_vars = array (0,-1) []
  1903. , modBreaks_decls = array (0,-1) []
  1904. }
  1905. \end{code}