root/compiler/main/HscTypes.lhs

Revision 215c8265e72a7f2a8d57793d5a5dec4c0deed08a, 92.6 KB (checked in by Paolo Capriotti <p.capriotti@…>, 2 weeks ago)

Add a fixity environment to InteractiveContext? (#2947)

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