2 % (c) The University of Glasgow, 2006
4 \section[HscTypes]{Types for the per-module compiler}
7 -- | Types for the per-module compiler
11 FinderCache, FindResult(..), ModLocationCache,
12 Target(..), TargetId(..), pprTarget, pprTargetId,
15 -- * Information about modules
16 ModDetails(..), emptyModDetails,
17 ModGuts(..), CgGuts(..), ForeignStubs(..),
20 ModSummary(..), ms_mod_name, showModMsg, isBootSummary,
21 msHsFilePath, msHiFilePath, msObjFilePath,
23 -- * Information about the module being compiled
24 HscSource(..), isHsBoot, hscSourceString, -- Re-exported from DriverPhases
26 -- * State relating to modules in this package
27 HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
28 hptInstances, hptRules, hptVectInfo,
30 -- * State relating to known packages
31 ExternalPackageState(..), EpsStats(..), addEpsInStats,
32 PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
33 lookupIfaceByModule, emptyModIface,
35 PackageInstEnv, PackageRuleBase,
41 -- * Interactive context
42 InteractiveContext(..), emptyInteractiveContext,
43 icPrintUnqual, extendInteractiveContext,
44 substInteractiveContext,
45 mkPrintUnqualified, pprModulePrefix,
48 ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache,
52 FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
54 -- * TyThings and type environments
56 tyThingClass, tyThingTyCon, tyThingDataCon, tyThingId,
57 implicitTyThings, isImplicitTyThing,
59 TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv,
60 extendTypeEnv, extendTypeEnvList, extendTypeEnvWithIds, lookupTypeEnv,
61 typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
67 -- * Information on imports and exports
68 WhetherHasOrphans, IsBootInterface, Usage(..),
69 Dependencies(..), noDependencies,
70 NameCache(..), OrigNameCache, OrigIParamCache,
71 Avails, availsToNameSet, availsToNameEnv, availName, availNames,
72 GenAvailInfo(..), AvailInfo, RdrAvailInfo,
76 Warnings(..), WarningTxt(..), plusWarns,
79 Linkable(..), isObjectLinkable,
80 Unlinked(..), CompiledByteCode,
81 isObject, nameOfObject, isInterpretable, byteCodeOfObject,
84 HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
87 ModBreaks (..), BreakIndex, emptyModBreaks,
89 -- * Vectorisation information
90 VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo,
93 -- * Compilation errors and warnings
94 SourceError, GhcApiError, mkSrcErr, srcErrorMessages, mkApiErr,
95 throwOneError, handleSourceError,
96 handleFlagWarnings, printOrThrowWarnings,
99 #include "HsVersions.h"
102 import ByteCodeAsm ( CompiledByteCode )
103 import {-# SOURCE #-} InteractiveEval ( Resume )
112 import InstEnv ( InstEnv, Instance )
113 import FamInstEnv ( FamInstEnv, FamInst )
114 import Rules ( RuleBase )
115 import CoreSyn ( CoreBind )
122 import Class ( Class, classAllSelIds, classATs, classTyCon )
124 import DataCon ( DataCon, dataConImplicitIds, dataConWrapId )
125 import PrelNames ( gHC_PRIM )
126 import Packages hiding ( Version(..) )
127 import DynFlags ( DynFlags(..), isOneShot, HscTarget (..), dopt,
129 import DriverPhases ( HscSource(..), isHsBoot, hscSourceString, Phase )
130 import BasicTypes ( IPName, defaultFixity, WarningTxt(..) )
131 import OptimizationFuel ( OptFuelState )
133 import CoreSyn ( CoreRule )
134 import Maybes ( orElse, expectJust, catMaybes )
137 import SrcLoc ( SrcSpan, Located(..) )
138 import UniqFM ( lookupUFM, eltsUFM, emptyUFM )
139 import UniqSupply ( UniqSupply )
141 import StringBuffer ( StringBuffer )
144 import Data.Dynamic ( Typeable )
145 import qualified Data.Dynamic as Dyn
149 import System.FilePath
150 import System.Time ( ClockTime )
152 import Data.Array ( Array, array )
154 import Data.Map (Map)
155 import Control.Monad ( mplus, guard, liftM, when )
158 -- -----------------------------------------------------------------------------
161 -- When the compiler (HscMain) discovers errors, it throws an
162 -- exception in the IO monad.
164 mkSrcErr :: ErrorMessages -> SourceError
165 srcErrorMessages :: SourceError -> ErrorMessages
166 mkApiErr :: SDoc -> GhcApiError
168 throwOneError :: MonadIO m => ErrMsg -> m ab
169 throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err
171 -- | A source error is an error that is caused by one or more errors in the
172 -- source code. A 'SourceError' is thrown by many functions in the
173 -- compilation pipeline. Inside GHC these errors are merely printed via
174 -- 'log_action', but API clients may treat them differently, for example,
175 -- insert them into a list box. If you want the default behaviour, use the
178 -- > handleSourceError printExceptionAndWarnings $ do
179 -- > ... api calls that may fail ...
181 -- The 'SourceError's error messages can be accessed via 'srcErrorMessages'.
182 -- This list may be empty if the compiler failed due to @-Werror@
183 -- ('Opt_WarnIsError').
185 -- See 'printExceptionAndWarnings' for more information on what to take care
186 -- of when writing a custom error handler.
187 data SourceError = SourceError ErrorMessages
189 instance Show SourceError where
190 show (SourceError msgs) = unlines . map show . bagToList $ msgs
191 -- ToDo: is there some nicer way to print this?
193 sourceErrorTc :: Dyn.TyCon
194 sourceErrorTc = Dyn.mkTyCon "SourceError"
195 {-# NOINLINE sourceErrorTc #-}
196 instance Typeable SourceError where
197 typeOf _ = Dyn.mkTyConApp sourceErrorTc []
199 instance Exception SourceError
201 mkSrcErr = SourceError
203 -- | Perform the given action and call the exception handler if the action
204 -- throws a 'SourceError'. See 'SourceError' for more information.
205 handleSourceError :: (ExceptionMonad m) =>
206 (SourceError -> m a) -- ^ exception handler
207 -> m a -- ^ action to perform
209 handleSourceError handler act =
210 gcatch act (\(e :: SourceError) -> handler e)
212 srcErrorMessages (SourceError msgs) = msgs
214 -- | XXX: what exactly is an API error?
215 data GhcApiError = GhcApiError SDoc
217 instance Show GhcApiError where
218 show (GhcApiError msg) = showSDoc msg
220 ghcApiErrorTc :: Dyn.TyCon
221 ghcApiErrorTc = Dyn.mkTyCon "GhcApiError"
222 {-# NOINLINE ghcApiErrorTc #-}
223 instance Typeable GhcApiError where
224 typeOf _ = Dyn.mkTyConApp ghcApiErrorTc []
226 instance Exception GhcApiError
228 mkApiErr = GhcApiError
230 -- | Given a bag of warnings, turn them into an exception if
231 -- -Werror is enabled, or print them out otherwise.
232 printOrThrowWarnings :: DynFlags -> Bag WarnMsg -> IO ()
233 printOrThrowWarnings dflags warns
234 | dopt Opt_WarnIsError dflags
235 = when (not (isEmptyBag warns)) $ do
236 throwIO $ mkSrcErr $ warns `snocBag` warnIsErrorMsg
238 = printBagOfWarnings dflags warns
240 handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
241 handleFlagWarnings dflags warns
242 = when (dopt Opt_WarnDeprecatedFlags dflags) $ do
243 -- It would be nicer if warns :: [Located Message], but that
244 -- has circular import problems.
245 let bag = listToBag [ mkPlainWarnMsg loc (text warn)
246 | L loc warn <- warns ]
248 printOrThrowWarnings dflags bag
252 -- | Hscenv is like 'Session', except that some of the fields are immutable.
253 -- An HscEnv is used to compile a single module from plain Haskell source
254 -- code (after preprocessing) to either C, assembly or C--. Things like
255 -- the module graph don't change during a single compilation.
257 -- Historical note: \"hsc\" used to be the name of the compiler binary,
258 -- when there was a separate driver and compiler. To compile a single
259 -- module, the driver would invoke hsc on the source code... so nowadays
260 -- we think of hsc as the layer of the compiler that deals with compiling
264 hsc_dflags :: DynFlags,
265 -- ^ The dynamic flag settings
267 hsc_targets :: [Target],
268 -- ^ The targets (or roots) of the current session
270 hsc_mod_graph :: ModuleGraph,
271 -- ^ The module graph of the current session
273 hsc_IC :: InteractiveContext,
274 -- ^ The context for evaluating interactive statements
276 hsc_HPT :: HomePackageTable,
277 -- ^ The home package table describes already-compiled
278 -- home-package modules, /excluding/ the module we
279 -- are compiling right now.
280 -- (In one-shot mode the current module is the only
281 -- home-package module, so hsc_HPT is empty. All other
282 -- modules count as \"external-package\" modules.
283 -- However, even in GHCi mode, hi-boot interfaces are
284 -- demand-loaded into the external-package table.)
286 -- 'hsc_HPT' is not mutable because we only demand-load
287 -- external packages; the home package is eagerly
288 -- loaded, module by module, by the compilation manager.
290 -- The HPT may contain modules compiled earlier by @--make@
291 -- but not actually below the current module in the dependency
294 -- (This changes a previous invariant: changed Jan 05.)
296 hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
297 -- ^ Information about the currently loaded external packages.
298 -- This is mutable because packages will be demand-loaded during
299 -- a compilation run as required.
301 hsc_NC :: {-# UNPACK #-} !(IORef NameCache),
302 -- ^ As with 'hsc_EPS', this is side-effected by compiling to
303 -- reflect sucking in interface files. They cache the state of
304 -- external interface files, in effect.
306 hsc_FC :: {-# UNPACK #-} !(IORef FinderCache),
307 -- ^ The cached result of performing finding in the file system
308 hsc_MLC :: {-# UNPACK #-} !(IORef ModLocationCache),
309 -- ^ This caches the location of modules, so we don't have to
310 -- search the filesystem multiple times. See also 'hsc_FC'.
312 hsc_OptFuel :: OptFuelState,
313 -- ^ Settings to control the use of \"optimization fuel\":
314 -- by limiting the number of transformations,
315 -- we can use binary search to help find compiler bugs.
317 hsc_type_env_var :: Maybe (Module, IORef TypeEnv)
318 -- ^ Used for one-shot compilation only, to initialise
319 -- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for
320 -- 'TcRunTypes.TcGblEnv'
323 hscEPS :: HscEnv -> IO ExternalPackageState
324 hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
326 -- | A compilation target.
328 -- A target may be supplied with the actual text of the
329 -- module. If so, use this instead of the file contents (this
330 -- is for use in an IDE where the file hasn't been saved by
333 { targetId :: TargetId -- ^ module or filename
334 , targetAllowObjCode :: Bool -- ^ object code allowed?
335 , targetContents :: Maybe (StringBuffer,ClockTime)
336 -- ^ in-memory text buffer?
340 = TargetModule ModuleName
341 -- ^ A module name: search for the file
342 | TargetFile FilePath (Maybe Phase)
343 -- ^ A filename: preprocess & parse it to find the module name.
344 -- If specified, the Phase indicates how to compile this file
345 -- (which phase to start from). Nothing indicates the starting phase
346 -- should be determined from the suffix of the filename.
349 pprTarget :: Target -> SDoc
350 pprTarget (Target id obj _) =
351 (if obj then char '*' else empty) <> pprTargetId id
353 instance Outputable Target where
356 pprTargetId :: TargetId -> SDoc
357 pprTargetId (TargetModule m) = ppr m
358 pprTargetId (TargetFile f _) = text f
360 instance Outputable TargetId where
363 -- | Helps us find information about modules in the home package
364 type HomePackageTable = ModuleNameEnv HomeModInfo
365 -- Domain = modules in the home package that have been fully compiled
366 -- "home" package name cached here for convenience
368 -- | Helps us find information about modules in the imported packages
369 type PackageIfaceTable = ModuleEnv ModIface
370 -- Domain = modules in the imported packages
372 emptyHomePackageTable :: HomePackageTable
373 emptyHomePackageTable = emptyUFM
375 emptyPackageIfaceTable :: PackageIfaceTable
376 emptyPackageIfaceTable = emptyModuleEnv
378 -- | Information about modules in the package being compiled
381 hm_iface :: !ModIface,
382 -- ^ The basic loaded interface file: every loaded module has one of
383 -- these, even if it is imported from another package
384 hm_details :: !ModDetails,
385 -- ^ Extra information that has been created from the 'ModIface' for
386 -- the module, typically during typechecking
387 hm_linkable :: !(Maybe Linkable)
388 -- ^ The actual artifact we would like to link to access things in
391 -- 'hm_linkable' might be Nothing:
393 -- 1. If this is an .hs-boot module
395 -- 2. Temporarily during compilation if we pruned away
396 -- the old linkable because it was out of date.
398 -- After a complete compilation ('GHC.load'), all 'hm_linkable' fields
399 -- in the 'HomePackageTable' will be @Just@.
401 -- When re-linking a module ('HscMain.HscNoRecomp'), we construct the
402 -- 'HomeModInfo' by building a new 'ModDetails' from the old
403 -- 'ModIface' (only).
406 -- | Find the 'ModIface' for a 'Module', searching in both the loaded home
407 -- and external package module information
414 lookupIfaceByModule dflags hpt pit mod
415 | modulePackageId mod == thisPackage dflags
416 = -- The module comes from the home package, so look first
417 -- in the HPT. If it's not from the home package it's wrong to look
418 -- in the HPT, because the HPT is indexed by *ModuleName* not Module
419 fmap hm_iface (lookupUFM hpt (moduleName mod))
420 `mplus` lookupModuleEnv pit mod
422 | otherwise = lookupModuleEnv pit mod -- Look in PIT only
424 -- If the module does come from the home package, why do we look in the PIT as well?
425 -- (a) In OneShot mode, even home-package modules accumulate in the PIT
426 -- (b) Even in Batch (--make) mode, there is *one* case where a home-package
427 -- module is in the PIT, namely GHC.Prim when compiling the base package.
428 -- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
429 -- of its own, but it doesn't seem worth the bother.
434 hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([Instance], [FamInst])
435 -- ^ Find all the instance declarations (of classes and families) that are in
436 -- modules imported by this one, directly or indirectly, and are in the Home
437 -- Package Table. This ensures that we don't see instances from modules @--make@
438 -- compiled before this one, but which are not below this one.
439 hptInstances hsc_env want_this_module
440 = let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do
441 guard (want_this_module (moduleName (mi_module (hm_iface mod_info))))
442 let details = hm_details mod_info
443 return (md_insts details, md_fam_insts details)
444 in (concat insts, concat famInsts)
446 hptVectInfo :: HscEnv -> VectInfo
447 -- ^ Get the combined VectInfo of all modules in the home package table. In
448 -- contrast to instances and rules, we don't care whether the modules are
449 -- \"below\" us in the dependency sense. The VectInfo of those modules not \"below\"
450 -- us does not affect the compilation of the current module.
451 hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details)
453 hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
454 -- ^ Get rules from modules \"below\" this one (in the dependency sense)
455 hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False
458 hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation]
459 -- ^ Get annotations from modules \"below\" this one (in the dependency sense)
460 hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps
461 hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env
463 hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a]
464 hptAllThings extract hsc_env = concatMap extract (eltsUFM (hsc_HPT hsc_env))
466 hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a]
467 -- Get things from modules \"below\" this one (in the dependency sense)
468 -- C.f Inst.hptInstances
469 hptSomeThingsBelowUs extract include_hi_boot hsc_env deps
470 | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
473 hpt = hsc_HPT hsc_env
476 | -- Find each non-hi-boot module below me
477 (mod, is_boot_mod) <- deps
478 , include_hi_boot || not is_boot_mod
480 -- unsavoury: when compiling the base package with --make, we
481 -- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't
482 -- be in the HPT, because we never compile it; it's in the EPT
483 -- instead. ToDo: clean up, and remove this slightly bogus
485 , mod /= moduleName gHC_PRIM
487 -- Look it up in the HPT
488 , let things = case lookupUFM hpt mod of
489 Just info -> extract info
490 Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg []
491 msg = vcat [ptext (sLit "missing module") <+> ppr mod,
492 ptext (sLit "Probable cause: out-of-date interface files")]
493 -- This really shouldn't happen, but see Trac #962
499 %************************************************************************
501 \subsection{Dealing with Annotations}
503 %************************************************************************
506 prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv
507 -- ^ Deal with gathering annotations in from all possible places
508 -- and combining them into a single 'AnnEnv'
509 prepareAnnotations hsc_env mb_guts
510 = do { eps <- hscEPS hsc_env
511 ; let -- Extract annotations from the module being compiled if supplied one
512 mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts
513 -- Extract dependencies of the module if we are supplied one,
514 -- otherwise load annotations from all home package table
515 -- entries regardless of dependency ordering.
516 home_pkg_anns = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts
517 other_pkg_anns = eps_ann_env eps
518 ann_env = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns,
525 %************************************************************************
527 \subsection{The Finder cache}
529 %************************************************************************
532 -- | The 'FinderCache' maps home module names to the result of
533 -- searching for that module. It records the results of searching for
534 -- modules along the search path. On @:load@, we flush the entire
535 -- contents of this cache.
537 -- Although the @FinderCache@ range is 'FindResult' for convenience ,
538 -- in fact it will only ever contain 'Found' or 'NotFound' entries.
540 type FinderCache = ModuleNameEnv FindResult
542 -- | The result of searching for an imported module.
544 = Found ModLocation Module
545 -- ^ The module was found
546 | NoPackage PackageId
547 -- ^ The requested package was not found
548 | FoundMultiple [PackageId]
549 -- ^ _Error_: both in multiple packages
550 | NotFound [FilePath] (Maybe PackageId) [PackageId] [PackageId]
551 -- ^ The module was not found, including either
552 -- * the specified places were searched
553 -- * the package that this module should have been in
554 -- * list of packages in which the module was hidden,
555 -- * list of hidden packages containing this module
556 | NotFoundInPackage PackageId
557 -- ^ The module was not found in this package
559 -- | Cache that remembers where we found a particular module. Contains both
560 -- home modules and package modules. On @:load@, only home modules are
561 -- purged from this cache.
562 type ModLocationCache = ModuleEnv ModLocation
565 %************************************************************************
567 \subsection{Symbol tables and Module details}
569 %************************************************************************
572 -- | A 'ModIface' plus a 'ModDetails' summarises everything we know
573 -- about a compiled module. The 'ModIface' is the stuff *before* linking,
574 -- and can be written out to an interface file. The 'ModDetails is after
575 -- linking and can be completely recovered from just the 'ModIface'.
577 -- When we read an interface file, we also construct a 'ModIface' from it,
578 -- except that we explicitly make the 'mi_decls' and a few other fields empty;
579 -- as when reading we consolidate the declarations etc. into a number of indexed
580 -- maps and environments in the 'ExternalPackageState'.
583 mi_module :: !Module, -- ^ Name of the module we are for
584 mi_iface_hash :: !Fingerprint, -- ^ Hash of the whole interface
585 mi_mod_hash :: !Fingerprint, -- ^ Hash of the ABI only
587 mi_orphan :: !WhetherHasOrphans, -- ^ Whether this module has orphans
588 mi_finsts :: !WhetherHasFamInst, -- ^ Whether this module has family instances
589 mi_boot :: !IsBootInterface, -- ^ Read from an hi-boot file?
591 mi_deps :: Dependencies,
592 -- ^ The dependencies of the module. This is
593 -- consulted for directly-imported modules, but not
594 -- for anything else (hence lazy)
596 mi_usages :: [Usage],
597 -- ^ Usages; kept sorted so that it's easy to decide
598 -- whether to write a new iface file (changing usages
599 -- doesn't affect the hash of this module)
601 -- NOT STRICT! we read this field lazily from the interface file
602 -- It is *only* consulted by the recompilation checker
605 -- Kept sorted by (mod,occ), to make version comparisons easier
606 mi_exports :: ![IfaceExport],
607 -- ^ Records the modules that are the declaration points for things
608 -- exported by this module, and the 'OccName's of those things
610 mi_exp_hash :: !Fingerprint, -- ^ Hash of export list
612 mi_fixities :: [(OccName,Fixity)],
615 -- NOT STRICT! we read this field lazily from the interface file
617 mi_warns :: Warnings,
620 -- NOT STRICT! we read this field lazily from the interface file
622 mi_anns :: [IfaceAnnotation],
625 -- NOT STRICT! we read this field lazily from the interface file
627 -- Type, class and variable declarations
628 -- The hash of an Id changes if its fixity or deprecations change
629 -- (as well as its type of course)
630 -- Ditto data constructors, class operations, except that
631 -- the hash of the parent class/tycon changes
632 mi_decls :: [(Fingerprint,IfaceDecl)], -- ^ Sorted type, variable, class etc. declarations
634 mi_globals :: !(Maybe GlobalRdrEnv),
635 -- ^ Binds all the things defined at the top level in
636 -- the /original source/ code for this module. which
637 -- is NOT the same as mi_exports, nor mi_decls (which
638 -- may contains declarations for things not actually
639 -- defined by the user). Used for GHCi and for inspecting
640 -- the contents of modules via the GHC API only.
642 -- (We need the source file to figure out the
643 -- top-level environment, if we didn't compile this module
644 -- from source then this field contains @Nothing@).
646 -- Strictly speaking this field should live in the
647 -- 'HomeModInfo', but that leads to more plumbing.
649 -- Instance declarations and rules
650 mi_insts :: [IfaceInst], -- ^ Sorted class instance
651 mi_fam_insts :: [IfaceFamInst], -- ^ Sorted family instances
652 mi_rules :: [IfaceRule], -- ^ Sorted rules
653 mi_orphan_hash :: !Fingerprint, -- ^ Hash for orphan rules and
654 -- class and family instances
657 mi_vect_info :: !IfaceVectInfo, -- ^ Vectorisation information
659 -- Cached environments for easy lookup
660 -- These are computed (lazily) from other fields
661 -- and are not put into the interface file
662 mi_warn_fn :: Name -> Maybe WarningTxt, -- ^ Cached lookup for 'mi_warns'
663 mi_fix_fn :: OccName -> Fixity, -- ^ Cached lookup for 'mi_fixities'
664 mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint),
665 -- ^ Cached lookup for 'mi_decls'.
666 -- The @Nothing@ in 'mi_hash_fn' means that the thing
667 -- isn't in decls. It's useful to know that when
668 -- seeing if we are up to date wrt. the old interface.
669 -- The 'OccName' is the parent of the name, if it has one.
670 mi_hpc :: !AnyHpcUsage
671 -- ^ True if this program uses Hpc at any point in the program.
674 -- | The 'ModDetails' is essentially a cache for information in the 'ModIface'
675 -- for home modules only. Information relating to packages will be loaded into
676 -- global environments in 'ExternalPackageState'.
679 -- The next two fields are created by the typechecker
680 md_exports :: [AvailInfo],
681 md_types :: !TypeEnv, -- ^ Local type environment for this particular module
682 md_insts :: ![Instance], -- ^ 'DFunId's for the instances in this module
683 md_fam_insts :: ![FamInst],
684 md_rules :: ![CoreRule], -- ^ Domain may include 'Id's from other modules
685 md_anns :: ![Annotation], -- ^ Annotations present in this module: currently
686 -- they only annotate things also declared in this module
687 md_vect_info :: !VectInfo -- ^ Module vectorisation information
690 emptyModDetails :: ModDetails
691 emptyModDetails = ModDetails { md_types = emptyTypeEnv,
697 md_vect_info = noVectInfo
700 -- | Records the modules directly imported by a module for extracting e.g. usage information
701 type ImportedMods = ModuleEnv [(ModuleName, Bool, SrcSpan)]
702 -- TODO: we are not actually using the codomain of this type at all, so it can be
703 -- replaced with ModuleEnv ()
705 -- | A ModGuts is carried through the compiler, accumulating stuff as it goes
706 -- There is only one ModGuts at any time, the one for the module
707 -- being compiled right now. Once it is compiled, a 'ModIface' and
708 -- 'ModDetails' are extracted and the ModGuts is dicarded.
711 mg_module :: !Module, -- ^ Module being compiled
712 mg_boot :: IsBootInterface, -- ^ Whether it's an hs-boot module
713 mg_exports :: ![AvailInfo], -- ^ What it exports
714 mg_deps :: !Dependencies, -- ^ What it depends on, directly or
716 mg_dir_imps :: !ImportedMods, -- ^ Directly-imported modules; used to
717 -- generate initialisation code
718 mg_used_names:: !NameSet, -- ^ What the module needed (used in 'MkIface.mkIface')
720 mg_rdr_env :: !GlobalRdrEnv, -- ^ Top-level lexical environment
722 -- These fields all describe the things **declared in this module**
723 mg_fix_env :: !FixityEnv, -- ^ Fixities declared in this module
724 -- TODO: I'm unconvinced this is actually used anywhere
725 mg_types :: !TypeEnv, -- ^ Types declared in this module
726 mg_insts :: ![Instance], -- ^ Class instances declared in this module
727 mg_fam_insts :: ![FamInst], -- ^ Family instances declared in this module
728 mg_rules :: ![CoreRule], -- ^ Before the core pipeline starts, contains
729 -- See Note [Overall plumbing for rules] in Rules.lhs
730 mg_binds :: ![CoreBind], -- ^ Bindings for this module
731 mg_foreign :: !ForeignStubs, -- ^ Foreign exports declared in this module
732 mg_warns :: !Warnings, -- ^ Warnings declared in the module
733 mg_anns :: [Annotation], -- ^ Annotations declared in this module
734 mg_hpc_info :: !HpcInfo, -- ^ Coverage tick boxes in the module
735 mg_modBreaks :: !ModBreaks, -- ^ Breakpoints for the module
736 mg_vect_info :: !VectInfo, -- ^ Pool of vectorised declarations in the module
738 -- The next two fields are unusual, because they give instance
739 -- environments for *all* modules in the home package, including
740 -- this module, rather than for *just* this module.
741 -- Reason: when looking up an instance we don't want to have to
742 -- look at each module in the home package in turn
743 mg_inst_env :: InstEnv,
744 -- ^ Class instance environment from /home-package/ modules (including
745 -- this one); c.f. 'tcg_inst_env'
746 mg_fam_inst_env :: FamInstEnv
747 -- ^ Type-family instance enviroment for /home-package/ modules
748 -- (including this one); c.f. 'tcg_fam_inst_env'
751 -- The ModGuts takes on several slightly different forms:
753 -- After simplification, the following fields change slightly:
754 -- mg_rules Orphan rules only (local ones now attached to binds)
755 -- mg_binds With rules attached
757 -- The ModGuts takes on several slightly different forms:
759 -- After simplification, the following fields change slightly:
760 -- mg_rules Orphan rules only (local ones now attached to binds)
761 -- mg_binds With rules attached
764 ---------------------------------------------------------
765 -- The Tidy pass forks the information about this module:
766 -- * one lot goes to interface file generation (ModIface)
767 -- and later compilations (ModDetails)
768 -- * the other lot goes to code generation (CgGuts)
770 -- | A restricted form of 'ModGuts' for code generation purposes
773 cg_module :: !Module, -- ^ Module being compiled
775 cg_tycons :: [TyCon],
776 -- ^ Algebraic data types (including ones that started
777 -- life as classes); generate constructors and info
778 -- tables. Includes newtypes, just for the benefit of
781 cg_binds :: [CoreBind],
782 -- ^ The tidied main bindings, including
783 -- previously-implicit bindings for record and class
784 -- selectors, and data construtor wrappers. But *not*
785 -- data constructor workers; reason: we we regard them
786 -- as part of the code-gen of tycons
788 cg_dir_imps :: ![Module],
789 -- ^ Directly-imported modules; used to generate
790 -- initialisation code
792 cg_foreign :: !ForeignStubs, -- ^ Foreign export stubs
793 cg_dep_pkgs :: ![PackageId], -- ^ Dependent packages, used to
794 -- generate #includes for C code gen
795 cg_hpc_info :: !HpcInfo, -- ^ Program coverage tick box information
796 cg_modBreaks :: !ModBreaks -- ^ Module breakpoints
799 -----------------------------------
800 -- | Foreign export stubs
801 data ForeignStubs = NoStubs -- ^ We don't have any stubs
805 -- ^ There are some stubs. Parameters:
807 -- 1) Header file prototypes for
808 -- "foreign exported" functions
810 -- 2) C stubs to use when calling
811 -- "foreign exported" functions
815 emptyModIface :: Module -> ModIface
817 = ModIface { mi_module = mod,
818 mi_iface_hash = fingerprint0,
819 mi_mod_hash = fingerprint0,
823 mi_deps = noDependencies,
826 mi_exp_hash = fingerprint0,
828 mi_warns = NoWarnings,
834 mi_globals = Nothing,
835 mi_orphan_hash = fingerprint0,
836 mi_vect_info = noIfaceVectInfo,
837 mi_warn_fn = emptyIfaceWarnCache,
838 mi_fix_fn = emptyIfaceFixCache,
839 mi_hash_fn = emptyIfaceHashCache,
845 %************************************************************************
847 \subsection{The interactive context}
849 %************************************************************************
852 -- | Interactive context, recording information relevant to GHCi
853 data InteractiveContext
854 = InteractiveContext {
855 ic_toplev_scope :: [Module], -- ^ The context includes the "top-level" scope of
858 ic_exports :: [(Module, Maybe (ImportDecl RdrName))], -- ^ The context includes just the exported parts of these
861 ic_rn_gbl_env :: GlobalRdrEnv, -- ^ The contexts' cached 'GlobalRdrEnv', built from
862 -- 'ic_toplev_scope' and 'ic_exports'
864 ic_tmp_ids :: [Id] -- ^ Names bound during interaction with the user.
865 -- Later Ids shadow earlier ones with the same OccName.
868 , ic_resume :: [Resume] -- ^ The stack of breakpoint contexts
871 , ic_cwd :: Maybe FilePath -- virtual CWD of the program
875 emptyInteractiveContext :: InteractiveContext
876 emptyInteractiveContext
877 = InteractiveContext { ic_toplev_scope = [],
879 ic_rn_gbl_env = emptyGlobalRdrEnv,
887 icPrintUnqual :: DynFlags -> InteractiveContext -> PrintUnqualified
888 icPrintUnqual dflags ictxt = mkPrintUnqualified dflags (ic_rn_gbl_env ictxt)
891 extendInteractiveContext
892 :: InteractiveContext
894 -> InteractiveContext
895 extendInteractiveContext ictxt ids
896 = ictxt { ic_tmp_ids = snub ((ic_tmp_ids ictxt \\ ids) ++ ids)
897 -- NB. must be this way around, because we want
898 -- new ids to shadow existing bindings.
900 where snub = map head . group . sort
902 substInteractiveContext :: InteractiveContext -> TvSubst -> InteractiveContext
903 substInteractiveContext ictxt subst | isEmptyTvSubst subst = ictxt
904 substInteractiveContext ictxt@InteractiveContext{ic_tmp_ids=ids} subst
905 = ictxt { ic_tmp_ids = map subst_ty ids }
907 subst_ty id = id `setIdType` substTy subst (idType id)
910 %************************************************************************
912 Building a PrintUnqualified
914 %************************************************************************
916 Note [Printing original names]
917 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
918 Deciding how to print names is pretty tricky. We are given a name
919 P:M.T, where P is the package name, M is the defining module, and T is
920 the occurrence name, and we have to decide in which form to display
921 the name given a GlobalRdrEnv describing the current scope.
923 Ideally we want to display the name in the form in which it is in
924 scope. However, the name might not be in scope at all, and that's
925 where it gets tricky. Here are the cases:
927 1. T uniquely maps to P:M.T ---> "T" NameUnqual
928 2. There is an X for which X.T
929 uniquely maps to P:M.T ---> "X.T" NameQual X
930 3. There is no binding for "M.T" ---> "M.T" NameNotInScope1
931 4. Otherwise ---> "P:M.T" NameNotInScope2
933 (3) and (4) apply when the entity P:M.T is not in the GlobalRdrEnv at
934 all. In these cases we still want to refer to the name as "M.T", *but*
935 "M.T" might mean something else in the current scope (e.g. if there's
936 an "import X as M"), so to avoid confusion we avoid using "M.T" if
937 there's already a binding for it. Instead we write P:M.T.
939 There's one further subtlety: in case (3), what if there are two
940 things around, P1:M.T and P2:M.T? Then we don't want to print both of
941 them as M.T! However only one of the modules P1:M and P2:M can be
942 exposed (say P2), so we use M.T for that, and P1:M.T for the other one.
943 This is handled by the qual_mod component of PrintUnqualified, inside
944 the (ppr mod) of case (3), in Name.pprModulePrefix
947 -- | Creates some functions that work out the best ways to format
948 -- names for the user according to a set of heuristics
949 mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified
950 mkPrintUnqualified dflags env = (qual_name, qual_mod)
952 qual_name mod occ -- The (mod,occ) pair is the original name of the thing
953 | [gre] <- unqual_gres, right_name gre = NameUnqual
954 -- If there's a unique entity that's in scope unqualified with 'occ'
955 -- AND that entity is the right one, then we can use the unqualified name
957 | [gre] <- qual_gres = NameQual (get_qual_mod (gre_prov gre))
960 if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env)
964 | otherwise = panic "mkPrintUnqualified"
966 right_name gre = nameModule_maybe (gre_name gre) == Just mod
968 unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
969 qual_gres = filter right_name (lookupGlobalRdrEnv env occ)
971 get_qual_mod LocalDef = moduleName mod
972 get_qual_mod (Imported is) = ASSERT( not (null is) ) is_as (is_decl (head is))
974 -- we can mention a module P:M without the P: qualifier iff
975 -- "import M" would resolve unambiguously to P:M. (if P is the
976 -- current package we can just assume it is unqualified).
979 | modulePackageId mod == thisPackage dflags = False
981 | [pkgconfig] <- [pkg | (pkg,exposed_module) <- lookup,
982 exposed pkg && exposed_module],
983 packageConfigId pkgconfig == modulePackageId mod
984 -- this says: we are given a module P:M, is there just one exposed package
985 -- that exposes a module M, and is it package P?
989 where lookup = lookupModuleInAllPackages dflags (moduleName mod)
993 %************************************************************************
997 %************************************************************************
1000 -- | Determine the 'TyThing's brought into scope by another 'TyThing'
1001 -- /other/ than itself. For example, Id's don't have any implicit TyThings
1002 -- as they just bring themselves into scope, but classes bring their
1003 -- dictionary datatype, type constructor and some selector functions into
1004 -- scope, just for a start!
1006 -- N.B. the set of TyThings returned here *must* match the set of
1007 -- names returned by LoadIface.ifaceDeclSubBndrs, in the sense that
1008 -- TyThing.getOccName should define a bijection between the two lists.
1009 -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
1010 -- The order of the list does not matter.
1011 implicitTyThings :: TyThing -> [TyThing]
1013 -- For data and newtype declarations:
1014 implicitTyThings (ATyCon tc)
1015 = -- fields (names of selectors)
1016 -- (possibly) implicit coercion and family coercion
1017 -- depending on whether it's a newtype or a family instance or both
1018 implicitCoTyCon tc ++
1019 -- for each data constructor in order,
1020 -- the contructor, worker, and (possibly) wrapper
1021 concatMap (extras_plus . ADataCon) (tyConDataCons tc)
1023 implicitTyThings (AClass cl)
1024 = -- dictionary datatype:
1027 -- [recursive call:]
1028 -- (possibly) newtype coercion; definitely no family coercion here
1031 -- (no wrapper by invariant)
1032 extras_plus (ATyCon (classTyCon cl)) ++
1034 -- No extras_plus (recursive call) for the classATs, because they
1035 -- are only the family decls; they have no implicit things
1036 map ATyCon (classATs cl) ++
1037 -- superclass and operation selectors
1038 map AnId (classAllSelIds cl)
1040 implicitTyThings (ADataCon dc) =
1041 -- For data cons add the worker and (possibly) wrapper
1042 map AnId (dataConImplicitIds dc)
1044 implicitTyThings (AnId _) = []
1046 -- add a thing and recursive call
1047 extras_plus :: TyThing -> [TyThing]
1048 extras_plus thing = thing : implicitTyThings thing
1050 -- For newtypes and indexed data types (and both),
1051 -- add the implicit coercion tycon
1052 implicitCoTyCon :: TyCon -> [TyThing]
1054 = map ATyCon . catMaybes $ [-- Just if newtype, Nothing if not
1055 newTyConCo_maybe tc,
1056 -- Just if family instance, Nothing if not
1057 tyConFamilyCoercion_maybe tc]
1059 -- sortByOcc = sortBy (\ x -> \ y -> getOccName x < getOccName y)
1062 -- | Returns @True@ if there should be no interface-file declaration
1063 -- for this thing on its own: either it is built-in, or it is part
1064 -- of some other declaration, or it is generated implicitly by some
1065 -- other declaration.
1066 isImplicitTyThing :: TyThing -> Bool
1067 isImplicitTyThing (ADataCon _) = True
1068 isImplicitTyThing (AnId id) = isImplicitId id
1069 isImplicitTyThing (AClass _) = False
1070 isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc
1072 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
1073 extendTypeEnvWithIds env ids
1074 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
1077 %************************************************************************
1081 %************************************************************************
1084 -- | A map from 'Name's to 'TyThing's, constructed by typechecking
1085 -- local declarations or interface files
1086 type TypeEnv = NameEnv TyThing
1088 emptyTypeEnv :: TypeEnv
1089 typeEnvElts :: TypeEnv -> [TyThing]
1090 typeEnvClasses :: TypeEnv -> [Class]
1091 typeEnvTyCons :: TypeEnv -> [TyCon]
1092 typeEnvIds :: TypeEnv -> [Id]
1093 typeEnvDataCons :: TypeEnv -> [DataCon]
1094 lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
1096 emptyTypeEnv = emptyNameEnv
1097 typeEnvElts env = nameEnvElts env
1098 typeEnvClasses env = [cl | AClass cl <- typeEnvElts env]
1099 typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
1100 typeEnvIds env = [id | AnId id <- typeEnvElts env]
1101 typeEnvDataCons env = [dc | ADataCon dc <- typeEnvElts env]
1103 mkTypeEnv :: [TyThing] -> TypeEnv
1104 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
1106 lookupTypeEnv = lookupNameEnv
1108 -- Extend the type environment
1109 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
1110 extendTypeEnv env thing = extendNameEnv env (getName thing) thing
1112 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
1113 extendTypeEnvList env things = foldl extendTypeEnv env things
1117 -- | Find the 'TyThing' for the given 'Name' by using all the resources
1118 -- at our disposal: the compiled modules in the 'HomePackageTable' and the
1119 -- compiled modules in other packages that live in 'PackageTypeEnv'. Note
1120 -- that this does NOT look up the 'TyThing' in the module being compiled: you
1121 -- have to do that yourself, if desired
1122 lookupType :: DynFlags
1128 lookupType dflags hpt pte name
1129 -- in one-shot, we don't use the HPT
1130 | not (isOneShot (ghcMode dflags)) && modulePackageId mod == this_pkg
1131 = do hm <- lookupUFM hpt (moduleName mod) -- Maybe monad
1132 lookupNameEnv (md_types (hm_details hm)) name
1134 = lookupNameEnv pte name
1135 where mod = ASSERT( isExternalName name ) nameModule name
1136 this_pkg = thisPackage dflags
1138 -- | As 'lookupType', but with a marginally easier-to-use interface
1139 -- if you have a 'HscEnv'
1140 lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing)
1141 lookupTypeHscEnv hsc_env name = do
1142 eps <- readIORef (hsc_EPS hsc_env)
1143 return $! lookupType dflags hpt (eps_PTE eps) name
1145 dflags = hsc_dflags hsc_env
1146 hpt = hsc_HPT hsc_env
1150 -- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise
1151 tyThingTyCon :: TyThing -> TyCon
1152 tyThingTyCon (ATyCon tc) = tc
1153 tyThingTyCon other = pprPanic "tyThingTyCon" (pprTyThing other)
1155 -- | Get the 'Class' from a 'TyThing' if it is a class thing. Panics otherwise
1156 tyThingClass :: TyThing -> Class
1157 tyThingClass (AClass cls) = cls
1158 tyThingClass other = pprPanic "tyThingClass" (pprTyThing other)
1160 -- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise
1161 tyThingDataCon :: TyThing -> DataCon
1162 tyThingDataCon (ADataCon dc) = dc
1163 tyThingDataCon other = pprPanic "tyThingDataCon" (pprTyThing other)
1165 -- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise
1166 tyThingId :: TyThing -> Id
1167 tyThingId (AnId id) = id
1168 tyThingId (ADataCon dc) = dataConWrapId dc
1169 tyThingId other = pprPanic "tyThingId" (pprTyThing other)
1172 %************************************************************************
1174 \subsection{MonadThings and friends}
1176 %************************************************************************
1179 -- | Class that abstracts out the common ability of the monads in GHC
1180 -- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides
1181 -- a number of related convenience functions for accessing particular
1182 -- kinds of 'TyThing'
1183 class Monad m => MonadThings m where
1184 lookupThing :: Name -> m TyThing
1186 lookupId :: Name -> m Id
1187 lookupId = liftM tyThingId . lookupThing
1189 lookupDataCon :: Name -> m DataCon
1190 lookupDataCon = liftM tyThingDataCon . lookupThing
1192 lookupTyCon :: Name -> m TyCon
1193 lookupTyCon = liftM tyThingTyCon . lookupThing
1195 lookupClass :: Name -> m Class
1196 lookupClass = liftM tyThingClass . lookupThing
1200 -- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
1201 mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
1202 -> (OccName -> Maybe (OccName, Fingerprint))
1203 mkIfaceHashCache pairs
1204 = \occ -> lookupOccEnv env occ
1206 env = foldr add_decl emptyOccEnv pairs
1207 add_decl (v,d) env0 = foldr add_imp env1 (ifaceDeclSubBndrs d)
1209 decl_name = ifName d
1210 env1 = extendOccEnv env0 decl_name (decl_name, v)
1211 add_imp bndr env = extendOccEnv env bndr (decl_name, v)
1213 emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
1214 emptyIfaceHashCache _occ = Nothing
1217 %************************************************************************
1219 \subsection{Auxiliary types}
1221 %************************************************************************
1223 These types are defined here because they are mentioned in ModDetails,
1224 but they are mostly elaborated elsewhere
1227 ------------------ Warnings -------------------------
1228 -- | Warning information for a module
1230 = NoWarnings -- ^ Nothing deprecated
1231 | WarnAll WarningTxt -- ^ Whole module deprecated
1232 | WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated
1234 -- Only an OccName is needed because
1235 -- (1) a deprecation always applies to a binding
1236 -- defined in the module in which the deprecation appears.
1237 -- (2) deprecations are only reported outside the defining module.
1238 -- this is important because, otherwise, if we saw something like
1240 -- {-# DEPRECATED f "" #-}
1243 -- g = let f = undefined in f
1245 -- we'd need more information than an OccName to know to say something
1246 -- about the use of f in h but not the use of the locally bound f in g
1248 -- however, because we only report about deprecations from the outside,
1249 -- and a module can only export one value called f,
1250 -- an OccName suffices.
1252 -- this is in contrast with fixity declarations, where we need to map
1253 -- a Name to its fixity declaration.
1256 -- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface'
1257 mkIfaceWarnCache :: Warnings -> Name -> Maybe WarningTxt
1258 mkIfaceWarnCache NoWarnings = \_ -> Nothing
1259 mkIfaceWarnCache (WarnAll t) = \_ -> Just t
1260 mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
1262 emptyIfaceWarnCache :: Name -> Maybe WarningTxt
1263 emptyIfaceWarnCache _ = Nothing
1265 plusWarns :: Warnings -> Warnings -> Warnings
1266 plusWarns d NoWarnings = d
1267 plusWarns NoWarnings d = d
1268 plusWarns _ (WarnAll t) = WarnAll t
1269 plusWarns (WarnAll t) _ = WarnAll t
1270 plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2)
1273 -- | A collection of 'AvailInfo' - several things that are \"available\"
1274 type Avails = [AvailInfo]
1275 -- | 'Name'd things that are available
1276 type AvailInfo = GenAvailInfo Name
1277 -- | 'RdrName'd things that are available
1278 type RdrAvailInfo = GenAvailInfo OccName
1280 -- | Records what things are "available", i.e. in scope
1281 data GenAvailInfo name = Avail name -- ^ An ordinary identifier in scope
1283 [name] -- ^ A type or class in scope. Parameters:
1285 -- 1) The name of the type or class
1287 -- 2) The available pieces of type or class.
1288 -- NB: If the type or class is itself
1289 -- to be in scope, it must be in this list.
1290 -- Thus, typically: @AvailTC Eq [Eq, ==, \/=]@
1292 -- Equality used when deciding if the interface has changed
1294 -- | The original names declared of a certain module that are exported
1295 type IfaceExport = (Module, [GenAvailInfo OccName])
1297 availsToNameSet :: [AvailInfo] -> NameSet
1298 availsToNameSet avails = foldr add emptyNameSet avails
1299 where add avail set = addListToNameSet set (availNames avail)
1301 availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo
1302 availsToNameEnv avails = foldr add emptyNameEnv avails
1303 where add avail env = extendNameEnvList env
1304 (zip (availNames avail) (repeat avail))
1306 -- | Just the main name made available, i.e. not the available pieces
1307 -- of type or class brought into scope by the 'GenAvailInfo'
1308 availName :: GenAvailInfo name -> name
1309 availName (Avail n) = n
1310 availName (AvailTC n _) = n
1312 -- | All names made available by the availability information
1313 availNames :: GenAvailInfo name -> [name]
1314 availNames (Avail n) = [n]
1315 availNames (AvailTC _ ns) = ns
1317 instance Outputable n => Outputable (GenAvailInfo n) where
1320 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
1321 pprAvail (Avail n) = ppr n
1322 pprAvail (AvailTC n ns) = ppr n <> braces (hsep (punctuate comma (map ppr ns)))
1326 -- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface'
1327 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
1328 mkIfaceFixCache pairs
1329 = \n -> lookupOccEnv env n `orElse` defaultFixity
1331 env = mkOccEnv pairs
1333 emptyIfaceFixCache :: OccName -> Fixity
1334 emptyIfaceFixCache _ = defaultFixity
1336 -- | Fixity environment mapping names to their fixities
1337 type FixityEnv = NameEnv FixItem
1339 -- | Fixity information for an 'Name'. We keep the OccName in the range
1340 -- so that we can generate an interface from it
1341 data FixItem = FixItem OccName Fixity
1343 instance Outputable FixItem where
1344 ppr (FixItem occ fix) = ppr fix <+> ppr occ
1346 emptyFixityEnv :: FixityEnv
1347 emptyFixityEnv = emptyNameEnv
1349 lookupFixity :: FixityEnv -> Name -> Fixity
1350 lookupFixity env n = case lookupNameEnv env n of
1351 Just (FixItem _ fix) -> fix
1352 Nothing -> defaultFixity
1356 %************************************************************************
1358 \subsection{WhatsImported}
1360 %************************************************************************
1363 -- | Records whether a module has orphans. An \"orphan\" is one of:
1365 -- * An instance declaration in a module other than the definition
1366 -- module for one of the type constructors or classes in the instance head
1368 -- * A transformation rule in a module other than the one defining
1369 -- the function in the head of the rule
1370 type WhetherHasOrphans = Bool
1372 -- | Does this module define family instances?
1373 type WhetherHasFamInst = Bool
1375 -- | Did this module originate from a *-boot file?
1376 type IsBootInterface = Bool
1378 -- | Dependency information about modules and packages below this one
1379 -- in the import hierarchy.
1381 -- Invariant: the dependencies of a module @M@ never includes @M@.
1383 -- Invariant: none of the lists contain duplicates.
1385 = Deps { dep_mods :: [(ModuleName, IsBootInterface)]
1386 -- ^ Home-package module dependencies
1387 , dep_pkgs :: [PackageId]
1388 -- ^ External package dependencies
1389 , dep_orphs :: [Module]
1390 -- ^ Orphan modules (whether home or external pkg),
1391 -- *not* including family instance orphans as they
1392 -- are anyway included in 'dep_finsts'
1393 , dep_finsts :: [Module]
1394 -- ^ Modules that contain family instances (whether the
1395 -- instances are from the home or an external package)
1398 -- Equality used only for old/new comparison in MkIface.addVersionInfo
1400 -- See 'TcRnTypes.ImportAvails' for details on dependencies.
1402 noDependencies :: Dependencies
1403 noDependencies = Deps [] [] [] []
1405 -- | Records modules that we depend on by making a direct import from
1407 = UsagePackageModule {
1409 -- ^ External package module depended on
1410 usg_mod_hash :: Fingerprint
1411 } -- ^ Module from another package
1413 usg_mod_name :: ModuleName,
1414 -- ^ Name of the module
1415 usg_mod_hash :: Fingerprint,
1416 -- ^ Cached module fingerprint
1417 usg_entities :: [(OccName,Fingerprint)],
1418 -- ^ Entities we depend on, sorted by occurrence name and fingerprinted.
1419 -- NB: usages are for parent names only, e.g. type constructors
1420 -- but not the associated data constructors.
1421 usg_exports :: Maybe Fingerprint
1422 -- ^ Fingerprint for the export list we used to depend on this module,
1423 -- if we depend on the export list
1424 } -- ^ Module from the current package
1426 -- The export list field is (Just v) if we depend on the export list:
1427 -- i.e. we imported the module directly, whether or not we
1428 -- enumerated the things we imported, or just imported
1430 -- We need to recompile if M's exports change, because
1431 -- if the import was import M, we might now have a name clash
1432 -- in the importing module.
1433 -- if the import was import M(x) M might no longer export x
1434 -- The only way we don't depend on the export list is if we have
1436 -- And of course, for modules that aren't imported directly we don't
1437 -- depend on their export lists
1441 %************************************************************************
1443 The External Package State
1445 %************************************************************************
1448 type PackageTypeEnv = TypeEnv
1449 type PackageRuleBase = RuleBase
1450 type PackageInstEnv = InstEnv
1451 type PackageFamInstEnv = FamInstEnv
1452 type PackageVectInfo = VectInfo
1453 type PackageAnnEnv = AnnEnv
1455 -- | Information about other packages that we have slurped in by reading
1456 -- their interface files
1457 data ExternalPackageState
1459 eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
1460 -- ^ In OneShot mode (only), home-package modules
1461 -- accumulate in the external package state, and are
1462 -- sucked in lazily. For these home-pkg modules
1463 -- (only) we need to record which are boot modules.
1464 -- We set this field after loading all the
1465 -- explicitly-imported interfaces, but before doing
1468 -- The 'ModuleName' part is not necessary, but it's useful for
1469 -- debug prints, and it's convenient because this field comes
1470 -- direct from 'TcRnTypes.imp_dep_mods'
1472 eps_PIT :: !PackageIfaceTable,
1473 -- ^ The 'ModIface's for modules in external packages
1474 -- whose interfaces we have opened.
1475 -- The declarations in these interface files are held in the
1476 -- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules'
1477 -- fields of this record, not in the 'mi_decls' fields of the
1478 -- interface we have sucked in.
1480 -- What /is/ in the PIT is:
1484 -- * Fingerprint info
1490 -- * Deprecations and warnings
1492 eps_PTE :: !PackageTypeEnv,
1493 -- ^ Result of typechecking all the external package
1494 -- interface files we have sucked in. The domain of
1495 -- the mapping is external-package modules
1497 eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated
1498 -- from all the external-package modules
1499 eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated
1500 -- from all the external-package modules
1501 eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated
1502 -- from all the external-package modules
1503 eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated
1504 -- from all the external-package modules
1505 eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated
1506 -- from all the external-package modules
1508 eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external
1509 -- packages, keyed off the module that declared them
1511 eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages
1514 -- | Accumulated statistics about what we are putting into the 'ExternalPackageState'.
1515 -- \"In\" means stuff that is just /read/ from interface files,
1516 -- \"Out\" means actually sucked in and type-checked
1517 data EpsStats = EpsStats { n_ifaces_in
1518 , n_decls_in, n_decls_out
1519 , n_rules_in, n_rules_out
1520 , n_insts_in, n_insts_out :: !Int }
1522 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
1523 -- ^ Add stats for one newly-read interface
1524 addEpsInStats stats n_decls n_insts n_rules
1525 = stats { n_ifaces_in = n_ifaces_in stats + 1
1526 , n_decls_in = n_decls_in stats + n_decls
1527 , n_insts_in = n_insts_in stats + n_insts
1528 , n_rules_in = n_rules_in stats + n_rules }
1531 Names in a NameCache are always stored as a Global, and have the SrcLoc
1532 of their binding locations.
1534 Actually that's not quite right. When we first encounter the original
1535 name, we might not be at its binding site (e.g. we are reading an
1536 interface file); so we give it 'noSrcLoc' then. Later, when we find
1537 its binding site, we fix it up.
1540 -- | The NameCache makes sure that there is just one Unique assigned for
1541 -- each original name; i.e. (module-name, occ-name) pair and provides
1542 -- something of a lookup mechanism for those names.
1544 = NameCache { nsUniqs :: UniqSupply,
1545 -- ^ Supply of uniques
1546 nsNames :: OrigNameCache,
1547 -- ^ Ensures that one original name gets one unique
1548 nsIPs :: OrigIParamCache
1549 -- ^ Ensures that one implicit parameter name gets one unique
1552 -- | Per-module cache of original 'OccName's given 'Name's
1553 type OrigNameCache = ModuleEnv (OccEnv Name)
1555 -- | Module-local cache of implicit parameter 'OccName's given 'Name's
1556 type OrigIParamCache = Map (IPName OccName) (IPName Name)
1561 %************************************************************************
1563 The module graph and ModSummary type
1564 A ModSummary is a node in the compilation manager's
1565 dependency graph, and it's also passed to hscMain
1567 %************************************************************************
1570 -- | A ModuleGraph contains all the nodes from the home package (only).
1571 -- There will be a node for each source module, plus a node for each hi-boot
1574 -- The graph is not necessarily stored in topologically-sorted order. Use
1575 -- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this.
1576 type ModuleGraph = [ModSummary]
1578 emptyMG :: ModuleGraph
1581 -- | A single node in a 'ModuleGraph. The nodes of the module graph are one of:
1583 -- * A regular Haskell source module
1585 -- * A hi-boot source module
1587 -- * An external-core source module
1590 ms_mod :: Module, -- ^ Identity of the module
1591 ms_hsc_src :: HscSource, -- ^ The module source either plain Haskell, hs-boot or external core
1592 ms_location :: ModLocation, -- ^ Location of the various files belonging to the module
1593 ms_hs_date :: ClockTime, -- ^ Timestamp of source file
1594 ms_obj_date :: Maybe ClockTime, -- ^ Timestamp of object, if we have one
1595 ms_srcimps :: [Located (ImportDecl RdrName)], -- ^ Source imports of the module
1596 ms_imps :: [Located (ImportDecl RdrName)], -- ^ Non-source imports of the module
1597 ms_hspp_file :: FilePath, -- ^ Filename of preprocessed source file
1598 ms_hspp_opts :: DynFlags, -- ^ Cached flags from @OPTIONS@, @INCLUDE@
1599 -- and @LANGUAGE@ pragmas in the modules source code
1600 ms_hspp_buf :: Maybe StringBuffer -- ^ The actual preprocessed source, if we have it
1603 ms_mod_name :: ModSummary -> ModuleName
1604 ms_mod_name = moduleName . ms_mod
1606 -- The ModLocation contains both the original source filename and the
1607 -- filename of the cleaned-up source file after all preprocessing has been
1608 -- done. The point is that the summariser will have to cpp/unlit/whatever
1609 -- all files anyway, and there's no point in doing this twice -- just
1610 -- park the result in a temp file, put the name of it in the location,
1611 -- and let @compile@ read from that file on the way back up.
1613 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
1614 -- the ms_hs_date and imports can, of course, change
1616 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
1617 msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
1618 msHiFilePath ms = ml_hi_file (ms_location ms)
1619 msObjFilePath ms = ml_obj_file (ms_location ms)
1621 -- | Did this 'ModSummary' originate from a hs-boot file?
1622 isBootSummary :: ModSummary -> Bool
1623 isBootSummary ms = isHsBoot (ms_hsc_src ms)
1625 instance Outputable ModSummary where
1627 = sep [text "ModSummary {",
1628 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1629 text "ms_mod =" <+> ppr (ms_mod ms)
1630 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
1631 text "ms_imps =" <+> ppr (ms_imps ms),
1632 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1636 showModMsg :: HscTarget -> Bool -> ModSummary -> String
1637 showModMsg target recomp mod_summary
1639 hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
1640 char '(', text (normalise $ msHsFilePath mod_summary) <> comma,
1642 HscInterpreted | recomp
1643 -> text "interpreted"
1644 HscNothing -> text "nothing"
1645 _ -> text (normalise $ msObjFilePath mod_summary),
1648 mod = moduleName (ms_mod mod_summary)
1649 mod_str = showSDoc (ppr mod) ++ hscSourceString (ms_hsc_src mod_summary)
1653 %************************************************************************
1655 \subsection{Hpc Support}
1657 %************************************************************************
1660 -- | Information about a modules use of Haskell Program Coverage
1663 { hpcInfoTickCount :: Int
1664 , hpcInfoHash :: Int
1667 { hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*?
1670 -- | This is used to signal if one of my imports used HPC instrumentation
1671 -- even if there is no module-local HPC usage
1672 type AnyHpcUsage = Bool
1674 emptyHpcInfo :: AnyHpcUsage -> HpcInfo
1675 emptyHpcInfo = NoHpcInfo
1677 -- | Find out if HPC is used by this module or any of the modules
1679 isHpcUsed :: HpcInfo -> AnyHpcUsage
1680 isHpcUsed (HpcInfo {}) = True
1681 isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
1684 %************************************************************************
1686 \subsection{Vectorisation Support}
1688 %************************************************************************
1690 The following information is generated and consumed by the vectorisation
1691 subsystem. It communicates the vectorisation status of declarations from one
1694 Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
1695 below? We need to know `f' when converting to IfaceVectInfo. However, during
1696 vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
1697 on just the OccName easily in a Core pass.
1700 -- | Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'.
1703 vectInfoVar :: VarEnv (Var , Var ), -- ^ @(f, f_v)@ keyed on @f@
1704 vectInfoTyCon :: NameEnv (TyCon , TyCon), -- ^ @(T, T_v)@ keyed on @T@
1705 vectInfoDataCon :: NameEnv (DataCon, DataCon), -- ^ @(C, C_v)@ keyed on @C@
1706 vectInfoPADFun :: NameEnv (TyCon , Var), -- ^ @(T_v, paT)@ keyed on @T_v@
1707 vectInfoIso :: NameEnv (TyCon , Var) -- ^ @(T, isoT)@ keyed on @T@
1710 -- | Vectorisation information for 'ModIface': a slightly less low-level view
1713 ifaceVectInfoVar :: [Name],
1714 -- ^ All variables in here have a vectorised variant
1715 ifaceVectInfoTyCon :: [Name],
1716 -- ^ All 'TyCon's in here have a vectorised variant;
1717 -- the name of the vectorised variant and those of its
1718 -- data constructors are determined by 'OccName.mkVectTyConOcc'
1719 -- and 'OccName.mkVectDataConOcc'; the names of
1720 -- the isomorphisms are determined by 'OccName.mkVectIsoOcc'
1721 ifaceVectInfoTyConReuse :: [Name]
1722 -- ^ The vectorised form of all the 'TyCon's in here coincides with
1723 -- the unconverted form; the name of the isomorphisms is determined
1724 -- by 'OccName.mkVectIsoOcc'
1727 noVectInfo :: VectInfo
1728 noVectInfo = VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyNameEnv emptyNameEnv
1730 plusVectInfo :: VectInfo -> VectInfo -> VectInfo
1731 plusVectInfo vi1 vi2 =
1732 VectInfo (vectInfoVar vi1 `plusVarEnv` vectInfoVar vi2)
1733 (vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2)
1734 (vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
1735 (vectInfoPADFun vi1 `plusNameEnv` vectInfoPADFun vi2)
1736 (vectInfoIso vi1 `plusNameEnv` vectInfoIso vi2)
1738 concatVectInfo :: [VectInfo] -> VectInfo
1739 concatVectInfo = foldr plusVectInfo noVectInfo
1741 noIfaceVectInfo :: IfaceVectInfo
1742 noIfaceVectInfo = IfaceVectInfo [] [] []
1745 %************************************************************************
1747 \subsection{Linkable stuff}
1749 %************************************************************************
1751 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
1752 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
1755 -- | Information we can use to dynamically link modules into the compiler
1756 data Linkable = LM {
1757 linkableTime :: ClockTime, -- ^ Time at which this linkable was built
1758 -- (i.e. when the bytecodes were produced,
1759 -- or the mod date on the files)
1760 linkableModule :: Module, -- ^ The linkable module itself
1761 linkableUnlinked :: [Unlinked]
1762 -- ^ Those files and chunks of code we have yet to link.
1764 -- INVARIANT: A valid linkable always has at least one 'Unlinked' item.
1765 -- If this list is empty, the Linkable represents a fake linkable, which
1766 -- is generated in HscNothing mode to avoid recompiling modules.
1768 -- XXX: Do items get removed from this list when they get linked?
1771 isObjectLinkable :: Linkable -> Bool
1772 isObjectLinkable l = not (null unlinked) && all isObject unlinked
1773 where unlinked = linkableUnlinked l
1774 -- A linkable with no Unlinked's is treated as a BCO. We can
1775 -- generate a linkable with no Unlinked's as a result of
1776 -- compiling a module in HscNothing mode, and this choice
1777 -- happens to work well with checkStability in module GHC.
1779 instance Outputable Linkable where
1780 ppr (LM when_made mod unlinkeds)
1781 = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
1782 $$ nest 3 (ppr unlinkeds)
1784 -------------------------------------------
1786 -- | Objects which have yet to be linked by the compiler
1788 = DotO FilePath -- ^ An object file (.o)
1789 | DotA FilePath -- ^ Static archive file (.a)
1790 | DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib)
1791 | BCOs CompiledByteCode ModBreaks -- ^ A byte-code object, lives only in memory
1794 data CompiledByteCode = CompiledByteCodeUndefined
1795 _unused :: CompiledByteCode
1796 _unused = CompiledByteCodeUndefined
1799 instance Outputable Unlinked where
1800 ppr (DotO path) = text "DotO" <+> text path
1801 ppr (DotA path) = text "DotA" <+> text path
1802 ppr (DotDLL path) = text "DotDLL" <+> text path
1804 ppr (BCOs bcos _) = text "BCOs" <+> ppr bcos
1806 ppr (BCOs _ _) = text "No byte code"
1809 -- | Is this an actual file on disk we can link in somehow?
1810 isObject :: Unlinked -> Bool
1811 isObject (DotO _) = True
1812 isObject (DotA _) = True
1813 isObject (DotDLL _) = True
1816 -- | Is this a bytecode linkable with no file on disk?
1817 isInterpretable :: Unlinked -> Bool
1818 isInterpretable = not . isObject
1820 -- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object
1821 nameOfObject :: Unlinked -> FilePath
1822 nameOfObject (DotO fn) = fn
1823 nameOfObject (DotA fn) = fn
1824 nameOfObject (DotDLL fn) = fn
1825 nameOfObject other = pprPanic "nameOfObject" (ppr other)
1827 -- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable
1828 byteCodeOfObject :: Unlinked -> CompiledByteCode
1829 byteCodeOfObject (BCOs bc _) = bc
1830 byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
1833 %************************************************************************
1835 \subsection{Breakpoint Support}
1837 %************************************************************************
1840 -- | Breakpoint index
1841 type BreakIndex = Int
1843 -- | All the information about the breakpoints for a given module
1846 { modBreaks_flags :: BreakArray
1847 -- ^ The array of flags, one per breakpoint,
1848 -- indicating which breakpoints are enabled.
1849 , modBreaks_locs :: !(Array BreakIndex SrcSpan)
1850 -- ^ An array giving the source span of each breakpoint.
1851 , modBreaks_vars :: !(Array BreakIndex [OccName])
1852 -- ^ An array giving the names of the free variables at each breakpoint.
1853 , modBreaks_decls :: !(Array BreakIndex [String])
1854 -- ^ An array giving the names of the declarations enclosing each breakpoint.
1857 emptyModBreaks :: ModBreaks
1858 emptyModBreaks = ModBreaks
1859 { modBreaks_flags = error "ModBreaks.modBreaks_array not initialised"
1860 -- Todo: can we avoid this?
1861 , modBreaks_locs = array (0,-1) []
1862 , modBreaks_vars = array (0,-1) []
1863 , modBreaks_decls = array (0,-1) []