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, extendInteractiveContext,
58 substInteractiveContext,
59 mkPrintUnqualified, pprModulePrefix,
62 ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache,
66 FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
68 -- * TyThings and type environments
70 tyThingClass, tyThingTyCon, tyThingDataCon, tyThingId,
71 implicitTyThings, isImplicitTyThing,
73 TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv,
74 extendTypeEnv, extendTypeEnvList, extendTypeEnvWithIds, lookupTypeEnv,
75 typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
81 -- * Information on imports and exports
82 WhetherHasOrphans, IsBootInterface, Usage(..),
83 Dependencies(..), noDependencies,
84 NameCache(..), OrigNameCache, OrigIParamCache,
85 Avails, availsToNameSet, availsToNameEnv, availName, availNames,
86 GenAvailInfo(..), AvailInfo, RdrAvailInfo,
90 Warnings(..), WarningTxt(..), plusWarns,
93 Linkable(..), isObjectLinkable,
94 Unlinked(..), CompiledByteCode,
95 isObject, nameOfObject, isInterpretable, byteCodeOfObject,
98 HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
101 ModBreaks (..), BreakIndex, emptyModBreaks,
103 -- * Vectorisation information
104 VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo,
108 #include "HsVersions.h"
111 import ByteCodeAsm ( CompiledByteCode )
112 import {-# SOURCE #-} InteractiveEval ( Resume )
121 import InstEnv ( InstEnv, Instance )
122 import FamInstEnv ( FamInstEnv, FamInst )
123 import Rules ( RuleBase )
124 import CoreSyn ( CoreBind )
132 import Class ( Class, classSelIds, classATs, classTyCon )
134 import DataCon ( DataCon, dataConImplicitIds, dataConWrapId )
135 import PrelNames ( gHC_PRIM )
136 import Packages hiding ( Version(..) )
137 import DynFlags ( DynFlags(..), isOneShot, HscTarget (..), dopt,
139 import DriverPhases ( HscSource(..), isHsBoot, hscSourceString, Phase )
140 import BasicTypes ( IPName, defaultFixity, WarningTxt(..) )
141 import OptimizationFuel ( OptFuelState )
143 import FiniteMap ( FiniteMap )
144 import CoreSyn ( CoreRule )
145 import Maybes ( orElse, expectJust, catMaybes )
148 import SrcLoc ( SrcSpan, Located(..) )
149 import UniqFM ( lookupUFM, eltsUFM, emptyUFM )
150 import UniqSupply ( UniqSupply )
152 import StringBuffer ( StringBuffer )
155 import Data.Dynamic ( Typeable )
156 import qualified Data.Dynamic as Dyn
160 import System.FilePath
161 import System.Time ( ClockTime )
163 import Data.Array ( Array, array )
165 import Control.Monad ( mplus, guard, liftM, when )
170 %************************************************************************
172 \subsection{Compilation environment}
174 %************************************************************************
178 -- | The Session is a handle to the complete state of a compilation
179 -- session. A compilation session consists of a set of modules
180 -- constituting the current program or library, the context for
181 -- interactive evaluation, and various caches.
182 data Session = Session !(IORef HscEnv) !(IORef WarningMessages)
184 mkSrcErr :: ErrorMessages -> SourceError
185 srcErrorMessages :: SourceError -> ErrorMessages
186 mkApiErr :: SDoc -> GhcApiError
188 throwOneError :: MonadIO m => ErrMsg -> m ab
189 throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err
191 -- | A source error is an error that is caused by one or more errors in the
192 -- source code. A 'SourceError' is thrown by many functions in the
193 -- compilation pipeline. Inside GHC these errors are merely printed via
194 -- 'log_action', but API clients may treat them differently, for example,
195 -- insert them into a list box. If you want the default behaviour, use the
198 -- > handleSourceError printExceptionAndWarnings $ do
199 -- > ... api calls that may fail ...
201 -- The 'SourceError's error messages can be accessed via 'srcErrorMessages'.
202 -- This list may be empty if the compiler failed due to @-Werror@
203 -- ('Opt_WarnIsError').
205 -- See 'printExceptionAndWarnings' for more information on what to take care
206 -- of when writing a custom error handler.
207 data SourceError = SourceError ErrorMessages
209 instance Show SourceError where
210 show (SourceError msgs) = unlines . map show . bagToList $ msgs
211 -- ToDo: is there some nicer way to print this?
213 sourceErrorTc :: Dyn.TyCon
214 sourceErrorTc = Dyn.mkTyCon "SourceError"
215 {-# NOINLINE sourceErrorTc #-}
216 instance Typeable SourceError where
217 typeOf _ = Dyn.mkTyConApp sourceErrorTc []
219 instance Exception SourceError
221 mkSrcErr = SourceError
223 -- | Perform the given action and call the exception handler if the action
224 -- throws a 'SourceError'. See 'SourceError' for more information.
225 handleSourceError :: (ExceptionMonad m) =>
226 (SourceError -> m a) -- ^ exception handler
227 -> m a -- ^ action to perform
229 handleSourceError handler act =
230 gcatch act (\(e :: SourceError) -> handler e)
232 srcErrorMessages (SourceError msgs) = msgs
234 -- | XXX: what exactly is an API error?
235 data GhcApiError = GhcApiError SDoc
237 instance Show GhcApiError where
238 show (GhcApiError msg) = showSDoc msg
240 ghcApiErrorTc :: Dyn.TyCon
241 ghcApiErrorTc = Dyn.mkTyCon "GhcApiError"
242 {-# NOINLINE ghcApiErrorTc #-}
243 instance Typeable GhcApiError where
244 typeOf _ = Dyn.mkTyConApp ghcApiErrorTc []
246 instance Exception GhcApiError
248 mkApiErr = GhcApiError
250 -- | A monad that allows logging of warnings.
251 class Monad m => WarnLogMonad m where
252 setWarnings :: WarningMessages -> m ()
253 getWarnings :: m WarningMessages
255 logWarnings :: WarnLogMonad m => WarningMessages -> m ()
256 logWarnings warns = do
257 warns0 <- getWarnings
258 setWarnings (unionBags warns warns0)
260 -- | Clear the log of 'Warnings'.
261 clearWarnings :: WarnLogMonad m => m ()
262 clearWarnings = setWarnings emptyBag
264 -- | Returns true if there were any warnings.
265 hasWarnings :: WarnLogMonad m => m Bool
266 hasWarnings = getWarnings >>= return . not . isEmptyBag
268 -- | A monad that has all the features needed by GHC API calls.
270 -- In short, a GHC monad
272 -- - allows embedding of IO actions,
274 -- - can log warnings,
276 -- - allows handling of (extensible) exceptions, and
278 -- - maintains a current session.
280 -- If you do not use 'Ghc' or 'GhcT', make sure to call 'GHC.initGhcMonad'
281 -- before any call to the GHC API functions can occur.
283 class (Functor m, MonadIO m, WarnLogMonad m, ExceptionMonad m)
285 getSession :: m HscEnv
286 setSession :: HscEnv -> m ()
288 -- | Call the argument with the current session.
289 withSession :: GhcMonad m => (HscEnv -> m a) -> m a
290 withSession f = getSession >>= f
292 -- | Set the current session to the result of applying the current session to
294 modifySession :: GhcMonad m => (HscEnv -> HscEnv) -> m ()
295 modifySession f = do h <- getSession
298 withSavedSession :: GhcMonad m => m a -> m a
299 withSavedSession m = do
300 saved_session <- getSession
301 m `gfinally` setSession saved_session
303 -- | Call an action with a temporarily modified Session.
304 withTempSession :: GhcMonad m => (HscEnv -> HscEnv) -> m a -> m a
305 withTempSession f m =
306 withSavedSession $ modifySession f >> m
308 -- | A minimal implementation of a 'GhcMonad'. If you need a custom monad,
309 -- e.g., to maintain additional state consider wrapping this monad or using
311 newtype Ghc a = Ghc { unGhc :: Session -> IO a }
313 instance Functor Ghc where
314 fmap f m = Ghc $ \s -> f `fmap` unGhc m s
316 instance Monad Ghc where
317 return a = Ghc $ \_ -> return a
318 m >>= g = Ghc $ \s -> do a <- unGhc m s; unGhc (g a) s
320 instance MonadIO Ghc where
321 liftIO ioA = Ghc $ \_ -> ioA
323 instance ExceptionMonad Ghc where
325 Ghc $ \s -> unGhc act s `gcatch` \e -> unGhc (handle e) s
326 gblock (Ghc m) = Ghc $ \s -> gblock (m s)
327 gunblock (Ghc m) = Ghc $ \s -> gunblock (m s)
329 Ghc $ \s -> gmask $ \io_restore ->
331 g_restore (Ghc m) = Ghc $ \s -> io_restore (m s)
333 unGhc (f g_restore) s
335 instance WarnLogMonad Ghc where
336 setWarnings warns = Ghc $ \(Session _ wref) -> writeIORef wref warns
337 -- | Return 'Warnings' accumulated so far.
338 getWarnings = Ghc $ \(Session _ wref) -> readIORef wref
340 instance GhcMonad Ghc where
341 getSession = Ghc $ \(Session r _) -> readIORef r
342 setSession s' = Ghc $ \(Session r _) -> writeIORef r s'
344 -- | A monad transformer to add GHC specific features to another monad.
346 -- Note that the wrapped monad must support IO and handling of exceptions.
347 newtype GhcT m a = GhcT { unGhcT :: Session -> m a }
348 liftGhcT :: Monad m => m a -> GhcT m a
349 liftGhcT m = GhcT $ \_ -> m
351 instance Functor m => Functor (GhcT m) where
352 fmap f m = GhcT $ \s -> f `fmap` unGhcT m s
354 instance Monad m => Monad (GhcT m) where
355 return x = GhcT $ \_ -> return x
356 m >>= k = GhcT $ \s -> do a <- unGhcT m s; unGhcT (k a) s
358 instance MonadIO m => MonadIO (GhcT m) where
359 liftIO ioA = GhcT $ \_ -> liftIO ioA
361 instance ExceptionMonad m => ExceptionMonad (GhcT m) where
363 GhcT $ \s -> unGhcT act s `gcatch` \e -> unGhcT (handle e) s
364 gblock (GhcT m) = GhcT $ \s -> gblock (m s)
365 gunblock (GhcT m) = GhcT $ \s -> gunblock (m s)
367 GhcT $ \s -> gmask $ \io_restore ->
369 g_restore (GhcT m) = GhcT $ \s -> io_restore (m s)
371 unGhcT (f g_restore) s
373 instance MonadIO m => WarnLogMonad (GhcT m) where
374 setWarnings warns = GhcT $ \(Session _ wref) -> liftIO $ writeIORef wref warns
375 -- | Return 'Warnings' accumulated so far.
376 getWarnings = GhcT $ \(Session _ wref) -> liftIO $ readIORef wref
378 instance (Functor m, ExceptionMonad m, MonadIO m) => GhcMonad (GhcT m) where
379 getSession = GhcT $ \(Session r _) -> liftIO $ readIORef r
380 setSession s' = GhcT $ \(Session r _) -> liftIO $ writeIORef r s'
382 -- | Lift an IO action returning errors messages into a 'GhcMonad'.
384 -- In order to reduce dependencies to other parts of the compiler, functions
385 -- outside the "main" parts of GHC return warnings and errors as a parameter
386 -- and signal success via by wrapping the result in a 'Maybe' type. This
387 -- function logs the returned warnings and propagates errors as exceptions
388 -- (of type 'SourceError').
390 -- This function assumes the following invariants:
392 -- 1. If the second result indicates success (is of the form 'Just x'),
393 -- there must be no error messages in the first result.
395 -- 2. If there are no error messages, but the second result indicates failure
396 -- there should be warnings in the first result. That is, if the action
397 -- failed, it must have been due to the warnings (i.e., @-Werror@).
398 ioMsgMaybe :: GhcMonad m =>
399 IO (Messages, Maybe a) -> m a
401 ((warns,errs), mb_r) <- liftIO ioA
404 Nothing -> liftIO $ throwIO (mkSrcErr errs)
405 Just r -> ASSERT( isEmptyBag errs ) return r
407 -- | Lift a non-failing IO action into a 'GhcMonad'.
409 -- Like 'ioMsgMaybe', but assumes that the action will never return any error
411 ioMsg :: GhcMonad m => IO (Messages, a) -> m a
413 ((warns,errs), r) <- liftIO ioA
415 ASSERT( isEmptyBag errs ) return r
417 -- | Reflect a computation in the 'Ghc' monad into the 'IO' monad.
419 -- You can use this to call functions returning an action in the 'Ghc' monad
420 -- inside an 'IO' action. This is needed for some (too restrictive) callback
421 -- arguments of some library functions:
423 -- > libFunc :: String -> (Int -> IO a) -> IO a
424 -- > ghcFunc :: Int -> Ghc a
426 -- > ghcFuncUsingLibFunc :: String -> Ghc a -> Ghc a
427 -- > ghcFuncUsingLibFunc str =
428 -- > reifyGhc $ \s ->
429 -- > libFunc $ \i -> do
430 -- > reflectGhc (ghcFunc i) s
432 reflectGhc :: Ghc a -> Session -> IO a
433 reflectGhc m = unGhc m
435 -- > Dual to 'reflectGhc'. See its documentation.
436 reifyGhc :: (Session -> IO a) -> Ghc a
437 reifyGhc act = Ghc $ act
439 handleFlagWarnings :: GhcMonad m => DynFlags -> [Located String] -> m ()
440 handleFlagWarnings dflags warns
441 = when (dopt Opt_WarnDeprecatedFlags dflags)
442 (handleFlagWarnings' dflags warns)
444 handleFlagWarnings' :: GhcMonad m => DynFlags -> [Located String] -> m ()
445 handleFlagWarnings' _ [] = return ()
446 handleFlagWarnings' dflags warns
447 = do -- It would be nicer if warns :: [Located Message], but that has circular
449 logWarnings $ listToBag (map mkFlagWarning warns)
450 when (dopt Opt_WarnIsError dflags) $
451 liftIO $ throwIO $ mkSrcErr emptyBag
453 mkFlagWarning :: Located String -> WarnMsg
454 mkFlagWarning (L loc warn)
455 = mkPlainWarnMsg loc (text warn)
459 -- | These functions are called in various places of the GHC API.
461 -- API clients can override any of these callbacks to change GHC's default
466 -- | Called by 'load' after the compilating of each module.
468 -- The default implementation simply prints all warnings and errors to
469 -- @stderr@. Don't forget to call 'clearWarnings' when implementing your
472 -- The first argument is the module that was compiled.
474 -- The second argument is @Nothing@ if no errors occured, but there may
475 -- have been warnings. If it is @Just err@ at least one error has
476 -- occured. If 'srcErrorMessages' is empty, compilation failed due to
478 reportModuleCompilationResult :: GhcMonad m =>
479 ModSummary -> Maybe SourceError
483 -- | Temporarily modify the callbacks. After the action is executed all
484 -- callbacks are reset (not, however, any other modifications to the session
486 withLocalCallbacks :: GhcMonad m =>
487 (GhcApiCallbacks -> GhcApiCallbacks)
489 withLocalCallbacks f m = do
490 hsc_env <- getSession
491 let cb0 = hsc_callbacks hsc_env
493 setSession (hsc_env { hsc_callbacks = cb' `seq` cb' })
495 hsc_env' <- getSession
496 setSession (hsc_env' { hsc_callbacks = cb0 })
502 -- | Hscenv is like 'Session', except that some of the fields are immutable.
503 -- An HscEnv is used to compile a single module from plain Haskell source
504 -- code (after preprocessing) to either C, assembly or C--. Things like
505 -- the module graph don't change during a single compilation.
507 -- Historical note: \"hsc\" used to be the name of the compiler binary,
508 -- when there was a separate driver and compiler. To compile a single
509 -- module, the driver would invoke hsc on the source code... so nowadays
510 -- we think of hsc as the layer of the compiler that deals with compiling
514 hsc_dflags :: DynFlags,
515 -- ^ The dynamic flag settings
517 hsc_callbacks :: GhcApiCallbacks,
518 -- ^ Callbacks for the GHC API.
520 hsc_targets :: [Target],
521 -- ^ The targets (or roots) of the current session
523 hsc_mod_graph :: ModuleGraph,
524 -- ^ The module graph of the current session
526 hsc_IC :: InteractiveContext,
527 -- ^ The context for evaluating interactive statements
529 hsc_HPT :: HomePackageTable,
530 -- ^ The home package table describes already-compiled
531 -- home-package modules, /excluding/ the module we
532 -- are compiling right now.
533 -- (In one-shot mode the current module is the only
534 -- home-package module, so hsc_HPT is empty. All other
535 -- modules count as \"external-package\" modules.
536 -- However, even in GHCi mode, hi-boot interfaces are
537 -- demand-loaded into the external-package table.)
539 -- 'hsc_HPT' is not mutable because we only demand-load
540 -- external packages; the home package is eagerly
541 -- loaded, module by module, by the compilation manager.
543 -- The HPT may contain modules compiled earlier by @--make@
544 -- but not actually below the current module in the dependency
547 -- (This changes a previous invariant: changed Jan 05.)
549 hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
550 -- ^ Information about the currently loaded external packages.
551 -- This is mutable because packages will be demand-loaded during
552 -- a compilation run as required.
554 hsc_NC :: {-# UNPACK #-} !(IORef NameCache),
555 -- ^ As with 'hsc_EPS', this is side-effected by compiling to
556 -- reflect sucking in interface files. They cache the state of
557 -- external interface files, in effect.
559 hsc_FC :: {-# UNPACK #-} !(IORef FinderCache),
560 -- ^ The cached result of performing finding in the file system
561 hsc_MLC :: {-# UNPACK #-} !(IORef ModLocationCache),
562 -- ^ This caches the location of modules, so we don't have to
563 -- search the filesystem multiple times. See also 'hsc_FC'.
565 hsc_OptFuel :: OptFuelState,
566 -- ^ Settings to control the use of \"optimization fuel\":
567 -- by limiting the number of transformations,
568 -- we can use binary search to help find compiler bugs.
570 hsc_type_env_var :: Maybe (Module, IORef TypeEnv),
571 -- ^ Used for one-shot compilation only, to initialise
572 -- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for
573 -- 'TcRunTypes.TcGblEnv'
575 hsc_global_rdr_env :: GlobalRdrEnv,
576 -- ^ A mapping from 'RdrName's that are in global scope during
577 -- the compilation of the current file to more detailed
578 -- information about those names. Not necessarily just the
579 -- names directly imported by the module being compiled!
581 hsc_global_type_env :: TypeEnv
582 -- ^ Typing information about all those things in global scope.
583 -- Not necessarily just the things directly imported by the module
587 hscEPS :: HscEnv -> IO ExternalPackageState
588 hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
590 -- | A compilation target.
592 -- A target may be supplied with the actual text of the
593 -- module. If so, use this instead of the file contents (this
594 -- is for use in an IDE where the file hasn't been saved by
597 { targetId :: TargetId -- ^ module or filename
598 , targetAllowObjCode :: Bool -- ^ object code allowed?
599 , targetContents :: Maybe (StringBuffer,ClockTime)
600 -- ^ in-memory text buffer?
604 = TargetModule ModuleName
605 -- ^ A module name: search for the file
606 | TargetFile FilePath (Maybe Phase)
607 -- ^ A filename: preprocess & parse it to find the module name.
608 -- If specified, the Phase indicates how to compile this file
609 -- (which phase to start from). Nothing indicates the starting phase
610 -- should be determined from the suffix of the filename.
613 pprTarget :: Target -> SDoc
614 pprTarget (Target id obj _) =
615 (if obj then char '*' else empty) <> pprTargetId id
617 instance Outputable Target where
620 pprTargetId :: TargetId -> SDoc
621 pprTargetId (TargetModule m) = ppr m
622 pprTargetId (TargetFile f _) = text f
624 instance Outputable TargetId where
627 -- | Helps us find information about modules in the home package
628 type HomePackageTable = ModuleNameEnv HomeModInfo
629 -- Domain = modules in the home package that have been fully compiled
630 -- "home" package name cached here for convenience
632 -- | Helps us find information about modules in the imported packages
633 type PackageIfaceTable = ModuleEnv ModIface
634 -- Domain = modules in the imported packages
636 emptyHomePackageTable :: HomePackageTable
637 emptyHomePackageTable = emptyUFM
639 emptyPackageIfaceTable :: PackageIfaceTable
640 emptyPackageIfaceTable = emptyModuleEnv
642 -- | Information about modules in the package being compiled
645 hm_iface :: !ModIface,
646 -- ^ The basic loaded interface file: every loaded module has one of
647 -- these, even if it is imported from another package
648 hm_details :: !ModDetails,
649 -- ^ Extra information that has been created from the 'ModIface' for
650 -- the module, typically during typechecking
651 hm_linkable :: !(Maybe Linkable)
652 -- ^ The actual artifact we would like to link to access things in
655 -- 'hm_linkable' might be Nothing:
657 -- 1. If this is an .hs-boot module
659 -- 2. Temporarily during compilation if we pruned away
660 -- the old linkable because it was out of date.
662 -- After a complete compilation ('GHC.load'), all 'hm_linkable' fields
663 -- in the 'HomePackageTable' will be @Just@.
665 -- When re-linking a module ('HscMain.HscNoRecomp'), we construct the
666 -- 'HomeModInfo' by building a new 'ModDetails' from the old
667 -- 'ModIface' (only).
670 -- | Find the 'ModIface' for a 'Module', searching in both the loaded home
671 -- and external package module information
678 lookupIfaceByModule dflags hpt pit mod
679 | modulePackageId mod == thisPackage dflags
680 = -- The module comes from the home package, so look first
681 -- in the HPT. If it's not from the home package it's wrong to look
682 -- in the HPT, because the HPT is indexed by *ModuleName* not Module
683 fmap hm_iface (lookupUFM hpt (moduleName mod))
684 `mplus` lookupModuleEnv pit mod
686 | otherwise = lookupModuleEnv pit mod -- Look in PIT only
688 -- If the module does come from the home package, why do we look in the PIT as well?
689 -- (a) In OneShot mode, even home-package modules accumulate in the PIT
690 -- (b) Even in Batch (--make) mode, there is *one* case where a home-package
691 -- module is in the PIT, namely GHC.Prim when compiling the base package.
692 -- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
693 -- of its own, but it doesn't seem worth the bother.
698 hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([Instance], [FamInst])
699 -- ^ Find all the instance declarations (of classes and families) that are in
700 -- modules imported by this one, directly or indirectly, and are in the Home
701 -- Package Table. This ensures that we don't see instances from modules @--make@
702 -- compiled before this one, but which are not below this one.
703 hptInstances hsc_env want_this_module
704 = let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do
705 guard (want_this_module (moduleName (mi_module (hm_iface mod_info))))
706 let details = hm_details mod_info
707 return (md_insts details, md_fam_insts details)
708 in (concat insts, concat famInsts)
710 hptVectInfo :: HscEnv -> VectInfo
711 -- ^ Get the combined VectInfo of all modules in the home package table. In
712 -- contrast to instances and rules, we don't care whether the modules are
713 -- \"below\" us in the dependency sense. The VectInfo of those modules not \"below\"
714 -- us does not affect the compilation of the current module.
715 hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details)
717 hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
718 -- ^ Get rules from modules \"below\" this one (in the dependency sense)
719 hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False
722 hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation]
723 -- ^ Get annotations from modules \"below\" this one (in the dependency sense)
724 hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps
725 hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env
727 hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a]
728 hptAllThings extract hsc_env = concatMap extract (eltsUFM (hsc_HPT hsc_env))
730 hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a]
731 -- Get things from modules \"below\" this one (in the dependency sense)
732 -- C.f Inst.hptInstances
733 hptSomeThingsBelowUs extract include_hi_boot hsc_env deps
734 | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
737 hpt = hsc_HPT hsc_env
740 | -- Find each non-hi-boot module below me
741 (mod, is_boot_mod) <- deps
742 , include_hi_boot || not is_boot_mod
744 -- unsavoury: when compiling the base package with --make, we
745 -- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't
746 -- be in the HPT, because we never compile it; it's in the EPT
747 -- instead. ToDo: clean up, and remove this slightly bogus
749 , mod /= moduleName gHC_PRIM
751 -- Look it up in the HPT
752 , let things = case lookupUFM hpt mod of
753 Just info -> extract info
754 Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg []
755 msg = vcat [ptext (sLit "missing module") <+> ppr mod,
756 ptext (sLit "Probable cause: out-of-date interface files")]
757 -- This really shouldn't happen, but see Trac #962
763 %************************************************************************
765 \subsection{Dealing with Annotations}
767 %************************************************************************
770 prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv
771 -- ^ Deal with gathering annotations in from all possible places
772 -- and combining them into a single 'AnnEnv'
773 prepareAnnotations hsc_env mb_guts
774 = do { eps <- hscEPS hsc_env
775 ; let -- Extract annotations from the module being compiled if supplied one
776 mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts
777 -- Extract dependencies of the module if we are supplied one,
778 -- otherwise load annotations from all home package table
779 -- entries regardless of dependency ordering.
780 home_pkg_anns = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts
781 other_pkg_anns = eps_ann_env eps
782 ann_env = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns,
789 %************************************************************************
791 \subsection{The Finder cache}
793 %************************************************************************
796 -- | The 'FinderCache' maps home module names to the result of
797 -- searching for that module. It records the results of searching for
798 -- modules along the search path. On @:load@, we flush the entire
799 -- contents of this cache.
801 -- Although the @FinderCache@ range is 'FindResult' for convenience ,
802 -- in fact it will only ever contain 'Found' or 'NotFound' entries.
804 type FinderCache = ModuleNameEnv FindResult
806 -- | The result of searching for an imported module.
808 = Found ModLocation Module
809 -- ^ The module was found
810 | NoPackage PackageId
811 -- ^ The requested package was not found
812 | FoundMultiple [PackageId]
813 -- ^ _Error_: both in multiple packages
814 | NotFound [FilePath] (Maybe PackageId) [PackageId] [PackageId]
815 -- ^ The module was not found, including either
816 -- * the specified places were searched
817 -- * the package that this module should have been in
818 -- * list of packages in which the module was hidden,
819 -- * list of hidden packages containing this module
820 | NotFoundInPackage PackageId
821 -- ^ The module was not found in this package
823 -- | Cache that remembers where we found a particular module. Contains both
824 -- home modules and package modules. On @:load@, only home modules are
825 -- purged from this cache.
826 type ModLocationCache = ModuleEnv ModLocation
829 %************************************************************************
831 \subsection{Symbol tables and Module details}
833 %************************************************************************
836 -- | A 'ModIface' plus a 'ModDetails' summarises everything we know
837 -- about a compiled module. The 'ModIface' is the stuff *before* linking,
838 -- and can be written out to an interface file. The 'ModDetails is after
839 -- linking and can be completely recovered from just the 'ModIface'.
841 -- When we read an interface file, we also construct a 'ModIface' from it,
842 -- except that we explicitly make the 'mi_decls' and a few other fields empty;
843 -- as when reading we consolidate the declarations etc. into a number of indexed
844 -- maps and environments in the 'ExternalPackageState'.
847 mi_module :: !Module, -- ^ Name of the module we are for
848 mi_iface_hash :: !Fingerprint, -- ^ Hash of the whole interface
849 mi_mod_hash :: !Fingerprint, -- ^ Hash of the ABI only
851 mi_orphan :: !WhetherHasOrphans, -- ^ Whether this module has orphans
852 mi_finsts :: !WhetherHasFamInst, -- ^ Whether this module has family instances
853 mi_boot :: !IsBootInterface, -- ^ Read from an hi-boot file?
855 mi_deps :: Dependencies,
856 -- ^ The dependencies of the module. This is
857 -- consulted for directly-imported modules, but not
858 -- for anything else (hence lazy)
860 mi_usages :: [Usage],
861 -- ^ Usages; kept sorted so that it's easy to decide
862 -- whether to write a new iface file (changing usages
863 -- doesn't affect the hash of this module)
865 -- NOT STRICT! we read this field lazily from the interface file
866 -- It is *only* consulted by the recompilation checker
869 -- Kept sorted by (mod,occ), to make version comparisons easier
870 mi_exports :: ![IfaceExport],
871 -- ^ Records the modules that are the declaration points for things
872 -- exported by this module, and the 'OccName's of those things
874 mi_exp_hash :: !Fingerprint, -- ^ Hash of export list
876 mi_fixities :: [(OccName,Fixity)],
879 -- NOT STRICT! we read this field lazily from the interface file
881 mi_warns :: Warnings,
884 -- NOT STRICT! we read this field lazily from the interface file
886 mi_anns :: [IfaceAnnotation],
889 -- NOT STRICT! we read this field lazily from the interface file
891 -- Type, class and variable declarations
892 -- The hash of an Id changes if its fixity or deprecations change
893 -- (as well as its type of course)
894 -- Ditto data constructors, class operations, except that
895 -- the hash of the parent class/tycon changes
896 mi_decls :: [(Fingerprint,IfaceDecl)], -- ^ Sorted type, variable, class etc. declarations
898 mi_globals :: !(Maybe GlobalRdrEnv),
899 -- ^ Binds all the things defined at the top level in
900 -- the /original source/ code for this module. which
901 -- is NOT the same as mi_exports, nor mi_decls (which
902 -- may contains declarations for things not actually
903 -- defined by the user). Used for GHCi and for inspecting
904 -- the contents of modules via the GHC API only.
906 -- (We need the source file to figure out the
907 -- top-level environment, if we didn't compile this module
908 -- from source then this field contains @Nothing@).
910 -- Strictly speaking this field should live in the
911 -- 'HomeModInfo', but that leads to more plumbing.
913 -- Instance declarations and rules
914 mi_insts :: [IfaceInst], -- ^ Sorted class instance
915 mi_fam_insts :: [IfaceFamInst], -- ^ Sorted family instances
916 mi_rules :: [IfaceRule], -- ^ Sorted rules
917 mi_orphan_hash :: !Fingerprint, -- ^ Hash for orphan rules and
918 -- class and family instances
921 mi_vect_info :: !IfaceVectInfo, -- ^ Vectorisation information
923 -- Cached environments for easy lookup
924 -- These are computed (lazily) from other fields
925 -- and are not put into the interface file
926 mi_warn_fn :: Name -> Maybe WarningTxt, -- ^ Cached lookup for 'mi_warns'
927 mi_fix_fn :: OccName -> Fixity, -- ^ Cached lookup for 'mi_fixities'
928 mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint),
929 -- ^ Cached lookup for 'mi_decls'.
930 -- The @Nothing@ in 'mi_hash_fn' means that the thing
931 -- isn't in decls. It's useful to know that when
932 -- seeing if we are up to date wrt. the old interface.
933 -- The 'OccName' is the parent of the name, if it has one.
934 mi_hpc :: !AnyHpcUsage
935 -- ^ True if this program uses Hpc at any point in the program.
938 -- | The 'ModDetails' is essentially a cache for information in the 'ModIface'
939 -- for home modules only. Information relating to packages will be loaded into
940 -- global environments in 'ExternalPackageState'.
943 -- The next two fields are created by the typechecker
944 md_exports :: [AvailInfo],
945 md_types :: !TypeEnv, -- ^ Local type environment for this particular module
946 md_insts :: ![Instance], -- ^ 'DFunId's for the instances in this module
947 md_fam_insts :: ![FamInst],
948 md_rules :: ![CoreRule], -- ^ Domain may include 'Id's from other modules
949 md_anns :: ![Annotation], -- ^ Annotations present in this module: currently
950 -- they only annotate things also declared in this module
951 md_vect_info :: !VectInfo -- ^ Module vectorisation information
954 emptyModDetails :: ModDetails
955 emptyModDetails = ModDetails { md_types = emptyTypeEnv,
961 md_vect_info = noVectInfo
964 -- | Records the modules directly imported by a module for extracting e.g. usage information
965 type ImportedMods = ModuleEnv [(ModuleName, Bool, SrcSpan)]
966 -- TODO: we are not actually using the codomain of this type at all, so it can be
967 -- replaced with ModuleEnv ()
969 -- | A ModGuts is carried through the compiler, accumulating stuff as it goes
970 -- There is only one ModGuts at any time, the one for the module
971 -- being compiled right now. Once it is compiled, a 'ModIface' and
972 -- 'ModDetails' are extracted and the ModGuts is dicarded.
975 mg_module :: !Module, -- ^ Module being compiled
976 mg_boot :: IsBootInterface, -- ^ Whether it's an hs-boot module
977 mg_exports :: ![AvailInfo], -- ^ What it exports
978 mg_deps :: !Dependencies, -- ^ What it depends on, directly or
980 mg_dir_imps :: !ImportedMods, -- ^ Directly-imported modules; used to
981 -- generate initialisation code
982 mg_used_names:: !NameSet, -- ^ What the module needed (used in 'MkIface.mkIface')
984 mg_rdr_env :: !GlobalRdrEnv, -- ^ Top-level lexical environment
986 -- These fields all describe the things **declared in this module**
987 mg_fix_env :: !FixityEnv, -- ^ Fixities declared in this module
988 -- TODO: I'm unconvinced this is actually used anywhere
989 mg_types :: !TypeEnv, -- ^ Types declared in this module
990 mg_insts :: ![Instance], -- ^ Class instances declared in this module
991 mg_fam_insts :: ![FamInst], -- ^ Family instances declared in this module
992 mg_rules :: ![CoreRule], -- ^ Before the core pipeline starts, contains
993 -- See Note [Overall plumbing for rules] in Rules.lhs
994 mg_binds :: ![CoreBind], -- ^ Bindings for this module
995 mg_foreign :: !ForeignStubs, -- ^ Foreign exports declared in this module
996 mg_warns :: !Warnings, -- ^ Warnings declared in the module
997 mg_anns :: [Annotation], -- ^ Annotations declared in this module
998 mg_hpc_info :: !HpcInfo, -- ^ Coverage tick boxes in the module
999 mg_modBreaks :: !ModBreaks, -- ^ Breakpoints for the module
1000 mg_vect_info :: !VectInfo, -- ^ Pool of vectorised declarations in the module
1002 -- The next two fields are unusual, because they give instance
1003 -- environments for *all* modules in the home package, including
1004 -- this module, rather than for *just* this module.
1005 -- Reason: when looking up an instance we don't want to have to
1006 -- look at each module in the home package in turn
1007 mg_inst_env :: InstEnv,
1008 -- ^ Class instance environment from /home-package/ modules (including
1009 -- this one); c.f. 'tcg_inst_env'
1010 mg_fam_inst_env :: FamInstEnv
1011 -- ^ Type-family instance enviroment for /home-package/ modules
1012 -- (including this one); c.f. 'tcg_fam_inst_env'
1015 -- The ModGuts takes on several slightly different forms:
1017 -- After simplification, the following fields change slightly:
1018 -- mg_rules Orphan rules only (local ones now attached to binds)
1019 -- mg_binds With rules attached
1021 -- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for
1022 -- the 'GHC.compileToCoreModule' interface.
1026 cm_module :: !Module,
1027 -- | Type environment for types declared in this module
1028 cm_types :: !TypeEnv,
1030 cm_binds :: [CoreBind],
1032 cm_imports :: ![Module]
1035 instance Outputable CoreModule where
1036 ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb}) =
1037 text "%module" <+> ppr mn <+> ppr te $$ vcat (map ppr cb)
1039 -- The ModGuts takes on several slightly different forms:
1041 -- After simplification, the following fields change slightly:
1042 -- mg_rules Orphan rules only (local ones now attached to binds)
1043 -- mg_binds With rules attached
1046 ---------------------------------------------------------
1047 -- The Tidy pass forks the information about this module:
1048 -- * one lot goes to interface file generation (ModIface)
1049 -- and later compilations (ModDetails)
1050 -- * the other lot goes to code generation (CgGuts)
1052 -- | A restricted form of 'ModGuts' for code generation purposes
1055 cg_module :: !Module, -- ^ Module being compiled
1057 cg_tycons :: [TyCon],
1058 -- ^ Algebraic data types (including ones that started
1059 -- life as classes); generate constructors and info
1060 -- tables. Includes newtypes, just for the benefit of
1063 cg_binds :: [CoreBind],
1064 -- ^ The tidied main bindings, including
1065 -- previously-implicit bindings for record and class
1066 -- selectors, and data construtor wrappers. But *not*
1067 -- data constructor workers; reason: we we regard them
1068 -- as part of the code-gen of tycons
1070 cg_dir_imps :: ![Module],
1071 -- ^ Directly-imported modules; used to generate
1072 -- initialisation code
1074 cg_foreign :: !ForeignStubs, -- ^ Foreign export stubs
1075 cg_dep_pkgs :: ![PackageId], -- ^ Dependent packages, used to
1076 -- generate #includes for C code gen
1077 cg_hpc_info :: !HpcInfo, -- ^ Program coverage tick box information
1078 cg_modBreaks :: !ModBreaks -- ^ Module breakpoints
1081 -----------------------------------
1082 -- | Foreign export stubs
1083 data ForeignStubs = NoStubs -- ^ We don't have any stubs
1087 -- ^ There are some stubs. Parameters:
1089 -- 1) Header file prototypes for
1090 -- "foreign exported" functions
1092 -- 2) C stubs to use when calling
1093 -- "foreign exported" functions
1097 emptyModIface :: Module -> ModIface
1099 = ModIface { mi_module = mod,
1100 mi_iface_hash = fingerprint0,
1101 mi_mod_hash = fingerprint0,
1105 mi_deps = noDependencies,
1108 mi_exp_hash = fingerprint0,
1110 mi_warns = NoWarnings,
1116 mi_globals = Nothing,
1117 mi_orphan_hash = fingerprint0,
1118 mi_vect_info = noIfaceVectInfo,
1119 mi_warn_fn = emptyIfaceWarnCache,
1120 mi_fix_fn = emptyIfaceFixCache,
1121 mi_hash_fn = emptyIfaceHashCache,
1127 %************************************************************************
1129 \subsection{The interactive context}
1131 %************************************************************************
1134 -- | Interactive context, recording information relevant to GHCi
1135 data InteractiveContext
1136 = InteractiveContext {
1137 ic_toplev_scope :: [Module], -- ^ The context includes the "top-level" scope of
1140 ic_exports :: [(Module, Maybe (ImportDecl RdrName))], -- ^ The context includes just the exported parts of these
1143 ic_rn_gbl_env :: GlobalRdrEnv, -- ^ The contexts' cached 'GlobalRdrEnv', built from
1144 -- 'ic_toplev_scope' and 'ic_exports'
1146 ic_tmp_ids :: [Id], -- ^ Names bound during interaction with the user.
1147 -- Later Ids shadow earlier ones with the same OccName.
1149 ic_tyvars :: TyVarSet -- ^ Skolem type variables free in
1150 -- 'ic_tmp_ids'. These arise at
1151 -- breakpoints in a polymorphic
1152 -- context, where we have only partial
1153 -- type information.
1156 , ic_resume :: [Resume] -- ^ The stack of breakpoint contexts
1159 , ic_cwd :: Maybe FilePath -- virtual CWD of the program
1163 emptyInteractiveContext :: InteractiveContext
1164 emptyInteractiveContext
1165 = InteractiveContext { ic_toplev_scope = [],
1167 ic_rn_gbl_env = emptyGlobalRdrEnv,
1169 ic_tyvars = emptyVarSet
1176 icPrintUnqual :: DynFlags -> InteractiveContext -> PrintUnqualified
1177 icPrintUnqual dflags ictxt = mkPrintUnqualified dflags (ic_rn_gbl_env ictxt)
1180 extendInteractiveContext
1181 :: InteractiveContext
1184 -> InteractiveContext
1185 extendInteractiveContext ictxt ids tyvars
1186 = ictxt { ic_tmp_ids = snub((ic_tmp_ids ictxt \\ ids) ++ ids),
1187 -- NB. must be this way around, because we want
1188 -- new ids to shadow existing bindings.
1189 ic_tyvars = ic_tyvars ictxt `unionVarSet` tyvars }
1190 where snub = map head . group . sort
1192 substInteractiveContext :: InteractiveContext -> TvSubst -> InteractiveContext
1193 substInteractiveContext ictxt subst | isEmptyTvSubst subst = ictxt
1194 substInteractiveContext ictxt@InteractiveContext{ic_tmp_ids=ids} subst =
1195 let ids' = map (\id -> id `setIdType` substTy subst (idType id)) ids
1196 subst_dom= varEnvKeys$ getTvSubstEnv subst
1197 subst_ran= varEnvElts$ getTvSubstEnv subst
1198 new_tvs = [ tv | Just tv <- map getTyVar_maybe subst_ran]
1199 ic_tyvars'= (`delVarSetListByKey` subst_dom)
1200 . (`extendVarSetList` new_tvs)
1202 in ictxt { ic_tmp_ids = ids'
1203 , ic_tyvars = ic_tyvars' }
1205 where delVarSetListByKey = foldl' delVarSetByKey
1208 %************************************************************************
1210 Building a PrintUnqualified
1212 %************************************************************************
1214 Note [Printing original names]
1215 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1216 Deciding how to print names is pretty tricky. We are given a name
1217 P:M.T, where P is the package name, M is the defining module, and T is
1218 the occurrence name, and we have to decide in which form to display
1219 the name given a GlobalRdrEnv describing the current scope.
1221 Ideally we want to display the name in the form in which it is in
1222 scope. However, the name might not be in scope at all, and that's
1223 where it gets tricky. Here are the cases:
1225 1. T uniquely maps to P:M.T ---> "T" NameUnqual
1226 2. There is an X for which X.T
1227 uniquely maps to P:M.T ---> "X.T" NameQual X
1228 3. There is no binding for "M.T" ---> "M.T" NameNotInScope1
1229 4. Otherwise ---> "P:M.T" NameNotInScope2
1231 (3) and (4) apply when the entity P:M.T is not in the GlobalRdrEnv at
1232 all. In these cases we still want to refer to the name as "M.T", *but*
1233 "M.T" might mean something else in the current scope (e.g. if there's
1234 an "import X as M"), so to avoid confusion we avoid using "M.T" if
1235 there's already a binding for it. Instead we write P:M.T.
1237 There's one further subtlety: in case (3), what if there are two
1238 things around, P1:M.T and P2:M.T? Then we don't want to print both of
1239 them as M.T! However only one of the modules P1:M and P2:M can be
1240 exposed (say P2), so we use M.T for that, and P1:M.T for the other one.
1241 This is handled by the qual_mod component of PrintUnqualified, inside
1242 the (ppr mod) of case (3), in Name.pprModulePrefix
1245 -- | Creates some functions that work out the best ways to format
1246 -- names for the user according to a set of heuristics
1247 mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified
1248 mkPrintUnqualified dflags env = (qual_name, qual_mod)
1250 qual_name mod occ -- The (mod,occ) pair is the original name of the thing
1251 | [gre] <- unqual_gres, right_name gre = NameUnqual
1252 -- If there's a unique entity that's in scope unqualified with 'occ'
1253 -- AND that entity is the right one, then we can use the unqualified name
1255 | [gre] <- qual_gres = NameQual (get_qual_mod (gre_prov gre))
1258 if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env)
1259 then NameNotInScope1
1260 else NameNotInScope2
1262 | otherwise = panic "mkPrintUnqualified"
1264 right_name gre = nameModule_maybe (gre_name gre) == Just mod
1266 unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
1267 qual_gres = filter right_name (lookupGlobalRdrEnv env occ)
1269 get_qual_mod LocalDef = moduleName mod
1270 get_qual_mod (Imported is) = ASSERT( not (null is) ) is_as (is_decl (head is))
1272 -- we can mention a module P:M without the P: qualifier iff
1273 -- "import M" would resolve unambiguously to P:M. (if P is the
1274 -- current package we can just assume it is unqualified).
1277 | modulePackageId mod == thisPackage dflags = False
1279 | [pkgconfig] <- [pkg | (pkg,exposed_module) <- lookup,
1280 exposed pkg && exposed_module],
1281 packageConfigId pkgconfig == modulePackageId mod
1282 -- this says: we are given a module P:M, is there just one exposed package
1283 -- that exposes a module M, and is it package P?
1287 where lookup = lookupModuleInAllPackages dflags (moduleName mod)
1291 %************************************************************************
1295 %************************************************************************
1298 -- | Determine the 'TyThing's brought into scope by another 'TyThing'
1299 -- /other/ than itself. For example, Id's don't have any implicit TyThings
1300 -- as they just bring themselves into scope, but classes bring their
1301 -- dictionary datatype, type constructor and some selector functions into
1302 -- scope, just for a start!
1304 -- N.B. the set of TyThings returned here *must* match the set of
1305 -- names returned by LoadIface.ifaceDeclSubBndrs, in the sense that
1306 -- TyThing.getOccName should define a bijection between the two lists.
1307 -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
1308 -- The order of the list does not matter.
1309 implicitTyThings :: TyThing -> [TyThing]
1311 -- For data and newtype declarations:
1312 implicitTyThings (ATyCon tc)
1313 = -- fields (names of selectors)
1314 -- (possibly) implicit coercion and family coercion
1315 -- depending on whether it's a newtype or a family instance or both
1316 implicitCoTyCon tc ++
1317 -- for each data constructor in order,
1318 -- the contructor, worker, and (possibly) wrapper
1319 concatMap (extras_plus . ADataCon) (tyConDataCons tc)
1321 implicitTyThings (AClass cl)
1322 = -- dictionary datatype:
1325 -- [recursive call:]
1326 -- (possibly) newtype coercion; definitely no family coercion here
1329 -- (no wrapper by invariant)
1330 extras_plus (ATyCon (classTyCon cl)) ++
1332 -- No extras_plus (recursive call) for the classATs, because they
1333 -- are only the family decls; they have no implicit things
1334 map ATyCon (classATs cl) ++
1335 -- superclass and operation selectors
1336 map AnId (classSelIds cl)
1338 implicitTyThings (ADataCon dc) =
1339 -- For data cons add the worker and (possibly) wrapper
1340 map AnId (dataConImplicitIds dc)
1342 implicitTyThings (AnId _) = []
1344 -- add a thing and recursive call
1345 extras_plus :: TyThing -> [TyThing]
1346 extras_plus thing = thing : implicitTyThings thing
1348 -- For newtypes and indexed data types (and both),
1349 -- add the implicit coercion tycon
1350 implicitCoTyCon :: TyCon -> [TyThing]
1352 = map ATyCon . catMaybes $ [-- Just if newtype, Nothing if not
1353 newTyConCo_maybe tc,
1354 -- Just if family instance, Nothing if not
1355 tyConFamilyCoercion_maybe tc]
1357 -- sortByOcc = sortBy (\ x -> \ y -> getOccName x < getOccName y)
1360 -- | Returns @True@ if there should be no interface-file declaration
1361 -- for this thing on its own: either it is built-in, or it is part
1362 -- of some other declaration, or it is generated implicitly by some
1363 -- other declaration.
1364 isImplicitTyThing :: TyThing -> Bool
1365 isImplicitTyThing (ADataCon _) = True
1366 isImplicitTyThing (AnId id) = isImplicitId id
1367 isImplicitTyThing (AClass _) = False
1368 isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc
1370 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
1371 extendTypeEnvWithIds env ids
1372 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
1375 %************************************************************************
1379 %************************************************************************
1382 -- | A map from 'Name's to 'TyThing's, constructed by typechecking
1383 -- local declarations or interface files
1384 type TypeEnv = NameEnv TyThing
1386 emptyTypeEnv :: TypeEnv
1387 typeEnvElts :: TypeEnv -> [TyThing]
1388 typeEnvClasses :: TypeEnv -> [Class]
1389 typeEnvTyCons :: TypeEnv -> [TyCon]
1390 typeEnvIds :: TypeEnv -> [Id]
1391 typeEnvDataCons :: TypeEnv -> [DataCon]
1392 lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
1394 emptyTypeEnv = emptyNameEnv
1395 typeEnvElts env = nameEnvElts env
1396 typeEnvClasses env = [cl | AClass cl <- typeEnvElts env]
1397 typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
1398 typeEnvIds env = [id | AnId id <- typeEnvElts env]
1399 typeEnvDataCons env = [dc | ADataCon dc <- typeEnvElts env]
1401 mkTypeEnv :: [TyThing] -> TypeEnv
1402 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
1404 lookupTypeEnv = lookupNameEnv
1406 -- Extend the type environment
1407 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
1408 extendTypeEnv env thing = extendNameEnv env (getName thing) thing
1410 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
1411 extendTypeEnvList env things = foldl extendTypeEnv env things
1415 -- | Find the 'TyThing' for the given 'Name' by using all the resources
1416 -- at our disposal: the compiled modules in the 'HomePackageTable' and the
1417 -- compiled modules in other packages that live in 'PackageTypeEnv'. Note
1418 -- that this does NOT look up the 'TyThing' in the module being compiled: you
1419 -- have to do that yourself, if desired
1420 lookupType :: DynFlags
1426 lookupType dflags hpt pte name
1427 -- in one-shot, we don't use the HPT
1428 | not (isOneShot (ghcMode dflags)) && modulePackageId mod == this_pkg
1429 = do hm <- lookupUFM hpt (moduleName mod) -- Maybe monad
1430 lookupNameEnv (md_types (hm_details hm)) name
1432 = lookupNameEnv pte name
1433 where mod = ASSERT( isExternalName name ) nameModule name
1434 this_pkg = thisPackage dflags
1436 -- | As 'lookupType', but with a marginally easier-to-use interface
1437 -- if you have a 'HscEnv'
1438 lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing)
1439 lookupTypeHscEnv hsc_env name = do
1440 eps <- readIORef (hsc_EPS hsc_env)
1441 return $! lookupType dflags hpt (eps_PTE eps) name
1443 dflags = hsc_dflags hsc_env
1444 hpt = hsc_HPT hsc_env
1448 -- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise
1449 tyThingTyCon :: TyThing -> TyCon
1450 tyThingTyCon (ATyCon tc) = tc
1451 tyThingTyCon other = pprPanic "tyThingTyCon" (pprTyThing other)
1453 -- | Get the 'Class' from a 'TyThing' if it is a class thing. Panics otherwise
1454 tyThingClass :: TyThing -> Class
1455 tyThingClass (AClass cls) = cls
1456 tyThingClass other = pprPanic "tyThingClass" (pprTyThing other)
1458 -- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise
1459 tyThingDataCon :: TyThing -> DataCon
1460 tyThingDataCon (ADataCon dc) = dc
1461 tyThingDataCon other = pprPanic "tyThingDataCon" (pprTyThing other)
1463 -- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise
1464 tyThingId :: TyThing -> Id
1465 tyThingId (AnId id) = id
1466 tyThingId (ADataCon dc) = dataConWrapId dc
1467 tyThingId other = pprPanic "tyThingId" (pprTyThing other)
1470 %************************************************************************
1472 \subsection{MonadThings and friends}
1474 %************************************************************************
1477 -- | Class that abstracts out the common ability of the monads in GHC
1478 -- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides
1479 -- a number of related convenience functions for accessing particular
1480 -- kinds of 'TyThing'
1481 class Monad m => MonadThings m where
1482 lookupThing :: Name -> m TyThing
1484 lookupId :: Name -> m Id
1485 lookupId = liftM tyThingId . lookupThing
1487 lookupDataCon :: Name -> m DataCon
1488 lookupDataCon = liftM tyThingDataCon . lookupThing
1490 lookupTyCon :: Name -> m TyCon
1491 lookupTyCon = liftM tyThingTyCon . lookupThing
1493 lookupClass :: Name -> m Class
1494 lookupClass = liftM tyThingClass . lookupThing
1498 -- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
1499 mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
1500 -> (OccName -> Maybe (OccName, Fingerprint))
1501 mkIfaceHashCache pairs
1502 = \occ -> lookupOccEnv env occ
1504 env = foldr add_decl emptyOccEnv pairs
1505 add_decl (v,d) env0 = foldr add_imp env1 (ifaceDeclSubBndrs d)
1507 decl_name = ifName d
1508 env1 = extendOccEnv env0 decl_name (decl_name, v)
1509 add_imp bndr env = extendOccEnv env bndr (decl_name, v)
1511 emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
1512 emptyIfaceHashCache _occ = Nothing
1515 %************************************************************************
1517 \subsection{Auxiliary types}
1519 %************************************************************************
1521 These types are defined here because they are mentioned in ModDetails,
1522 but they are mostly elaborated elsewhere
1525 ------------------ Warnings -------------------------
1526 -- | Warning information for a module
1528 = NoWarnings -- ^ Nothing deprecated
1529 | WarnAll WarningTxt -- ^ Whole module deprecated
1530 | WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated
1532 -- Only an OccName is needed because
1533 -- (1) a deprecation always applies to a binding
1534 -- defined in the module in which the deprecation appears.
1535 -- (2) deprecations are only reported outside the defining module.
1536 -- this is important because, otherwise, if we saw something like
1538 -- {-# DEPRECATED f "" #-}
1541 -- g = let f = undefined in f
1543 -- we'd need more information than an OccName to know to say something
1544 -- about the use of f in h but not the use of the locally bound f in g
1546 -- however, because we only report about deprecations from the outside,
1547 -- and a module can only export one value called f,
1548 -- an OccName suffices.
1550 -- this is in contrast with fixity declarations, where we need to map
1551 -- a Name to its fixity declaration.
1554 -- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface'
1555 mkIfaceWarnCache :: Warnings -> Name -> Maybe WarningTxt
1556 mkIfaceWarnCache NoWarnings = \_ -> Nothing
1557 mkIfaceWarnCache (WarnAll t) = \_ -> Just t
1558 mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
1560 emptyIfaceWarnCache :: Name -> Maybe WarningTxt
1561 emptyIfaceWarnCache _ = Nothing
1563 plusWarns :: Warnings -> Warnings -> Warnings
1564 plusWarns d NoWarnings = d
1565 plusWarns NoWarnings d = d
1566 plusWarns _ (WarnAll t) = WarnAll t
1567 plusWarns (WarnAll t) _ = WarnAll t
1568 plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2)
1571 -- | A collection of 'AvailInfo' - several things that are \"available\"
1572 type Avails = [AvailInfo]
1573 -- | 'Name'd things that are available
1574 type AvailInfo = GenAvailInfo Name
1575 -- | 'RdrName'd things that are available
1576 type RdrAvailInfo = GenAvailInfo OccName
1578 -- | Records what things are "available", i.e. in scope
1579 data GenAvailInfo name = Avail name -- ^ An ordinary identifier in scope
1581 [name] -- ^ A type or class in scope. Parameters:
1583 -- 1) The name of the type or class
1585 -- 2) The available pieces of type or class.
1586 -- NB: If the type or class is itself
1587 -- to be in scope, it must be in this list.
1588 -- Thus, typically: @AvailTC Eq [Eq, ==, \/=]@
1590 -- Equality used when deciding if the interface has changed
1592 -- | The original names declared of a certain module that are exported
1593 type IfaceExport = (Module, [GenAvailInfo OccName])
1595 availsToNameSet :: [AvailInfo] -> NameSet
1596 availsToNameSet avails = foldr add emptyNameSet avails
1597 where add avail set = addListToNameSet set (availNames avail)
1599 availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo
1600 availsToNameEnv avails = foldr add emptyNameEnv avails
1601 where add avail env = extendNameEnvList env
1602 (zip (availNames avail) (repeat avail))
1604 -- | Just the main name made available, i.e. not the available pieces
1605 -- of type or class brought into scope by the 'GenAvailInfo'
1606 availName :: GenAvailInfo name -> name
1607 availName (Avail n) = n
1608 availName (AvailTC n _) = n
1610 -- | All names made available by the availability information
1611 availNames :: GenAvailInfo name -> [name]
1612 availNames (Avail n) = [n]
1613 availNames (AvailTC _ ns) = ns
1615 instance Outputable n => Outputable (GenAvailInfo n) where
1618 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
1619 pprAvail (Avail n) = ppr n
1620 pprAvail (AvailTC n ns) = ppr n <> braces (hsep (punctuate comma (map ppr ns)))
1624 -- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface'
1625 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
1626 mkIfaceFixCache pairs
1627 = \n -> lookupOccEnv env n `orElse` defaultFixity
1629 env = mkOccEnv pairs
1631 emptyIfaceFixCache :: OccName -> Fixity
1632 emptyIfaceFixCache _ = defaultFixity
1634 -- | Fixity environment mapping names to their fixities
1635 type FixityEnv = NameEnv FixItem
1637 -- | Fixity information for an 'Name'. We keep the OccName in the range
1638 -- so that we can generate an interface from it
1639 data FixItem = FixItem OccName Fixity
1641 instance Outputable FixItem where
1642 ppr (FixItem occ fix) = ppr fix <+> ppr occ
1644 emptyFixityEnv :: FixityEnv
1645 emptyFixityEnv = emptyNameEnv
1647 lookupFixity :: FixityEnv -> Name -> Fixity
1648 lookupFixity env n = case lookupNameEnv env n of
1649 Just (FixItem _ fix) -> fix
1650 Nothing -> defaultFixity
1654 %************************************************************************
1656 \subsection{WhatsImported}
1658 %************************************************************************
1661 -- | Records whether a module has orphans. An \"orphan\" is one of:
1663 -- * An instance declaration in a module other than the definition
1664 -- module for one of the type constructors or classes in the instance head
1666 -- * A transformation rule in a module other than the one defining
1667 -- the function in the head of the rule
1668 type WhetherHasOrphans = Bool
1670 -- | Does this module define family instances?
1671 type WhetherHasFamInst = Bool
1673 -- | Did this module originate from a *-boot file?
1674 type IsBootInterface = Bool
1676 -- | Dependency information about modules and packages below this one
1677 -- in the import hierarchy.
1679 -- Invariant: the dependencies of a module @M@ never includes @M@.
1681 -- Invariant: none of the lists contain duplicates.
1683 = Deps { dep_mods :: [(ModuleName, IsBootInterface)]
1684 -- ^ Home-package module dependencies
1685 , dep_pkgs :: [PackageId]
1686 -- ^ External package dependencies
1687 , dep_orphs :: [Module]
1688 -- ^ Orphan modules (whether home or external pkg),
1689 -- *not* including family instance orphans as they
1690 -- are anyway included in 'dep_finsts'
1691 , dep_finsts :: [Module]
1692 -- ^ Modules that contain family instances (whether the
1693 -- instances are from the home or an external package)
1696 -- Equality used only for old/new comparison in MkIface.addVersionInfo
1698 -- See 'TcRnTypes.ImportAvails' for details on dependencies.
1700 noDependencies :: Dependencies
1701 noDependencies = Deps [] [] [] []
1703 -- | Records modules that we depend on by making a direct import from
1705 = UsagePackageModule {
1707 -- ^ External package module depended on
1708 usg_mod_hash :: Fingerprint
1709 } -- ^ Module from another package
1711 usg_mod_name :: ModuleName,
1712 -- ^ Name of the module
1713 usg_mod_hash :: Fingerprint,
1714 -- ^ Cached module fingerprint
1715 usg_entities :: [(OccName,Fingerprint)],
1716 -- ^ Entities we depend on, sorted by occurrence name and fingerprinted.
1717 -- NB: usages are for parent names only, e.g. type constructors
1718 -- but not the associated data constructors.
1719 usg_exports :: Maybe Fingerprint
1720 -- ^ Fingerprint for the export list we used to depend on this module,
1721 -- if we depend on the export list
1722 } -- ^ Module from the current package
1724 -- The export list field is (Just v) if we depend on the export list:
1725 -- i.e. we imported the module directly, whether or not we
1726 -- enumerated the things we imported, or just imported
1728 -- We need to recompile if M's exports change, because
1729 -- if the import was import M, we might now have a name clash
1730 -- in the importing module.
1731 -- if the import was import M(x) M might no longer export x
1732 -- The only way we don't depend on the export list is if we have
1734 -- And of course, for modules that aren't imported directly we don't
1735 -- depend on their export lists
1739 %************************************************************************
1741 The External Package State
1743 %************************************************************************
1746 type PackageTypeEnv = TypeEnv
1747 type PackageRuleBase = RuleBase
1748 type PackageInstEnv = InstEnv
1749 type PackageFamInstEnv = FamInstEnv
1750 type PackageVectInfo = VectInfo
1751 type PackageAnnEnv = AnnEnv
1753 -- | Information about other packages that we have slurped in by reading
1754 -- their interface files
1755 data ExternalPackageState
1757 eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
1758 -- ^ In OneShot mode (only), home-package modules
1759 -- accumulate in the external package state, and are
1760 -- sucked in lazily. For these home-pkg modules
1761 -- (only) we need to record which are boot modules.
1762 -- We set this field after loading all the
1763 -- explicitly-imported interfaces, but before doing
1766 -- The 'ModuleName' part is not necessary, but it's useful for
1767 -- debug prints, and it's convenient because this field comes
1768 -- direct from 'TcRnTypes.imp_dep_mods'
1770 eps_PIT :: !PackageIfaceTable,
1771 -- ^ The 'ModIface's for modules in external packages
1772 -- whose interfaces we have opened.
1773 -- The declarations in these interface files are held in the
1774 -- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules'
1775 -- fields of this record, not in the 'mi_decls' fields of the
1776 -- interface we have sucked in.
1778 -- What /is/ in the PIT is:
1782 -- * Fingerprint info
1788 -- * Deprecations and warnings
1790 eps_PTE :: !PackageTypeEnv,
1791 -- ^ Result of typechecking all the external package
1792 -- interface files we have sucked in. The domain of
1793 -- the mapping is external-package modules
1795 eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated
1796 -- from all the external-package modules
1797 eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated
1798 -- from all the external-package modules
1799 eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated
1800 -- from all the external-package modules
1801 eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated
1802 -- from all the external-package modules
1803 eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated
1804 -- from all the external-package modules
1806 eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external
1807 -- packages, keyed off the module that declared them
1809 eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages
1812 -- | Accumulated statistics about what we are putting into the 'ExternalPackageState'.
1813 -- \"In\" means stuff that is just /read/ from interface files,
1814 -- \"Out\" means actually sucked in and type-checked
1815 data EpsStats = EpsStats { n_ifaces_in
1816 , n_decls_in, n_decls_out
1817 , n_rules_in, n_rules_out
1818 , n_insts_in, n_insts_out :: !Int }
1820 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
1821 -- ^ Add stats for one newly-read interface
1822 addEpsInStats stats n_decls n_insts n_rules
1823 = stats { n_ifaces_in = n_ifaces_in stats + 1
1824 , n_decls_in = n_decls_in stats + n_decls
1825 , n_insts_in = n_insts_in stats + n_insts
1826 , n_rules_in = n_rules_in stats + n_rules }
1829 Names in a NameCache are always stored as a Global, and have the SrcLoc
1830 of their binding locations.
1832 Actually that's not quite right. When we first encounter the original
1833 name, we might not be at its binding site (e.g. we are reading an
1834 interface file); so we give it 'noSrcLoc' then. Later, when we find
1835 its binding site, we fix it up.
1838 -- | The NameCache makes sure that there is just one Unique assigned for
1839 -- each original name; i.e. (module-name, occ-name) pair and provides
1840 -- something of a lookup mechanism for those names.
1842 = NameCache { nsUniqs :: UniqSupply,
1843 -- ^ Supply of uniques
1844 nsNames :: OrigNameCache,
1845 -- ^ Ensures that one original name gets one unique
1846 nsIPs :: OrigIParamCache
1847 -- ^ Ensures that one implicit parameter name gets one unique
1850 -- | Per-module cache of original 'OccName's given 'Name's
1851 type OrigNameCache = ModuleEnv (OccEnv Name)
1853 -- | Module-local cache of implicit parameter 'OccName's given 'Name's
1854 type OrigIParamCache = FiniteMap (IPName OccName) (IPName Name)
1859 %************************************************************************
1861 The module graph and ModSummary type
1862 A ModSummary is a node in the compilation manager's
1863 dependency graph, and it's also passed to hscMain
1865 %************************************************************************
1868 -- | A ModuleGraph contains all the nodes from the home package (only).
1869 -- There will be a node for each source module, plus a node for each hi-boot
1872 -- The graph is not necessarily stored in topologically-sorted order. Use
1873 -- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this.
1874 type ModuleGraph = [ModSummary]
1876 emptyMG :: ModuleGraph
1879 -- | A single node in a 'ModuleGraph. The nodes of the module graph are one of:
1881 -- * A regular Haskell source module
1883 -- * A hi-boot source module
1885 -- * An external-core source module
1888 ms_mod :: Module, -- ^ Identity of the module
1889 ms_hsc_src :: HscSource, -- ^ The module source either plain Haskell, hs-boot or external core
1890 ms_location :: ModLocation, -- ^ Location of the various files belonging to the module
1891 ms_hs_date :: ClockTime, -- ^ Timestamp of source file
1892 ms_obj_date :: Maybe ClockTime, -- ^ Timestamp of object, if we have one
1893 ms_srcimps :: [Located (ImportDecl RdrName)], -- ^ Source imports of the module
1894 ms_imps :: [Located (ImportDecl RdrName)], -- ^ Non-source imports of the module
1895 ms_hspp_file :: FilePath, -- ^ Filename of preprocessed source file
1896 ms_hspp_opts :: DynFlags, -- ^ Cached flags from @OPTIONS@, @INCLUDE@
1897 -- and @LANGUAGE@ pragmas in the modules source code
1898 ms_hspp_buf :: Maybe StringBuffer -- ^ The actual preprocessed source, if we have it
1901 ms_mod_name :: ModSummary -> ModuleName
1902 ms_mod_name = moduleName . ms_mod
1904 -- The ModLocation contains both the original source filename and the
1905 -- filename of the cleaned-up source file after all preprocessing has been
1906 -- done. The point is that the summariser will have to cpp/unlit/whatever
1907 -- all files anyway, and there's no point in doing this twice -- just
1908 -- park the result in a temp file, put the name of it in the location,
1909 -- and let @compile@ read from that file on the way back up.
1911 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
1912 -- the ms_hs_date and imports can, of course, change
1914 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
1915 msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
1916 msHiFilePath ms = ml_hi_file (ms_location ms)
1917 msObjFilePath ms = ml_obj_file (ms_location ms)
1919 -- | Did this 'ModSummary' originate from a hs-boot file?
1920 isBootSummary :: ModSummary -> Bool
1921 isBootSummary ms = isHsBoot (ms_hsc_src ms)
1923 instance Outputable ModSummary where
1925 = sep [text "ModSummary {",
1926 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1927 text "ms_mod =" <+> ppr (ms_mod ms)
1928 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
1929 text "ms_imps =" <+> ppr (ms_imps ms),
1930 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1934 showModMsg :: HscTarget -> Bool -> ModSummary -> String
1935 showModMsg target recomp mod_summary
1937 hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
1938 char '(', text (normalise $ msHsFilePath mod_summary) <> comma,
1940 HscInterpreted | recomp
1941 -> text "interpreted"
1942 HscNothing -> text "nothing"
1943 _ -> text (normalise $ msObjFilePath mod_summary),
1946 mod = moduleName (ms_mod mod_summary)
1947 mod_str = showSDoc (ppr mod) ++ hscSourceString (ms_hsc_src mod_summary)
1951 %************************************************************************
1953 \subsection{Hpc Support}
1955 %************************************************************************
1958 -- | Information about a modules use of Haskell Program Coverage
1961 { hpcInfoTickCount :: Int
1962 , hpcInfoHash :: Int
1965 { hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*?
1968 -- | This is used to signal if one of my imports used HPC instrumentation
1969 -- even if there is no module-local HPC usage
1970 type AnyHpcUsage = Bool
1972 emptyHpcInfo :: AnyHpcUsage -> HpcInfo
1973 emptyHpcInfo = NoHpcInfo
1975 -- | Find out if HPC is used by this module or any of the modules
1977 isHpcUsed :: HpcInfo -> AnyHpcUsage
1978 isHpcUsed (HpcInfo {}) = True
1979 isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
1982 %************************************************************************
1984 \subsection{Vectorisation Support}
1986 %************************************************************************
1988 The following information is generated and consumed by the vectorisation
1989 subsystem. It communicates the vectorisation status of declarations from one
1992 Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
1993 below? We need to know `f' when converting to IfaceVectInfo. However, during
1994 vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
1995 on just the OccName easily in a Core pass.
1998 -- | Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'.
2001 vectInfoVar :: VarEnv (Var , Var ), -- ^ @(f, f_v)@ keyed on @f@
2002 vectInfoTyCon :: NameEnv (TyCon , TyCon), -- ^ @(T, T_v)@ keyed on @T@
2003 vectInfoDataCon :: NameEnv (DataCon, DataCon), -- ^ @(C, C_v)@ keyed on @C@
2004 vectInfoPADFun :: NameEnv (TyCon , Var), -- ^ @(T_v, paT)@ keyed on @T_v@
2005 vectInfoIso :: NameEnv (TyCon , Var) -- ^ @(T, isoT)@ keyed on @T@
2008 -- | Vectorisation information for 'ModIface': a slightly less low-level view
2011 ifaceVectInfoVar :: [Name],
2012 -- ^ All variables in here have a vectorised variant
2013 ifaceVectInfoTyCon :: [Name],
2014 -- ^ All 'TyCon's in here have a vectorised variant;
2015 -- the name of the vectorised variant and those of its
2016 -- data constructors are determined by 'OccName.mkVectTyConOcc'
2017 -- and 'OccName.mkVectDataConOcc'; the names of
2018 -- the isomorphisms are determined by 'OccName.mkVectIsoOcc'
2019 ifaceVectInfoTyConReuse :: [Name]
2020 -- ^ The vectorised form of all the 'TyCon's in here coincides with
2021 -- the unconverted form; the name of the isomorphisms is determined
2022 -- by 'OccName.mkVectIsoOcc'
2025 noVectInfo :: VectInfo
2026 noVectInfo = VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyNameEnv emptyNameEnv
2028 plusVectInfo :: VectInfo -> VectInfo -> VectInfo
2029 plusVectInfo vi1 vi2 =
2030 VectInfo (vectInfoVar vi1 `plusVarEnv` vectInfoVar vi2)
2031 (vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2)
2032 (vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
2033 (vectInfoPADFun vi1 `plusNameEnv` vectInfoPADFun vi2)
2034 (vectInfoIso vi1 `plusNameEnv` vectInfoIso vi2)
2036 concatVectInfo :: [VectInfo] -> VectInfo
2037 concatVectInfo = foldr plusVectInfo noVectInfo
2039 noIfaceVectInfo :: IfaceVectInfo
2040 noIfaceVectInfo = IfaceVectInfo [] [] []
2043 %************************************************************************
2045 \subsection{Linkable stuff}
2047 %************************************************************************
2049 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
2050 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
2053 -- | Information we can use to dynamically link modules into the compiler
2054 data Linkable = LM {
2055 linkableTime :: ClockTime, -- ^ Time at which this linkable was built
2056 -- (i.e. when the bytecodes were produced,
2057 -- or the mod date on the files)
2058 linkableModule :: Module, -- ^ The linkable module itself
2059 linkableUnlinked :: [Unlinked]
2060 -- ^ Those files and chunks of code we have yet to link.
2062 -- INVARIANT: A valid linkable always has at least one 'Unlinked' item.
2063 -- If this list is empty, the Linkable represents a fake linkable, which
2064 -- is generated in HscNothing mode to avoid recompiling modules.
2066 -- XXX: Do items get removed from this list when they get linked?
2069 isObjectLinkable :: Linkable -> Bool
2070 isObjectLinkable l = not (null unlinked) && all isObject unlinked
2071 where unlinked = linkableUnlinked l
2072 -- A linkable with no Unlinked's is treated as a BCO. We can
2073 -- generate a linkable with no Unlinked's as a result of
2074 -- compiling a module in HscNothing mode, and this choice
2075 -- happens to work well with checkStability in module GHC.
2077 instance Outputable Linkable where
2078 ppr (LM when_made mod unlinkeds)
2079 = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
2080 $$ nest 3 (ppr unlinkeds)
2082 -------------------------------------------
2084 -- | Objects which have yet to be linked by the compiler
2086 = DotO FilePath -- ^ An object file (.o)
2087 | DotA FilePath -- ^ Static archive file (.a)
2088 | DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib)
2089 | BCOs CompiledByteCode ModBreaks -- ^ A byte-code object, lives only in memory
2092 data CompiledByteCode = CompiledByteCodeUndefined
2093 _unused :: CompiledByteCode
2094 _unused = CompiledByteCodeUndefined
2097 instance Outputable Unlinked where
2098 ppr (DotO path) = text "DotO" <+> text path
2099 ppr (DotA path) = text "DotA" <+> text path
2100 ppr (DotDLL path) = text "DotDLL" <+> text path
2102 ppr (BCOs bcos _) = text "BCOs" <+> ppr bcos
2104 ppr (BCOs _ _) = text "No byte code"
2107 -- | Is this an actual file on disk we can link in somehow?
2108 isObject :: Unlinked -> Bool
2109 isObject (DotO _) = True
2110 isObject (DotA _) = True
2111 isObject (DotDLL _) = True
2114 -- | Is this a bytecode linkable with no file on disk?
2115 isInterpretable :: Unlinked -> Bool
2116 isInterpretable = not . isObject
2118 -- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object
2119 nameOfObject :: Unlinked -> FilePath
2120 nameOfObject (DotO fn) = fn
2121 nameOfObject (DotA fn) = fn
2122 nameOfObject (DotDLL fn) = fn
2123 nameOfObject other = pprPanic "nameOfObject" (ppr other)
2125 -- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable
2126 byteCodeOfObject :: Unlinked -> CompiledByteCode
2127 byteCodeOfObject (BCOs bc _) = bc
2128 byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
2131 %************************************************************************
2133 \subsection{Breakpoint Support}
2135 %************************************************************************
2138 -- | Breakpoint index
2139 type BreakIndex = Int
2141 -- | All the information about the breakpoints for a given module
2144 { modBreaks_flags :: BreakArray
2145 -- ^ The array of flags, one per breakpoint,
2146 -- indicating which breakpoints are enabled.
2147 , modBreaks_locs :: !(Array BreakIndex SrcSpan)
2148 -- ^ An array giving the source span of each breakpoint.
2149 , modBreaks_vars :: !(Array BreakIndex [OccName])
2150 -- ^ An array giving the names of the free variables at each breakpoint.
2153 emptyModBreaks :: ModBreaks
2154 emptyModBreaks = ModBreaks
2155 { modBreaks_flags = error "ModBreaks.modBreaks_array not initialised"
2156 -- Todo: can we avoid this?
2157 , modBreaks_locs = array (0,-1) []
2158 , modBreaks_vars = array (0,-1) []