2 % (c) The University of Glasgow, 2006
4 \section[HscTypes]{Types for the per-module compiler}
7 -- | Types for the per-module compiler
10 Ghc(..), GhcT(..), liftGhcT,
11 GhcMonad(..), WarnLogMonad(..),
14 logWarnings, clearWarnings, hasWarnings,
15 SourceError, GhcApiError, mkSrcErr, srcErrorMessages, mkApiErr,
16 throwOneError, handleSourceError,
20 -- * Sessions and compilation state
21 Session(..), withSession, modifySession, withTempSession,
23 FinderCache, FindResult(..), ModLocationCache,
24 Target(..), TargetId(..), pprTarget, pprTargetId,
27 GhcApiCallbacks(..), withLocalCallbacks,
29 -- * Information about modules
30 ModDetails(..), emptyModDetails,
31 ModGuts(..), CoreModule(..), CgGuts(..), ForeignStubs(..),
34 ModSummary(..), ms_mod_name, showModMsg, isBootSummary,
35 msHsFilePath, msHiFilePath, msObjFilePath,
37 -- * Information about the module being compiled
38 HscSource(..), isHsBoot, hscSourceString, -- Re-exported from DriverPhases
40 -- * State relating to modules in this package
41 HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
42 hptInstances, hptRules, hptVectInfo,
44 -- * State relating to known packages
45 ExternalPackageState(..), EpsStats(..), addEpsInStats,
46 PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
47 lookupIfaceByModule, emptyModIface,
49 PackageInstEnv, PackageRuleBase,
55 -- * Interactive context
56 InteractiveContext(..), emptyInteractiveContext,
57 icPrintUnqual, mkPrintUnqualified, extendInteractiveContext,
58 substInteractiveContext,
61 ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache,
65 FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
67 -- * TyThings and type environments
69 tyThingClass, tyThingTyCon, tyThingDataCon, tyThingId,
70 implicitTyThings, isImplicitTyThing,
72 TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv,
73 extendTypeEnv, extendTypeEnvList, extendTypeEnvWithIds, lookupTypeEnv,
74 typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
80 -- * Information on imports and exports
81 WhetherHasOrphans, IsBootInterface, Usage(..),
82 Dependencies(..), noDependencies,
83 NameCache(..), OrigNameCache, OrigIParamCache,
84 Avails, availsToNameSet, availsToNameEnv, availName, availNames,
85 GenAvailInfo(..), AvailInfo, RdrAvailInfo,
89 Warnings(..), WarningTxt(..), plusWarns,
92 Linkable(..), isObjectLinkable,
93 Unlinked(..), CompiledByteCode,
94 isObject, nameOfObject, isInterpretable, byteCodeOfObject,
97 HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
100 ModBreaks (..), BreakIndex, emptyModBreaks,
102 -- * Vectorisation information
103 VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo,
107 #include "HsVersions.h"
110 import ByteCodeAsm ( CompiledByteCode )
111 import {-# SOURCE #-} InteractiveEval ( Resume )
119 import OccName ( OccName, OccEnv, lookupOccEnv, mkOccEnv, emptyOccEnv,
122 import InstEnv ( InstEnv, Instance )
123 import FamInstEnv ( FamInstEnv, FamInst )
124 import Rules ( RuleBase )
125 import CoreSyn ( CoreBind )
133 import Class ( Class, classSelIds, classATs, classTyCon )
135 import DataCon ( DataCon, dataConImplicitIds, dataConWrapId )
136 import PrelNames ( gHC_PRIM )
137 import Packages hiding ( Version(..) )
138 import DynFlags ( DynFlags(..), isOneShot, HscTarget (..), dopt,
140 import DriverPhases ( HscSource(..), isHsBoot, hscSourceString, Phase )
141 import BasicTypes ( IPName, Fixity, defaultFixity, WarningTxt(..) )
142 import OptimizationFuel ( OptFuelState )
144 import FiniteMap ( FiniteMap )
145 import CoreSyn ( CoreRule )
146 import Maybes ( orElse, expectJust, catMaybes )
149 import SrcLoc ( SrcSpan, Located(..) )
150 import LazyUniqFM ( lookupUFM, eltsUFM, emptyUFM )
151 import UniqSupply ( UniqSupply )
153 import StringBuffer ( StringBuffer )
156 import Data.Dynamic ( Typeable )
157 import qualified Data.Dynamic as Dyn
161 import System.FilePath
162 import System.Time ( ClockTime )
164 import Data.Array ( Array, array )
166 import Control.Monad ( mplus, guard, liftM, when )
171 %************************************************************************
173 \subsection{Compilation environment}
175 %************************************************************************
179 -- | The Session is a handle to the complete state of a compilation
180 -- session. A compilation session consists of a set of modules
181 -- constituting the current program or library, the context for
182 -- interactive evaluation, and various caches.
183 data Session = Session !(IORef HscEnv) !(IORef WarningMessages)
185 mkSrcErr :: ErrorMessages -> SourceError
186 srcErrorMessages :: SourceError -> ErrorMessages
187 mkApiErr :: SDoc -> GhcApiError
189 throwOneError :: MonadIO m => ErrMsg -> m ab
190 throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err
192 -- | A source error is an error that is caused by one or more errors in the
193 -- source code. A 'SourceError' is thrown by many functions in the
194 -- compilation pipeline. Inside GHC these errors are merely printed via
195 -- 'log_action', but API clients may treat them differently, for example,
196 -- insert them into a list box. If you want the default behaviour, use the
199 -- > handleSourceError printExceptionAndWarnings $ do
200 -- > ... api calls that may fail ...
202 -- The 'SourceError's error messages can be accessed via 'srcErrorMessages'.
203 -- This list may be empty if the compiler failed due to @-Werror@
204 -- ('Opt_WarnIsError').
206 -- See 'printExceptionAndWarnings' for more information on what to take care
207 -- of when writing a custom error handler.
208 data SourceError = SourceError ErrorMessages
210 instance Show SourceError where
211 show (SourceError msgs) = unlines . map show . bagToList $ msgs
212 -- ToDo: is there some nicer way to print this?
214 sourceErrorTc :: Dyn.TyCon
215 sourceErrorTc = Dyn.mkTyCon "SourceError"
216 {-# NOINLINE sourceErrorTc #-}
217 instance Typeable SourceError where
218 typeOf _ = Dyn.mkTyConApp sourceErrorTc []
220 instance Exception SourceError
222 mkSrcErr = SourceError
224 -- | Perform the given action and call the exception handler if the action
225 -- throws a 'SourceError'. See 'SourceError' for more information.
226 handleSourceError :: (ExceptionMonad m) =>
227 (SourceError -> m a) -- ^ exception handler
228 -> m a -- ^ action to perform
230 handleSourceError handler act =
231 gcatch act (\(e :: SourceError) -> handler e)
233 srcErrorMessages (SourceError msgs) = msgs
235 -- | XXX: what exactly is an API error?
236 data GhcApiError = GhcApiError SDoc
238 instance Show GhcApiError where
239 show (GhcApiError msg) = showSDoc msg
241 ghcApiErrorTc :: Dyn.TyCon
242 ghcApiErrorTc = Dyn.mkTyCon "GhcApiError"
243 {-# NOINLINE ghcApiErrorTc #-}
244 instance Typeable GhcApiError where
245 typeOf _ = Dyn.mkTyConApp ghcApiErrorTc []
247 instance Exception GhcApiError
249 mkApiErr = GhcApiError
251 -- | A monad that allows logging of warnings.
252 class Monad m => WarnLogMonad m where
253 setWarnings :: WarningMessages -> m ()
254 getWarnings :: m WarningMessages
256 logWarnings :: WarnLogMonad m => WarningMessages -> m ()
257 logWarnings warns = do
258 warns0 <- getWarnings
259 setWarnings (unionBags warns warns0)
261 -- | Clear the log of 'Warnings'.
262 clearWarnings :: WarnLogMonad m => m ()
263 clearWarnings = setWarnings emptyBag
265 -- | Returns true if there were any warnings.
266 hasWarnings :: WarnLogMonad m => m Bool
267 hasWarnings = getWarnings >>= return . not . isEmptyBag
269 -- | A monad that has all the features needed by GHC API calls.
271 -- In short, a GHC monad
273 -- - allows embedding of IO actions,
275 -- - can log warnings,
277 -- - allows handling of (extensible) exceptions, and
279 -- - maintains a current session.
281 -- If you do not use 'Ghc' or 'GhcT', make sure to call 'GHC.initGhcMonad'
282 -- before any call to the GHC API functions can occur.
284 class (Functor m, MonadIO m, WarnLogMonad m, ExceptionMonad m)
286 getSession :: m HscEnv
287 setSession :: HscEnv -> m ()
289 -- | Call the argument with the current session.
290 withSession :: GhcMonad m => (HscEnv -> m a) -> m a
291 withSession f = getSession >>= f
293 -- | Set the current session to the result of applying the current session to
295 modifySession :: GhcMonad m => (HscEnv -> HscEnv) -> m ()
296 modifySession f = do h <- getSession
299 withSavedSession :: GhcMonad m => m a -> m a
300 withSavedSession m = do
301 saved_session <- getSession
302 m `gfinally` setSession saved_session
304 -- | Call an action with a temporarily modified Session.
305 withTempSession :: GhcMonad m => (HscEnv -> HscEnv) -> m a -> m a
306 withTempSession f m =
307 withSavedSession $ modifySession f >> m
309 -- | A minimal implementation of a 'GhcMonad'. If you need a custom monad,
310 -- e.g., to maintain additional state consider wrapping this monad or using
312 newtype Ghc a = Ghc { unGhc :: Session -> IO a }
314 instance Functor Ghc where
315 fmap f m = Ghc $ \s -> f `fmap` unGhc m s
317 instance Monad Ghc where
318 return a = Ghc $ \_ -> return a
319 m >>= g = Ghc $ \s -> do a <- unGhc m s; unGhc (g a) s
321 instance MonadIO Ghc where
322 liftIO ioA = Ghc $ \_ -> ioA
324 instance ExceptionMonad Ghc where
326 Ghc $ \s -> unGhc act s `gcatch` \e -> unGhc (handle e) s
327 gblock (Ghc m) = Ghc $ \s -> gblock (m s)
328 gunblock (Ghc m) = Ghc $ \s -> gunblock (m s)
330 instance WarnLogMonad Ghc where
331 setWarnings warns = Ghc $ \(Session _ wref) -> writeIORef wref warns
332 -- | Return 'Warnings' accumulated so far.
333 getWarnings = Ghc $ \(Session _ wref) -> readIORef wref
335 instance GhcMonad Ghc where
336 getSession = Ghc $ \(Session r _) -> readIORef r
337 setSession s' = Ghc $ \(Session r _) -> writeIORef r s'
339 -- | A monad transformer to add GHC specific features to another monad.
341 -- Note that the wrapped monad must support IO and handling of exceptions.
342 newtype GhcT m a = GhcT { unGhcT :: Session -> m a }
343 liftGhcT :: Monad m => m a -> GhcT m a
344 liftGhcT m = GhcT $ \_ -> m
346 instance Functor m => Functor (GhcT m) where
347 fmap f m = GhcT $ \s -> f `fmap` unGhcT m s
349 instance Monad m => Monad (GhcT m) where
350 return x = GhcT $ \_ -> return x
351 m >>= k = GhcT $ \s -> do a <- unGhcT m s; unGhcT (k a) s
353 instance MonadIO m => MonadIO (GhcT m) where
354 liftIO ioA = GhcT $ \_ -> liftIO ioA
356 instance ExceptionMonad m => ExceptionMonad (GhcT m) where
358 GhcT $ \s -> unGhcT act s `gcatch` \e -> unGhcT (handle e) s
359 gblock (GhcT m) = GhcT $ \s -> gblock (m s)
360 gunblock (GhcT m) = GhcT $ \s -> gunblock (m s)
362 instance MonadIO m => WarnLogMonad (GhcT m) where
363 setWarnings warns = GhcT $ \(Session _ wref) -> liftIO $ writeIORef wref warns
364 -- | Return 'Warnings' accumulated so far.
365 getWarnings = GhcT $ \(Session _ wref) -> liftIO $ readIORef wref
367 instance (Functor m, ExceptionMonad m, MonadIO m) => GhcMonad (GhcT m) where
368 getSession = GhcT $ \(Session r _) -> liftIO $ readIORef r
369 setSession s' = GhcT $ \(Session r _) -> liftIO $ writeIORef r s'
371 -- | Lift an IO action returning errors messages into a 'GhcMonad'.
373 -- In order to reduce dependencies to other parts of the compiler, functions
374 -- outside the "main" parts of GHC return warnings and errors as a parameter
375 -- and signal success via by wrapping the result in a 'Maybe' type. This
376 -- function logs the returned warnings and propagates errors as exceptions
377 -- (of type 'SourceError').
379 -- This function assumes the following invariants:
381 -- 1. If the second result indicates success (is of the form 'Just x'),
382 -- there must be no error messages in the first result.
384 -- 2. If there are no error messages, but the second result indicates failure
385 -- there should be warnings in the first result. That is, if the action
386 -- failed, it must have been due to the warnings (i.e., @-Werror@).
387 ioMsgMaybe :: GhcMonad m =>
388 IO (Messages, Maybe a) -> m a
390 ((warns,errs), mb_r) <- liftIO ioA
393 Nothing -> liftIO $ throwIO (mkSrcErr errs)
394 Just r -> ASSERT( isEmptyBag errs ) return r
396 -- | Lift a non-failing IO action into a 'GhcMonad'.
398 -- Like 'ioMsgMaybe', but assumes that the action will never return any error
400 ioMsg :: GhcMonad m => IO (Messages, a) -> m a
402 ((warns,errs), r) <- liftIO ioA
404 ASSERT( isEmptyBag errs ) return r
406 -- | Reflect a computation in the 'Ghc' monad into the 'IO' monad.
408 -- You can use this to call functions returning an action in the 'Ghc' monad
409 -- inside an 'IO' action. This is needed for some (too restrictive) callback
410 -- arguments of some library functions:
412 -- > libFunc :: String -> (Int -> IO a) -> IO a
413 -- > ghcFunc :: Int -> Ghc a
415 -- > ghcFuncUsingLibFunc :: String -> Ghc a -> Ghc a
416 -- > ghcFuncUsingLibFunc str =
417 -- > reifyGhc $ \s ->
418 -- > libFunc $ \i -> do
419 -- > reflectGhc (ghcFunc i) s
421 reflectGhc :: Ghc a -> Session -> IO a
422 reflectGhc m = unGhc m
424 -- > Dual to 'reflectGhc'. See its documentation.
425 reifyGhc :: (Session -> IO a) -> Ghc a
426 reifyGhc act = Ghc $ act
428 handleFlagWarnings :: GhcMonad m => DynFlags -> [Located String] -> m ()
429 handleFlagWarnings dflags warns
430 = when (dopt Opt_WarnDeprecatedFlags dflags)
431 (handleFlagWarnings' dflags warns)
433 handleFlagWarnings' :: GhcMonad m => DynFlags -> [Located String] -> m ()
434 handleFlagWarnings' _ [] = return ()
435 handleFlagWarnings' dflags warns
436 = do -- It would be nicer if warns :: [Located Message], but that has circular
438 logWarnings $ listToBag (map mkFlagWarning warns)
439 when (dopt Opt_WarnIsError dflags) $
440 liftIO $ throwIO $ mkSrcErr emptyBag
442 mkFlagWarning :: Located String -> WarnMsg
443 mkFlagWarning (L loc warn)
444 = mkPlainWarnMsg loc (text warn)
448 -- | These functions are called in various places of the GHC API.
450 -- API clients can override any of these callbacks to change GHC's default
455 -- | Called by 'load' after the compilating of each module.
457 -- The default implementation simply prints all warnings and errors to
458 -- @stderr@. Don't forget to call 'clearWarnings' when implementing your
461 -- The first argument is the module that was compiled.
463 -- The second argument is @Nothing@ if no errors occured, but there may
464 -- have been warnings. If it is @Just err@ at least one error has
465 -- occured. If 'srcErrorMessages' is empty, compilation failed due to
467 reportModuleCompilationResult :: GhcMonad m =>
468 ModSummary -> Maybe SourceError
472 -- | Temporarily modify the callbacks. After the action is executed all
473 -- callbacks are reset (not, however, any other modifications to the session
475 withLocalCallbacks :: GhcMonad m =>
476 (GhcApiCallbacks -> GhcApiCallbacks)
478 withLocalCallbacks f m = do
479 hsc_env <- getSession
480 let cb0 = hsc_callbacks hsc_env
482 setSession (hsc_env { hsc_callbacks = cb' `seq` cb' })
484 hsc_env' <- getSession
485 setSession (hsc_env' { hsc_callbacks = cb0 })
491 -- | Hscenv is like 'Session', except that some of the fields are immutable.
492 -- An HscEnv is used to compile a single module from plain Haskell source
493 -- code (after preprocessing) to either C, assembly or C--. Things like
494 -- the module graph don't change during a single compilation.
496 -- Historical note: \"hsc\" used to be the name of the compiler binary,
497 -- when there was a separate driver and compiler. To compile a single
498 -- module, the driver would invoke hsc on the source code... so nowadays
499 -- we think of hsc as the layer of the compiler that deals with compiling
503 hsc_dflags :: DynFlags,
504 -- ^ The dynamic flag settings
506 hsc_callbacks :: GhcApiCallbacks,
507 -- ^ Callbacks for the GHC API.
509 hsc_targets :: [Target],
510 -- ^ The targets (or roots) of the current session
512 hsc_mod_graph :: ModuleGraph,
513 -- ^ The module graph of the current session
515 hsc_IC :: InteractiveContext,
516 -- ^ The context for evaluating interactive statements
518 hsc_HPT :: HomePackageTable,
519 -- ^ The home package table describes already-compiled
520 -- home-package modules, /excluding/ the module we
521 -- are compiling right now.
522 -- (In one-shot mode the current module is the only
523 -- home-package module, so hsc_HPT is empty. All other
524 -- modules count as \"external-package\" modules.
525 -- However, even in GHCi mode, hi-boot interfaces are
526 -- demand-loaded into the external-package table.)
528 -- 'hsc_HPT' is not mutable because we only demand-load
529 -- external packages; the home package is eagerly
530 -- loaded, module by module, by the compilation manager.
532 -- The HPT may contain modules compiled earlier by @--make@
533 -- but not actually below the current module in the dependency
536 -- (This changes a previous invariant: changed Jan 05.)
538 hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
539 -- ^ Information about the currently loaded external packages.
540 -- This is mutable because packages will be demand-loaded during
541 -- a compilation run as required.
543 hsc_NC :: {-# UNPACK #-} !(IORef NameCache),
544 -- ^ As with 'hsc_EPS', this is side-effected by compiling to
545 -- reflect sucking in interface files. They cache the state of
546 -- external interface files, in effect.
548 hsc_FC :: {-# UNPACK #-} !(IORef FinderCache),
549 -- ^ The cached result of performing finding in the file system
550 hsc_MLC :: {-# UNPACK #-} !(IORef ModLocationCache),
551 -- ^ This caches the location of modules, so we don't have to
552 -- search the filesystem multiple times. See also 'hsc_FC'.
554 hsc_OptFuel :: OptFuelState,
555 -- ^ Settings to control the use of \"optimization fuel\":
556 -- by limiting the number of transformations,
557 -- we can use binary search to help find compiler bugs.
559 hsc_type_env_var :: Maybe (Module, IORef TypeEnv),
560 -- ^ Used for one-shot compilation only, to initialise
561 -- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for
562 -- 'TcRunTypes.TcGblEnv'
564 hsc_global_rdr_env :: GlobalRdrEnv,
565 -- ^ A mapping from 'RdrName's that are in global scope during
566 -- the compilation of the current file to more detailed
567 -- information about those names. Not necessarily just the
568 -- names directly imported by the module being compiled!
570 hsc_global_type_env :: TypeEnv
571 -- ^ Typing information about all those things in global scope.
572 -- Not necessarily just the things directly imported by the module
576 hscEPS :: HscEnv -> IO ExternalPackageState
577 hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
579 -- | A compilation target.
581 -- A target may be supplied with the actual text of the
582 -- module. If so, use this instead of the file contents (this
583 -- is for use in an IDE where the file hasn't been saved by
586 { targetId :: TargetId -- ^ module or filename
587 , targetAllowObjCode :: Bool -- ^ object code allowed?
588 , targetContents :: Maybe (StringBuffer,ClockTime)
589 -- ^ in-memory text buffer?
593 = TargetModule ModuleName
594 -- ^ A module name: search for the file
595 | TargetFile FilePath (Maybe Phase)
596 -- ^ A filename: preprocess & parse it to find the module name.
597 -- If specified, the Phase indicates how to compile this file
598 -- (which phase to start from). Nothing indicates the starting phase
599 -- should be determined from the suffix of the filename.
602 pprTarget :: Target -> SDoc
603 pprTarget (Target id obj _) =
604 (if obj then char '*' else empty) <> pprTargetId id
606 instance Outputable Target where
609 pprTargetId :: TargetId -> SDoc
610 pprTargetId (TargetModule m) = ppr m
611 pprTargetId (TargetFile f _) = text f
613 instance Outputable TargetId where
616 -- | Helps us find information about modules in the home package
617 type HomePackageTable = ModuleNameEnv HomeModInfo
618 -- Domain = modules in the home package that have been fully compiled
619 -- "home" package name cached here for convenience
621 -- | Helps us find information about modules in the imported packages
622 type PackageIfaceTable = ModuleEnv ModIface
623 -- Domain = modules in the imported packages
625 emptyHomePackageTable :: HomePackageTable
626 emptyHomePackageTable = emptyUFM
628 emptyPackageIfaceTable :: PackageIfaceTable
629 emptyPackageIfaceTable = emptyModuleEnv
631 -- | Information about modules in the package being compiled
634 hm_iface :: !ModIface,
635 -- ^ The basic loaded interface file: every loaded module has one of
636 -- these, even if it is imported from another package
637 hm_details :: !ModDetails,
638 -- ^ Extra information that has been created from the 'ModIface' for
639 -- the module, typically during typechecking
640 hm_linkable :: !(Maybe Linkable)
641 -- ^ The actual artifact we would like to link to access things in
644 -- 'hm_linkable' might be Nothing:
646 -- 1. If this is an .hs-boot module
648 -- 2. Temporarily during compilation if we pruned away
649 -- the old linkable because it was out of date.
651 -- After a complete compilation ('GHC.load'), all 'hm_linkable' fields
652 -- in the 'HomePackageTable' will be @Just@.
654 -- When re-linking a module ('HscMain.HscNoRecomp'), we construct the
655 -- 'HomeModInfo' by building a new 'ModDetails' from the old
656 -- 'ModIface' (only).
659 -- | Find the 'ModIface' for a 'Module', searching in both the loaded home
660 -- and external package module information
667 lookupIfaceByModule dflags hpt pit mod
668 | modulePackageId mod == thisPackage dflags
669 = -- The module comes from the home package, so look first
670 -- in the HPT. If it's not from the home package it's wrong to look
671 -- in the HPT, because the HPT is indexed by *ModuleName* not Module
672 fmap hm_iface (lookupUFM hpt (moduleName mod))
673 `mplus` lookupModuleEnv pit mod
675 | otherwise = lookupModuleEnv pit mod -- Look in PIT only
677 -- If the module does come from the home package, why do we look in the PIT as well?
678 -- (a) In OneShot mode, even home-package modules accumulate in the PIT
679 -- (b) Even in Batch (--make) mode, there is *one* case where a home-package
680 -- module is in the PIT, namely GHC.Prim when compiling the base package.
681 -- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
682 -- of its own, but it doesn't seem worth the bother.
687 hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([Instance], [FamInst])
688 -- ^ Find all the instance declarations (of classes and families) that are in
689 -- modules imported by this one, directly or indirectly, and are in the Home
690 -- Package Table. This ensures that we don't see instances from modules @--make@
691 -- compiled before this one, but which are not below this one.
692 hptInstances hsc_env want_this_module
693 = let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do
694 guard (want_this_module (moduleName (mi_module (hm_iface mod_info))))
695 let details = hm_details mod_info
696 return (md_insts details, md_fam_insts details)
697 in (concat insts, concat famInsts)
699 hptVectInfo :: HscEnv -> VectInfo
700 -- ^ Get the combined VectInfo of all modules in the home package table. In
701 -- contrast to instances and rules, we don't care whether the modules are
702 -- \"below\" us in the dependency sense. The VectInfo of those modules not \"below\"
703 -- us does not affect the compilation of the current module.
704 hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details)
706 hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
707 -- ^ Get rules from modules \"below\" this one (in the dependency sense)
708 hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False
711 hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation]
712 -- ^ Get annotations from modules \"below\" this one (in the dependency sense)
713 hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps
714 hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env
716 hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a]
717 hptAllThings extract hsc_env = concatMap extract (eltsUFM (hsc_HPT hsc_env))
719 hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a]
720 -- Get things from modules \"below\" this one (in the dependency sense)
721 -- C.f Inst.hptInstances
722 hptSomeThingsBelowUs extract include_hi_boot hsc_env deps
723 | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
726 hpt = hsc_HPT hsc_env
729 | -- Find each non-hi-boot module below me
730 (mod, is_boot_mod) <- deps
731 , include_hi_boot || not is_boot_mod
733 -- unsavoury: when compiling the base package with --make, we
734 -- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't
735 -- be in the HPT, because we never compile it; it's in the EPT
736 -- instead. ToDo: clean up, and remove this slightly bogus
738 , mod /= moduleName gHC_PRIM
740 -- Look it up in the HPT
741 , let things = case lookupUFM hpt mod of
742 Just info -> extract info
743 Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg []
744 msg = vcat [ptext (sLit "missing module") <+> ppr mod,
745 ptext (sLit "Probable cause: out-of-date interface files")]
746 -- This really shouldn't happen, but see Trac #962
752 %************************************************************************
754 \subsection{Dealing with Annotations}
756 %************************************************************************
759 prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv
760 -- ^ Deal with gathering annotations in from all possible places
761 -- and combining them into a single 'AnnEnv'
762 prepareAnnotations hsc_env mb_guts
763 = do { eps <- hscEPS hsc_env
764 ; let -- Extract annotations from the module being compiled if supplied one
765 mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts
766 -- Extract dependencies of the module if we are supplied one,
767 -- otherwise load annotations from all home package table
768 -- entries regardless of dependency ordering.
769 home_pkg_anns = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts
770 other_pkg_anns = eps_ann_env eps
771 ann_env = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns,
778 %************************************************************************
780 \subsection{The Finder cache}
782 %************************************************************************
785 -- | The 'FinderCache' maps home module names to the result of
786 -- searching for that module. It records the results of searching for
787 -- modules along the search path. On @:load@, we flush the entire
788 -- contents of this cache.
790 -- Although the @FinderCache@ range is 'FindResult' for convenience ,
791 -- in fact it will only ever contain 'Found' or 'NotFound' entries.
793 type FinderCache = ModuleNameEnv FindResult
795 -- | The result of searching for an imported module.
797 = Found ModLocation Module
798 -- ^ The module was found
799 | NoPackage PackageId
800 -- ^ The requested package was not found
801 | FoundMultiple [PackageId]
802 -- ^ _Error_: both in multiple packages
803 | PackageHidden PackageId
804 -- ^ For an explicit source import, the package containing the module is
806 | ModuleHidden PackageId
807 -- ^ For an explicit source import, the package containing the module is
808 -- exposed, but the module itself is hidden.
809 | NotFound [FilePath] (Maybe PackageId)
810 -- ^ The module was not found, the specified places were searched
811 | NotFoundInPackage PackageId
812 -- ^ The module was not found in this package
814 -- | Cache that remembers where we found a particular module. Contains both
815 -- home modules and package modules. On @:load@, only home modules are
816 -- purged from this cache.
817 type ModLocationCache = ModuleEnv ModLocation
820 %************************************************************************
822 \subsection{Symbol tables and Module details}
824 %************************************************************************
827 -- | A 'ModIface' plus a 'ModDetails' summarises everything we know
828 -- about a compiled module. The 'ModIface' is the stuff *before* linking,
829 -- and can be written out to an interface file. The 'ModDetails is after
830 -- linking and can be completely recovered from just the 'ModIface'.
832 -- When we read an interface file, we also construct a 'ModIface' from it,
833 -- except that we explicitly make the 'mi_decls' and a few other fields empty;
834 -- as when reading we consolidate the declarations etc. into a number of indexed
835 -- maps and environments in the 'ExternalPackageState'.
838 mi_module :: !Module, -- ^ Name of the module we are for
839 mi_iface_hash :: !Fingerprint, -- ^ Hash of the whole interface
840 mi_mod_hash :: !Fingerprint, -- ^ Hash of the ABI only
842 mi_orphan :: !WhetherHasOrphans, -- ^ Whether this module has orphans
843 mi_finsts :: !WhetherHasFamInst, -- ^ Whether this module has family instances
844 mi_boot :: !IsBootInterface, -- ^ Read from an hi-boot file?
846 mi_deps :: Dependencies,
847 -- ^ The dependencies of the module, consulted for directly
848 -- imported modules only
850 -- This is consulted for directly-imported modules,
851 -- but not for anything else (hence lazy)
852 mi_usages :: [Usage],
853 -- ^ Usages; kept sorted so that it's easy to decide
854 -- whether to write a new iface file (changing usages
855 -- doesn't affect the hash of this module)
857 -- NOT STRICT! we read this field lazily from the interface file
858 -- It is *only* consulted by the recompilation checker
861 -- Kept sorted by (mod,occ), to make version comparisons easier
862 mi_exports :: ![IfaceExport],
863 -- ^ Records the modules that are the declaration points for things
864 -- exported by this module, and the 'OccName's of those things
866 mi_exp_hash :: !Fingerprint, -- ^ Hash of export list
868 mi_fixities :: [(OccName,Fixity)],
871 -- NOT STRICT! we read this field lazily from the interface file
873 mi_warns :: Warnings,
876 -- NOT STRICT! we read this field lazily from the interface file
878 mi_anns :: [IfaceAnnotation],
881 -- NOT STRICT! we read this field lazily from the interface file
883 -- Type, class and variable declarations
884 -- The hash of an Id changes if its fixity or deprecations change
885 -- (as well as its type of course)
886 -- Ditto data constructors, class operations, except that
887 -- the hash of the parent class/tycon changes
888 mi_decls :: [(Fingerprint,IfaceDecl)], -- ^ Sorted type, variable, class etc. declarations
890 mi_globals :: !(Maybe GlobalRdrEnv),
891 -- ^ Binds all the things defined at the top level in
892 -- the /original source/ code for this module. which
893 -- is NOT the same as mi_exports, nor mi_decls (which
894 -- may contains declarations for things not actually
895 -- defined by the user). Used for GHCi and for inspecting
896 -- the contents of modules via the GHC API only.
898 -- (We need the source file to figure out the
899 -- top-level environment, if we didn't compile this module
900 -- from source then this field contains @Nothing@).
902 -- Strictly speaking this field should live in the
903 -- 'HomeModInfo', but that leads to more plumbing.
905 -- Instance declarations and rules
906 mi_insts :: [IfaceInst], -- ^ Sorted class instance
907 mi_fam_insts :: [IfaceFamInst], -- ^ Sorted family instances
908 mi_rules :: [IfaceRule], -- ^ Sorted rules
909 mi_orphan_hash :: !Fingerprint, -- ^ Hash for orphan rules and
910 -- class and family instances
913 mi_vect_info :: !IfaceVectInfo, -- ^ Vectorisation information
915 -- Cached environments for easy lookup
916 -- These are computed (lazily) from other fields
917 -- and are not put into the interface file
918 mi_warn_fn :: Name -> Maybe WarningTxt, -- ^ Cached lookup for 'mi_warns'
919 mi_fix_fn :: OccName -> Fixity, -- ^ Cached lookup for 'mi_fixities'
920 mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint),
921 -- ^ Cached lookup for 'mi_decls'.
922 -- The @Nothing@ in 'mi_hash_fn' means that the thing
923 -- isn't in decls. It's useful to know that when
924 -- seeing if we are up to date wrt. the old interface.
925 -- The 'OccName' is the parent of the name, if it has one.
926 mi_hpc :: !AnyHpcUsage
927 -- ^ True if this program uses Hpc at any point in the program.
930 -- | The 'ModDetails' is essentially a cache for information in the 'ModIface'
931 -- for home modules only. Information relating to packages will be loaded into
932 -- global environments in 'ExternalPackageState'.
935 -- The next two fields are created by the typechecker
936 md_exports :: [AvailInfo],
937 md_types :: !TypeEnv, -- ^ Local type environment for this particular module
938 md_insts :: ![Instance], -- ^ 'DFunId's for the instances in this module
939 md_fam_insts :: ![FamInst],
940 md_rules :: ![CoreRule], -- ^ Domain may include 'Id's from other modules
941 md_anns :: ![Annotation], -- ^ Annotations present in this module: currently
942 -- they only annotate things also declared in this module
943 md_vect_info :: !VectInfo -- ^ Module vectorisation information
946 emptyModDetails :: ModDetails
947 emptyModDetails = ModDetails { md_types = emptyTypeEnv,
953 md_vect_info = noVectInfo
956 -- | Records the modules directly imported by a module for extracting e.g. usage information
957 type ImportedMods = ModuleEnv [(ModuleName, Bool, SrcSpan)]
958 -- TODO: we are not actually using the codomain of this type at all, so it can be
959 -- replaced with ModuleEnv ()
961 -- | A ModGuts is carried through the compiler, accumulating stuff as it goes
962 -- There is only one ModGuts at any time, the one for the module
963 -- being compiled right now. Once it is compiled, a 'ModIface' and
964 -- 'ModDetails' are extracted and the ModGuts is dicarded.
967 mg_module :: !Module, -- ^ Module being compiled
968 mg_boot :: IsBootInterface, -- ^ Whether it's an hs-boot module
969 mg_exports :: ![AvailInfo], -- ^ What it exports
970 mg_deps :: !Dependencies, -- ^ What it depends on, directly or
972 mg_dir_imps :: !ImportedMods, -- ^ Directly-imported modules; used to
973 -- generate initialisation code
974 mg_used_names:: !NameSet, -- ^ What the module needed (used in 'MkIface.mkIface')
976 mg_rdr_env :: !GlobalRdrEnv, -- ^ Top-level lexical environment
978 -- These fields all describe the things **declared in this module**
979 mg_fix_env :: !FixityEnv, -- ^ Fixities declared in this module
980 -- TODO: I'm unconvinced this is actually used anywhere
981 mg_types :: !TypeEnv, -- ^ Types declared in this module
982 mg_insts :: ![Instance], -- ^ Class instances declared in this module
983 mg_fam_insts :: ![FamInst], -- ^ Family instances declared in this module
984 mg_rules :: ![CoreRule], -- ^ Before the core pipeline starts, contains
985 -- rules declared in this module. After the core
986 -- pipeline starts, it is changed to contain all
987 -- known rules for those things imported
988 mg_binds :: ![CoreBind], -- ^ Bindings for this module
989 mg_foreign :: !ForeignStubs, -- ^ Foreign exports declared in this module
990 mg_warns :: !Warnings, -- ^ Warnings declared in the module
991 mg_anns :: [Annotation], -- ^ Annotations declared in this module
992 mg_hpc_info :: !HpcInfo, -- ^ Coverage tick boxes in the module
993 mg_modBreaks :: !ModBreaks, -- ^ Breakpoints for the module
994 mg_vect_info :: !VectInfo, -- ^ Pool of vectorised declarations in the module
996 -- The next two fields are unusual, because they give instance
997 -- environments for *all* modules in the home package, including
998 -- this module, rather than for *just* this module.
999 -- Reason: when looking up an instance we don't want to have to
1000 -- look at each module in the home package in turn
1001 mg_inst_env :: InstEnv,
1002 -- ^ Class instance environment from /home-package/ modules (including
1003 -- this one); c.f. 'tcg_inst_env'
1004 mg_fam_inst_env :: FamInstEnv
1005 -- ^ Type-family instance enviroment for /home-package/ modules
1006 -- (including this one); c.f. 'tcg_fam_inst_env'
1009 -- The ModGuts takes on several slightly different forms:
1011 -- After simplification, the following fields change slightly:
1012 -- mg_rules Orphan rules only (local ones now attached to binds)
1013 -- mg_binds With rules attached
1015 -- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for
1016 -- the 'GHC.compileToCoreModule' interface.
1020 cm_module :: !Module,
1021 -- | Type environment for types declared in this module
1022 cm_types :: !TypeEnv,
1024 cm_binds :: [CoreBind],
1026 cm_imports :: ![Module]
1029 instance Outputable CoreModule where
1030 ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb}) =
1031 text "%module" <+> ppr mn <+> ppr te $$ vcat (map ppr cb)
1033 -- The ModGuts takes on several slightly different forms:
1035 -- After simplification, the following fields change slightly:
1036 -- mg_rules Orphan rules only (local ones now attached to binds)
1037 -- mg_binds With rules attached
1040 ---------------------------------------------------------
1041 -- The Tidy pass forks the information about this module:
1042 -- * one lot goes to interface file generation (ModIface)
1043 -- and later compilations (ModDetails)
1044 -- * the other lot goes to code generation (CgGuts)
1046 -- | A restricted form of 'ModGuts' for code generation purposes
1049 cg_module :: !Module, -- ^ Module being compiled
1051 cg_tycons :: [TyCon],
1052 -- ^ Algebraic data types (including ones that started
1053 -- life as classes); generate constructors and info
1054 -- tables. Includes newtypes, just for the benefit of
1057 cg_binds :: [CoreBind],
1058 -- ^ The tidied main bindings, including
1059 -- previously-implicit bindings for record and class
1060 -- selectors, and data construtor wrappers. But *not*
1061 -- data constructor workers; reason: we we regard them
1062 -- as part of the code-gen of tycons
1064 cg_dir_imps :: ![Module],
1065 -- ^ Directly-imported modules; used to generate
1066 -- initialisation code
1068 cg_foreign :: !ForeignStubs, -- ^ Foreign export stubs
1069 cg_dep_pkgs :: ![PackageId], -- ^ Dependent packages, used to
1070 -- generate #includes for C code gen
1071 cg_hpc_info :: !HpcInfo, -- ^ Program coverage tick box information
1072 cg_modBreaks :: !ModBreaks -- ^ Module breakpoints
1075 -----------------------------------
1076 -- | Foreign export stubs
1077 data ForeignStubs = NoStubs -- ^ We don't have any stubs
1081 -- ^ There are some stubs. Parameters:
1083 -- 1) Header file prototypes for
1084 -- "foreign exported" functions
1086 -- 2) C stubs to use when calling
1087 -- "foreign exported" functions
1091 emptyModIface :: Module -> ModIface
1093 = ModIface { mi_module = mod,
1094 mi_iface_hash = fingerprint0,
1095 mi_mod_hash = fingerprint0,
1099 mi_deps = noDependencies,
1102 mi_exp_hash = fingerprint0,
1104 mi_warns = NoWarnings,
1110 mi_globals = Nothing,
1111 mi_orphan_hash = fingerprint0,
1112 mi_vect_info = noIfaceVectInfo,
1113 mi_warn_fn = emptyIfaceWarnCache,
1114 mi_fix_fn = emptyIfaceFixCache,
1115 mi_hash_fn = emptyIfaceHashCache,
1121 %************************************************************************
1123 \subsection{The interactive context}
1125 %************************************************************************
1128 -- | Interactive context, recording information relevant to GHCi
1129 data InteractiveContext
1130 = InteractiveContext {
1131 ic_toplev_scope :: [Module], -- ^ The context includes the "top-level" scope of
1134 ic_exports :: [Module], -- ^ The context includes just the exports of these
1137 ic_rn_gbl_env :: GlobalRdrEnv, -- ^ The contexts' cached 'GlobalRdrEnv', built from
1138 -- 'ic_toplev_scope' and 'ic_exports'
1140 ic_tmp_ids :: [Id], -- ^ Names bound during interaction with the user.
1141 -- Later Ids shadow earlier ones with the same OccName.
1143 ic_tyvars :: TyVarSet -- ^ Skolem type variables free in
1144 -- 'ic_tmp_ids'. These arise at
1145 -- breakpoints in a polymorphic
1146 -- context, where we have only partial
1147 -- type information.
1150 , ic_resume :: [Resume] -- ^ The stack of breakpoint contexts
1155 emptyInteractiveContext :: InteractiveContext
1156 emptyInteractiveContext
1157 = InteractiveContext { ic_toplev_scope = [],
1159 ic_rn_gbl_env = emptyGlobalRdrEnv,
1161 ic_tyvars = emptyVarSet
1167 icPrintUnqual :: DynFlags -> InteractiveContext -> PrintUnqualified
1168 icPrintUnqual dflags ictxt = mkPrintUnqualified dflags (ic_rn_gbl_env ictxt)
1171 extendInteractiveContext
1172 :: InteractiveContext
1175 -> InteractiveContext
1176 extendInteractiveContext ictxt ids tyvars
1177 = ictxt { ic_tmp_ids = snub((ic_tmp_ids ictxt \\ ids) ++ ids),
1178 -- NB. must be this way around, because we want
1179 -- new ids to shadow existing bindings.
1180 ic_tyvars = ic_tyvars ictxt `unionVarSet` tyvars }
1181 where snub = map head . group . sort
1183 substInteractiveContext :: InteractiveContext -> TvSubst -> InteractiveContext
1184 substInteractiveContext ictxt subst | isEmptyTvSubst subst = ictxt
1185 substInteractiveContext ictxt@InteractiveContext{ic_tmp_ids=ids} subst =
1186 let ids' = map (\id -> id `setIdType` substTy subst (idType id)) ids
1187 subst_dom= varEnvKeys$ getTvSubstEnv subst
1188 subst_ran= varEnvElts$ getTvSubstEnv subst
1189 new_tvs = [ tv | Just tv <- map getTyVar_maybe subst_ran]
1190 ic_tyvars'= (`delVarSetListByKey` subst_dom)
1191 . (`extendVarSetList` new_tvs)
1193 in ictxt { ic_tmp_ids = ids'
1194 , ic_tyvars = ic_tyvars' }
1196 where delVarSetListByKey = foldl' delVarSetByKey
1199 %************************************************************************
1201 Building a PrintUnqualified
1203 %************************************************************************
1205 Deciding how to print names is pretty tricky. We are given a name
1206 P:M.T, where P is the package name, M is the defining module, and T is
1207 the occurrence name, and we have to decide in which form to display
1208 the name given a GlobalRdrEnv describing the current scope.
1210 Ideally we want to display the name in the form in which it is in
1211 scope. However, the name might not be in scope at all, and that's
1212 where it gets tricky. Here are the cases:
1214 1. T uniquely maps to P:M.T ---> "T"
1215 2. there is an X for which X.T uniquely maps to P:M.T ---> "X.T"
1216 3. there is no binding for "M.T" ---> "M.T"
1217 4. otherwise ---> "P:M.T"
1219 3 and 4 apply when P:M.T is not in scope. In these cases we want to
1220 refer to the name as "M.T", but "M.T" might mean something else in the
1221 current scope (e.g. if there's an "import X as M"), so to avoid
1222 confusion we avoid using "M.T" if there's already a binding for it.
1224 There's one further subtlety: if the module M cannot be imported
1225 because it is not exposed by any package, then we must refer to it as
1226 "P:M". This is handled by the qual_mod component of PrintUnqualified.
1229 -- | Creates some functions that work out the best ways to format
1230 -- names for the user according to a set of heuristics
1231 mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified
1232 mkPrintUnqualified dflags env = (qual_name, qual_mod)
1234 qual_name mod occ -- The (mod,occ) pair is the original name of the thing
1235 | [gre] <- unqual_gres, right_name gre = NameUnqual
1236 -- If there's a unique entity that's in scope unqualified with 'occ'
1237 -- AND that entity is the right one, then we can use the unqualified name
1239 | [gre] <- qual_gres = NameQual (get_qual_mod (gre_prov gre))
1242 if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env)
1243 then NameNotInScope1
1244 else NameNotInScope2
1246 | otherwise = panic "mkPrintUnqualified"
1248 right_name gre = nameModule_maybe (gre_name gre) == Just mod
1250 unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
1251 qual_gres = filter right_name (lookupGlobalRdrEnv env occ)
1253 get_qual_mod LocalDef = moduleName mod
1254 get_qual_mod (Imported is) = ASSERT( not (null is) ) is_as (is_decl (head is))
1256 -- we can mention a module P:M without the P: qualifier iff
1257 -- "import M" would resolve unambiguously to P:M. (if P is the
1258 -- current package we can just assume it is unqualified).
1261 | modulePackageId mod == thisPackage dflags = False
1263 | [pkgconfig] <- [pkg | (pkg,exposed_module) <- lookup,
1264 exposed pkg && exposed_module],
1265 packageConfigId pkgconfig == modulePackageId mod
1266 -- this says: we are given a module P:M, is there just one exposed package
1267 -- that exposes a module M, and is it package P?
1271 where lookup = lookupModuleInAllPackages dflags (moduleName mod)
1275 %************************************************************************
1279 %************************************************************************
1282 -- | Determine the 'TyThing's brought into scope by another 'TyThing'
1283 -- /other/ than itself. For example, Id's don't have any implicit TyThings
1284 -- as they just bring themselves into scope, but classes bring their
1285 -- dictionary datatype, type constructor and some selector functions into
1286 -- scope, just for a start!
1288 -- N.B. the set of TyThings returned here *must* match the set of
1289 -- names returned by LoadIface.ifaceDeclSubBndrs, in the sense that
1290 -- TyThing.getOccName should define a bijection between the two lists.
1291 -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
1292 -- The order of the list does not matter.
1293 implicitTyThings :: TyThing -> [TyThing]
1295 -- For data and newtype declarations:
1296 implicitTyThings (ATyCon tc) =
1297 -- fields (names of selectors)
1298 map AnId (tyConSelIds tc) ++
1299 -- (possibly) implicit coercion and family coercion
1300 -- depending on whether it's a newtype or a family instance or both
1301 implicitCoTyCon tc ++
1302 -- for each data constructor in order,
1303 -- the contructor, worker, and (possibly) wrapper
1304 concatMap (extras_plus . ADataCon) (tyConDataCons tc)
1306 implicitTyThings (AClass cl)
1307 = -- dictionary datatype:
1310 -- [recursive call:]
1311 -- (possibly) newtype coercion; definitely no family coercion here
1314 -- (no wrapper by invariant)
1315 extras_plus (ATyCon (classTyCon cl)) ++
1317 -- No extras_plus (recursive call) for the classATs, because they
1318 -- are only the family decls; they have no implicit things
1319 map ATyCon (classATs cl) ++
1320 -- superclass and operation selectors
1321 map AnId (classSelIds cl)
1323 implicitTyThings (ADataCon dc) =
1324 -- For data cons add the worker and (possibly) wrapper
1325 map AnId (dataConImplicitIds dc)
1327 implicitTyThings (AnId _) = []
1329 -- add a thing and recursive call
1330 extras_plus :: TyThing -> [TyThing]
1331 extras_plus thing = thing : implicitTyThings thing
1333 -- For newtypes and indexed data types (and both),
1334 -- add the implicit coercion tycon
1335 implicitCoTyCon :: TyCon -> [TyThing]
1337 = map ATyCon . catMaybes $ [-- Just if newtype, Nothing if not
1338 newTyConCo_maybe tc,
1339 -- Just if family instance, Nothing if not
1340 tyConFamilyCoercion_maybe tc]
1342 -- sortByOcc = sortBy (\ x -> \ y -> getOccName x < getOccName y)
1345 -- | Returns @True@ if there should be no interface-file declaration
1346 -- for this thing on its own: either it is built-in, or it is part
1347 -- of some other declaration, or it is generated implicitly by some
1348 -- other declaration.
1349 isImplicitTyThing :: TyThing -> Bool
1350 isImplicitTyThing (ADataCon _) = True
1351 isImplicitTyThing (AnId id) = isImplicitId id
1352 isImplicitTyThing (AClass _) = False
1353 isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc
1355 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
1356 extendTypeEnvWithIds env ids
1357 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
1360 %************************************************************************
1364 %************************************************************************
1367 -- | A map from 'Name's to 'TyThing's, constructed by typechecking
1368 -- local declarations or interface files
1369 type TypeEnv = NameEnv TyThing
1371 emptyTypeEnv :: TypeEnv
1372 typeEnvElts :: TypeEnv -> [TyThing]
1373 typeEnvClasses :: TypeEnv -> [Class]
1374 typeEnvTyCons :: TypeEnv -> [TyCon]
1375 typeEnvIds :: TypeEnv -> [Id]
1376 typeEnvDataCons :: TypeEnv -> [DataCon]
1377 lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
1379 emptyTypeEnv = emptyNameEnv
1380 typeEnvElts env = nameEnvElts env
1381 typeEnvClasses env = [cl | AClass cl <- typeEnvElts env]
1382 typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
1383 typeEnvIds env = [id | AnId id <- typeEnvElts env]
1384 typeEnvDataCons env = [dc | ADataCon dc <- typeEnvElts env]
1386 mkTypeEnv :: [TyThing] -> TypeEnv
1387 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
1389 lookupTypeEnv = lookupNameEnv
1391 -- Extend the type environment
1392 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
1393 extendTypeEnv env thing = extendNameEnv env (getName thing) thing
1395 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
1396 extendTypeEnvList env things = foldl extendTypeEnv env things
1400 -- | Find the 'TyThing' for the given 'Name' by using all the resources
1401 -- at our disposal: the compiled modules in the 'HomePackageTable' and the
1402 -- compiled modules in other packages that live in 'PackageTypeEnv'. Note
1403 -- that this does NOT look up the 'TyThing' in the module being compiled: you
1404 -- have to do that yourself, if desired
1405 lookupType :: DynFlags
1411 lookupType dflags hpt pte name
1412 -- in one-shot, we don't use the HPT
1413 | not (isOneShot (ghcMode dflags)) && modulePackageId mod == this_pkg
1414 = do hm <- lookupUFM hpt (moduleName mod) -- Maybe monad
1415 lookupNameEnv (md_types (hm_details hm)) name
1417 = lookupNameEnv pte name
1418 where mod = ASSERT( isExternalName name ) nameModule name
1419 this_pkg = thisPackage dflags
1421 -- | As 'lookupType', but with a marginally easier-to-use interface
1422 -- if you have a 'HscEnv'
1423 lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing)
1424 lookupTypeHscEnv hsc_env name = do
1425 eps <- readIORef (hsc_EPS hsc_env)
1426 return $! lookupType dflags hpt (eps_PTE eps) name
1428 dflags = hsc_dflags hsc_env
1429 hpt = hsc_HPT hsc_env
1433 -- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise
1434 tyThingTyCon :: TyThing -> TyCon
1435 tyThingTyCon (ATyCon tc) = tc
1436 tyThingTyCon other = pprPanic "tyThingTyCon" (pprTyThing other)
1438 -- | Get the 'Class' from a 'TyThing' if it is a class thing. Panics otherwise
1439 tyThingClass :: TyThing -> Class
1440 tyThingClass (AClass cls) = cls
1441 tyThingClass other = pprPanic "tyThingClass" (pprTyThing other)
1443 -- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise
1444 tyThingDataCon :: TyThing -> DataCon
1445 tyThingDataCon (ADataCon dc) = dc
1446 tyThingDataCon other = pprPanic "tyThingDataCon" (pprTyThing other)
1448 -- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise
1449 tyThingId :: TyThing -> Id
1450 tyThingId (AnId id) = id
1451 tyThingId (ADataCon dc) = dataConWrapId dc
1452 tyThingId other = pprPanic "tyThingId" (pprTyThing other)
1455 %************************************************************************
1457 \subsection{MonadThings and friends}
1459 %************************************************************************
1462 -- | Class that abstracts out the common ability of the monads in GHC
1463 -- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides
1464 -- a number of related convenience functions for accessing particular
1465 -- kinds of 'TyThing'
1466 class Monad m => MonadThings m where
1467 lookupThing :: Name -> m TyThing
1469 lookupId :: Name -> m Id
1470 lookupId = liftM tyThingId . lookupThing
1472 lookupDataCon :: Name -> m DataCon
1473 lookupDataCon = liftM tyThingDataCon . lookupThing
1475 lookupTyCon :: Name -> m TyCon
1476 lookupTyCon = liftM tyThingTyCon . lookupThing
1478 lookupClass :: Name -> m Class
1479 lookupClass = liftM tyThingClass . lookupThing
1483 -- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
1484 mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
1485 -> (OccName -> Maybe (OccName, Fingerprint))
1486 mkIfaceHashCache pairs
1487 = \occ -> lookupOccEnv env occ
1489 env = foldr add_decl emptyOccEnv pairs
1490 add_decl (v,d) env0 = foldr add_imp env1 (ifaceDeclSubBndrs d)
1492 decl_name = ifName d
1493 env1 = extendOccEnv env0 decl_name (decl_name, v)
1494 add_imp bndr env = extendOccEnv env bndr (decl_name, v)
1496 emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
1497 emptyIfaceHashCache _occ = Nothing
1500 %************************************************************************
1502 \subsection{Auxiliary types}
1504 %************************************************************************
1506 These types are defined here because they are mentioned in ModDetails,
1507 but they are mostly elaborated elsewhere
1510 ------------------ Warnings -------------------------
1511 -- | Warning information for a module
1513 = NoWarnings -- ^ Nothing deprecated
1514 | WarnAll WarningTxt -- ^ Whole module deprecated
1515 | WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated
1517 -- Only an OccName is needed because
1518 -- (1) a deprecation always applies to a binding
1519 -- defined in the module in which the deprecation appears.
1520 -- (2) deprecations are only reported outside the defining module.
1521 -- this is important because, otherwise, if we saw something like
1523 -- {-# DEPRECATED f "" #-}
1526 -- g = let f = undefined in f
1528 -- we'd need more information than an OccName to know to say something
1529 -- about the use of f in h but not the use of the locally bound f in g
1531 -- however, because we only report about deprecations from the outside,
1532 -- and a module can only export one value called f,
1533 -- an OccName suffices.
1535 -- this is in contrast with fixity declarations, where we need to map
1536 -- a Name to its fixity declaration.
1539 -- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface'
1540 mkIfaceWarnCache :: Warnings -> Name -> Maybe WarningTxt
1541 mkIfaceWarnCache NoWarnings = \_ -> Nothing
1542 mkIfaceWarnCache (WarnAll t) = \_ -> Just t
1543 mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
1545 emptyIfaceWarnCache :: Name -> Maybe WarningTxt
1546 emptyIfaceWarnCache _ = Nothing
1548 plusWarns :: Warnings -> Warnings -> Warnings
1549 plusWarns d NoWarnings = d
1550 plusWarns NoWarnings d = d
1551 plusWarns _ (WarnAll t) = WarnAll t
1552 plusWarns (WarnAll t) _ = WarnAll t
1553 plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2)
1556 -- | A collection of 'AvailInfo' - several things that are \"available\"
1557 type Avails = [AvailInfo]
1558 -- | 'Name'd things that are available
1559 type AvailInfo = GenAvailInfo Name
1560 -- | 'RdrName'd things that are available
1561 type RdrAvailInfo = GenAvailInfo OccName
1563 -- | Records what things are "available", i.e. in scope
1564 data GenAvailInfo name = Avail name -- ^ An ordinary identifier in scope
1566 [name] -- ^ A type or class in scope. Parameters:
1568 -- 1) The name of the type or class
1570 -- 2) The available pieces of type or class.
1571 -- NB: If the type or class is itself
1572 -- to be in scope, it must be in this list.
1573 -- Thus, typically: @AvailTC Eq [Eq, ==, \/=]@
1575 -- Equality used when deciding if the interface has changed
1577 -- | The original names declared of a certain module that are exported
1578 type IfaceExport = (Module, [GenAvailInfo OccName])
1580 availsToNameSet :: [AvailInfo] -> NameSet
1581 availsToNameSet avails = foldr add emptyNameSet avails
1582 where add avail set = addListToNameSet set (availNames avail)
1584 availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo
1585 availsToNameEnv avails = foldr add emptyNameEnv avails
1586 where add avail env = extendNameEnvList env
1587 (zip (availNames avail) (repeat avail))
1589 -- | Just the main name made available, i.e. not the available pieces
1590 -- of type or class brought into scope by the 'GenAvailInfo'
1591 availName :: GenAvailInfo name -> name
1592 availName (Avail n) = n
1593 availName (AvailTC n _) = n
1595 -- | All names made available by the availability information
1596 availNames :: GenAvailInfo name -> [name]
1597 availNames (Avail n) = [n]
1598 availNames (AvailTC _ ns) = ns
1600 instance Outputable n => Outputable (GenAvailInfo n) where
1603 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
1604 pprAvail (Avail n) = ppr n
1605 pprAvail (AvailTC n ns) = ppr n <> braces (hsep (punctuate comma (map ppr ns)))
1609 -- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface'
1610 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
1611 mkIfaceFixCache pairs
1612 = \n -> lookupOccEnv env n `orElse` defaultFixity
1614 env = mkOccEnv pairs
1616 emptyIfaceFixCache :: OccName -> Fixity
1617 emptyIfaceFixCache _ = defaultFixity
1619 -- | Fixity environment mapping names to their fixities
1620 type FixityEnv = NameEnv FixItem
1622 -- | Fixity information for an 'Name'. We keep the OccName in the range
1623 -- so that we can generate an interface from it
1624 data FixItem = FixItem OccName Fixity
1626 instance Outputable FixItem where
1627 ppr (FixItem occ fix) = ppr fix <+> ppr occ
1629 emptyFixityEnv :: FixityEnv
1630 emptyFixityEnv = emptyNameEnv
1632 lookupFixity :: FixityEnv -> Name -> Fixity
1633 lookupFixity env n = case lookupNameEnv env n of
1634 Just (FixItem _ fix) -> fix
1635 Nothing -> defaultFixity
1639 %************************************************************************
1641 \subsection{WhatsImported}
1643 %************************************************************************
1646 -- | Records whether a module has orphans. An \"orphan\" is one of:
1648 -- * An instance declaration in a module other than the definition
1649 -- module for one of the type constructors or classes in the instance head
1651 -- * A transformation rule in a module other than the one defining
1652 -- the function in the head of the rule
1653 type WhetherHasOrphans = Bool
1655 -- | Does this module define family instances?
1656 type WhetherHasFamInst = Bool
1658 -- | Did this module originate from a *-boot file?
1659 type IsBootInterface = Bool
1661 -- | Dependency information about modules and packages below this one
1662 -- in the import hierarchy.
1664 -- Invariant: the dependencies of a module @M@ never includes @M@.
1666 -- Invariant: none of the lists contain duplicates.
1668 = Deps { dep_mods :: [(ModuleName, IsBootInterface)]
1669 -- ^ Home-package module dependencies
1670 , dep_pkgs :: [PackageId]
1671 -- ^ External package dependencies
1672 , dep_orphs :: [Module]
1673 -- ^ Orphan modules (whether home or external pkg),
1674 -- *not* including family instance orphans as they
1675 -- are anyway included in 'dep_finsts'
1676 , dep_finsts :: [Module]
1677 -- ^ Modules that contain family instances (whether the
1678 -- instances are from the home or an external package)
1681 -- Equality used only for old/new comparison in MkIface.addVersionInfo
1683 -- See 'TcRnTypes.ImportAvails' for details on dependencies.
1685 noDependencies :: Dependencies
1686 noDependencies = Deps [] [] [] []
1688 -- | Records modules that we depend on by making a direct import from
1690 = UsagePackageModule {
1692 -- ^ External package module depended on
1693 usg_mod_hash :: Fingerprint
1694 } -- ^ Module from another package
1696 usg_mod_name :: ModuleName,
1697 -- ^ Name of the module
1698 usg_mod_hash :: Fingerprint,
1699 -- ^ Cached module fingerprint
1700 usg_entities :: [(OccName,Fingerprint)],
1701 -- ^ Entities we depend on, sorted by occurrence name and fingerprinted.
1702 -- NB: usages are for parent names only, e.g. type constructors
1703 -- but not the associated data constructors.
1704 usg_exports :: Maybe Fingerprint
1705 -- ^ Fingerprint for the export list we used to depend on this module,
1706 -- if we depend on the export list
1707 } -- ^ Module from the current package
1709 -- The export list field is (Just v) if we depend on the export list:
1710 -- i.e. we imported the module directly, whether or not we
1711 -- enumerated the things we imported, or just imported
1713 -- We need to recompile if M's exports change, because
1714 -- if the import was import M, we might now have a name clash
1715 -- in the importing module.
1716 -- if the import was import M(x) M might no longer export x
1717 -- The only way we don't depend on the export list is if we have
1719 -- And of course, for modules that aren't imported directly we don't
1720 -- depend on their export lists
1724 %************************************************************************
1726 The External Package State
1728 %************************************************************************
1731 type PackageTypeEnv = TypeEnv
1732 type PackageRuleBase = RuleBase
1733 type PackageInstEnv = InstEnv
1734 type PackageFamInstEnv = FamInstEnv
1735 type PackageVectInfo = VectInfo
1736 type PackageAnnEnv = AnnEnv
1738 -- | Information about other packages that we have slurped in by reading
1739 -- their interface files
1740 data ExternalPackageState
1742 eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
1743 -- ^ In OneShot mode (only), home-package modules
1744 -- accumulate in the external package state, and are
1745 -- sucked in lazily. For these home-pkg modules
1746 -- (only) we need to record which are boot modules.
1747 -- We set this field after loading all the
1748 -- explicitly-imported interfaces, but before doing
1751 -- The 'ModuleName' part is not necessary, but it's useful for
1752 -- debug prints, and it's convenient because this field comes
1753 -- direct from 'TcRnTypes.imp_dep_mods'
1755 eps_PIT :: !PackageIfaceTable,
1756 -- ^ The 'ModIface's for modules in external packages
1757 -- whose interfaces we have opened.
1758 -- The declarations in these interface files are held in the
1759 -- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules'
1760 -- fields of this record, not in the 'mi_decls' fields of the
1761 -- interface we have sucked in.
1763 -- What /is/ in the PIT is:
1767 -- * Fingerprint info
1773 -- * Deprecations and warnings
1775 eps_PTE :: !PackageTypeEnv,
1776 -- ^ Result of typechecking all the external package
1777 -- interface files we have sucked in. The domain of
1778 -- the mapping is external-package modules
1780 eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated
1781 -- from all the external-package modules
1782 eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated
1783 -- from all the external-package modules
1784 eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated
1785 -- from all the external-package modules
1786 eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated
1787 -- from all the external-package modules
1788 eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated
1789 -- from all the external-package modules
1791 eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external
1792 -- packages, keyed off the module that declared them
1794 eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages
1797 -- | Accumulated statistics about what we are putting into the 'ExternalPackageState'.
1798 -- \"In\" means stuff that is just /read/ from interface files,
1799 -- \"Out\" means actually sucked in and type-checked
1800 data EpsStats = EpsStats { n_ifaces_in
1801 , n_decls_in, n_decls_out
1802 , n_rules_in, n_rules_out
1803 , n_insts_in, n_insts_out :: !Int }
1805 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
1806 -- ^ Add stats for one newly-read interface
1807 addEpsInStats stats n_decls n_insts n_rules
1808 = stats { n_ifaces_in = n_ifaces_in stats + 1
1809 , n_decls_in = n_decls_in stats + n_decls
1810 , n_insts_in = n_insts_in stats + n_insts
1811 , n_rules_in = n_rules_in stats + n_rules }
1814 Names in a NameCache are always stored as a Global, and have the SrcLoc
1815 of their binding locations.
1817 Actually that's not quite right. When we first encounter the original
1818 name, we might not be at its binding site (e.g. we are reading an
1819 interface file); so we give it 'noSrcLoc' then. Later, when we find
1820 its binding site, we fix it up.
1823 -- | The NameCache makes sure that there is just one Unique assigned for
1824 -- each original name; i.e. (module-name, occ-name) pair and provides
1825 -- something of a lookup mechanism for those names.
1827 = NameCache { nsUniqs :: UniqSupply,
1828 -- ^ Supply of uniques
1829 nsNames :: OrigNameCache,
1830 -- ^ Ensures that one original name gets one unique
1831 nsIPs :: OrigIParamCache
1832 -- ^ Ensures that one implicit parameter name gets one unique
1835 -- | Per-module cache of original 'OccName's given 'Name's
1836 type OrigNameCache = ModuleEnv (OccEnv Name)
1838 -- | Module-local cache of implicit parameter 'OccName's given 'Name's
1839 type OrigIParamCache = FiniteMap (IPName OccName) (IPName Name)
1844 %************************************************************************
1846 The module graph and ModSummary type
1847 A ModSummary is a node in the compilation manager's
1848 dependency graph, and it's also passed to hscMain
1850 %************************************************************************
1853 -- | A ModuleGraph contains all the nodes from the home package (only).
1854 -- There will be a node for each source module, plus a node for each hi-boot
1857 -- The graph is not necessarily stored in topologically-sorted order. Use
1858 -- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this.
1859 type ModuleGraph = [ModSummary]
1861 emptyMG :: ModuleGraph
1864 -- | A single node in a 'ModuleGraph. The nodes of the module graph are one of:
1866 -- * A regular Haskell source module
1868 -- * A hi-boot source module
1870 -- * An external-core source module
1873 ms_mod :: Module, -- ^ Identity of the module
1874 ms_hsc_src :: HscSource, -- ^ The module source either plain Haskell, hs-boot or external core
1875 ms_location :: ModLocation, -- ^ Location of the various files belonging to the module
1876 ms_hs_date :: ClockTime, -- ^ Timestamp of source file
1877 ms_obj_date :: Maybe ClockTime, -- ^ Timestamp of object, if we have one
1878 ms_srcimps :: [Located (ImportDecl RdrName)], -- ^ Source imports of the module
1879 ms_imps :: [Located (ImportDecl RdrName)], -- ^ Non-source imports of the module
1880 ms_hspp_file :: FilePath, -- ^ Filename of preprocessed source file
1881 ms_hspp_opts :: DynFlags, -- ^ Cached flags from @OPTIONS@, @INCLUDE@
1882 -- and @LANGUAGE@ pragmas in the modules source code
1883 ms_hspp_buf :: Maybe StringBuffer -- ^ The actual preprocessed source, if we have it
1886 ms_mod_name :: ModSummary -> ModuleName
1887 ms_mod_name = moduleName . ms_mod
1889 -- The ModLocation contains both the original source filename and the
1890 -- filename of the cleaned-up source file after all preprocessing has been
1891 -- done. The point is that the summariser will have to cpp/unlit/whatever
1892 -- all files anyway, and there's no point in doing this twice -- just
1893 -- park the result in a temp file, put the name of it in the location,
1894 -- and let @compile@ read from that file on the way back up.
1896 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
1897 -- the ms_hs_date and imports can, of course, change
1899 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
1900 msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
1901 msHiFilePath ms = ml_hi_file (ms_location ms)
1902 msObjFilePath ms = ml_obj_file (ms_location ms)
1904 -- | Did this 'ModSummary' originate from a hs-boot file?
1905 isBootSummary :: ModSummary -> Bool
1906 isBootSummary ms = isHsBoot (ms_hsc_src ms)
1908 instance Outputable ModSummary where
1910 = sep [text "ModSummary {",
1911 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1912 text "ms_mod =" <+> ppr (ms_mod ms)
1913 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
1914 text "ms_imps =" <+> ppr (ms_imps ms),
1915 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1919 showModMsg :: HscTarget -> Bool -> ModSummary -> String
1920 showModMsg target recomp mod_summary
1922 hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
1923 char '(', text (normalise $ msHsFilePath mod_summary) <> comma,
1925 HscInterpreted | recomp
1926 -> text "interpreted"
1927 HscNothing -> text "nothing"
1928 _ -> text (normalise $ msObjFilePath mod_summary),
1931 mod = moduleName (ms_mod mod_summary)
1932 mod_str = showSDoc (ppr mod) ++ hscSourceString (ms_hsc_src mod_summary)
1936 %************************************************************************
1938 \subsection{Hpc Support}
1940 %************************************************************************
1943 -- | Information about a modules use of Haskell Program Coverage
1946 { hpcInfoTickCount :: Int
1947 , hpcInfoHash :: Int
1950 { hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*?
1953 -- | This is used to signal if one of my imports used HPC instrumentation
1954 -- even if there is no module-local HPC usage
1955 type AnyHpcUsage = Bool
1957 emptyHpcInfo :: AnyHpcUsage -> HpcInfo
1958 emptyHpcInfo = NoHpcInfo
1960 -- | Find out if HPC is used by this module or any of the modules
1962 isHpcUsed :: HpcInfo -> AnyHpcUsage
1963 isHpcUsed (HpcInfo {}) = True
1964 isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
1967 %************************************************************************
1969 \subsection{Vectorisation Support}
1971 %************************************************************************
1973 The following information is generated and consumed by the vectorisation
1974 subsystem. It communicates the vectorisation status of declarations from one
1977 Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
1978 below? We need to know `f' when converting to IfaceVectInfo. However, during
1979 vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
1980 on just the OccName easily in a Core pass.
1983 -- | Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'.
1984 -- All of this information is always tidy, even in ModGuts.
1987 vectInfoVar :: VarEnv (Var , Var ), -- ^ @(f, f_v)@ keyed on @f@
1988 vectInfoTyCon :: NameEnv (TyCon , TyCon), -- ^ @(T, T_v)@ keyed on @T@
1989 vectInfoDataCon :: NameEnv (DataCon, DataCon), -- ^ @(C, C_v)@ keyed on @C@
1990 vectInfoPADFun :: NameEnv (TyCon , Var), -- ^ @(T_v, paT)@ keyed on @T_v@
1991 vectInfoIso :: NameEnv (TyCon , Var) -- ^ @(T, isoT)@ keyed on @T@
1994 -- | Vectorisation information for 'ModIface': a slightly less low-level view
1997 ifaceVectInfoVar :: [Name],
1998 -- ^ All variables in here have a vectorised variant
1999 ifaceVectInfoTyCon :: [Name],
2000 -- ^ All 'TyCon's in here have a vectorised variant;
2001 -- the name of the vectorised variant and those of its
2002 -- data constructors are determined by 'OccName.mkVectTyConOcc'
2003 -- and 'OccName.mkVectDataConOcc'; the names of
2004 -- the isomorphisms are determined by 'OccName.mkVectIsoOcc'
2005 ifaceVectInfoTyConReuse :: [Name]
2006 -- ^ The vectorised form of all the 'TyCon's in here coincides with
2007 -- the unconverted form; the name of the isomorphisms is determined
2008 -- by 'OccName.mkVectIsoOcc'
2011 noVectInfo :: VectInfo
2012 noVectInfo = VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyNameEnv emptyNameEnv
2014 plusVectInfo :: VectInfo -> VectInfo -> VectInfo
2015 plusVectInfo vi1 vi2 =
2016 VectInfo (vectInfoVar vi1 `plusVarEnv` vectInfoVar vi2)
2017 (vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2)
2018 (vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
2019 (vectInfoPADFun vi1 `plusNameEnv` vectInfoPADFun vi2)
2020 (vectInfoIso vi1 `plusNameEnv` vectInfoIso vi2)
2022 concatVectInfo :: [VectInfo] -> VectInfo
2023 concatVectInfo = foldr plusVectInfo noVectInfo
2025 noIfaceVectInfo :: IfaceVectInfo
2026 noIfaceVectInfo = IfaceVectInfo [] [] []
2029 %************************************************************************
2031 \subsection{Linkable stuff}
2033 %************************************************************************
2035 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
2036 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
2039 -- | Information we can use to dynamically link modules into the compiler
2040 data Linkable = LM {
2041 linkableTime :: ClockTime, -- ^ Time at which this linkable was built
2042 -- (i.e. when the bytecodes were produced,
2043 -- or the mod date on the files)
2044 linkableModule :: Module, -- ^ The linkable module itself
2045 linkableUnlinked :: [Unlinked]
2046 -- ^ Those files and chunks of code we have yet to link.
2048 -- INVARIANT: A valid linkable always has at least one 'Unlinked' item.
2049 -- If this list is empty, the Linkable represents a fake linkable, which
2050 -- is generated in HscNothing mode to avoid recompiling modules.
2052 -- XXX: Do items get removed from this list when they get linked?
2055 isObjectLinkable :: Linkable -> Bool
2056 isObjectLinkable l = not (null unlinked) && all isObject unlinked
2057 where unlinked = linkableUnlinked l
2058 -- A linkable with no Unlinked's is treated as a BCO. We can
2059 -- generate a linkable with no Unlinked's as a result of
2060 -- compiling a module in HscNothing mode, and this choice
2061 -- happens to work well with checkStability in module GHC.
2063 instance Outputable Linkable where
2064 ppr (LM when_made mod unlinkeds)
2065 = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
2066 $$ nest 3 (ppr unlinkeds)
2068 -------------------------------------------
2070 -- | Objects which have yet to be linked by the compiler
2072 = DotO FilePath -- ^ An object file (.o)
2073 | DotA FilePath -- ^ Static archive file (.a)
2074 | DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib)
2075 | BCOs CompiledByteCode ModBreaks -- ^ A byte-code object, lives only in memory
2078 data CompiledByteCode = CompiledByteCodeUndefined
2079 _unused :: CompiledByteCode
2080 _unused = CompiledByteCodeUndefined
2083 instance Outputable Unlinked where
2084 ppr (DotO path) = text "DotO" <+> text path
2085 ppr (DotA path) = text "DotA" <+> text path
2086 ppr (DotDLL path) = text "DotDLL" <+> text path
2088 ppr (BCOs bcos _) = text "BCOs" <+> ppr bcos
2090 ppr (BCOs _ _) = text "No byte code"
2093 -- | Is this an actual file on disk we can link in somehow?
2094 isObject :: Unlinked -> Bool
2095 isObject (DotO _) = True
2096 isObject (DotA _) = True
2097 isObject (DotDLL _) = True
2100 -- | Is this a bytecode linkable with no file on disk?
2101 isInterpretable :: Unlinked -> Bool
2102 isInterpretable = not . isObject
2104 -- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object
2105 nameOfObject :: Unlinked -> FilePath
2106 nameOfObject (DotO fn) = fn
2107 nameOfObject (DotA fn) = fn
2108 nameOfObject (DotDLL fn) = fn
2109 nameOfObject other = pprPanic "nameOfObject" (ppr other)
2111 -- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable
2112 byteCodeOfObject :: Unlinked -> CompiledByteCode
2113 byteCodeOfObject (BCOs bc _) = bc
2114 byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
2117 %************************************************************************
2119 \subsection{Breakpoint Support}
2121 %************************************************************************
2124 -- | Breakpoint index
2125 type BreakIndex = Int
2127 -- | All the information about the breakpoints for a given module
2130 { modBreaks_flags :: BreakArray
2131 -- ^ The array of flags, one per breakpoint,
2132 -- indicating which breakpoints are enabled.
2133 , modBreaks_locs :: !(Array BreakIndex SrcSpan)
2134 -- ^ An array giving the source span of each breakpoint.
2135 , modBreaks_vars :: !(Array BreakIndex [OccName])
2136 -- ^ An array giving the names of the free variables at each breakpoint.
2139 emptyModBreaks :: ModBreaks
2140 emptyModBreaks = ModBreaks
2141 { modBreaks_flags = error "ModBreaks.modBreaks_array not initialised"
2142 -- Todo: can we avoid this?
2143 , modBreaks_locs = array (0,-1) []
2144 , modBreaks_vars = array (0,-1) []