HscTypes.lhs 110 KB
Newer Older
1 2
%
% (c) The University of Glasgow, 2006
3 4 5 6
%
\section[HscTypes]{Types for the per-module compiler}

\begin{code}
7
{-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
8

9
-- | Types for the per-module compiler
dterei's avatar
dterei committed
10
module HscTypes (
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
11
        -- * compilation state
12
        HscEnv(..), hscEPS,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
13 14 15
        FinderCache, FindResult(..), ModLocationCache,
        Target(..), TargetId(..), pprTarget, pprTargetId,
        ModuleGraph, emptyMG,
16 17 18 19
        HscStatus(..),

        -- * Hsc monad
        Hsc(..), runHsc, runInteractiveHsc,
20

21
        -- * Information about modules
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
22
        ModDetails(..), emptyModDetails,
23
        ModGuts(..), CgGuts(..), ForeignStubs(..), appendStubC,
24
        ImportedMods, ImportedModsVal,
25

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
26 27
        ModSummary(..), ms_imps, ms_mod_name, showModMsg, isBootSummary,
        msHsFilePath, msHiFilePath, msObjFilePath,
28
        SourceModified(..),
29

30
        -- * Information about the module being compiled
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
31
        HscSource(..), isHsBoot, hscSourceString,       -- Re-exported from DriverPhases
dterei's avatar
dterei committed
32

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
33 34
        -- * State relating to modules in this package
        HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
35
        hptInstances, hptRules, hptVectInfo, pprHPT,
36 37
        hptObjs,

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
38 39 40 41
        -- * State relating to known packages
        ExternalPackageState(..), EpsStats(..), addEpsInStats,
        PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
        lookupIfaceByModule, emptyModIface,
dterei's avatar
dterei committed
42

43
        PackageInstEnv, PackageFamInstEnv, PackageRuleBase,
44

45
        mkSOName, mkHsSOName, soExt,
46

47 48 49
        -- * Annotations
        prepareAnnotations,

50
        -- * Interactive context
dterei's avatar
dterei committed
51
        InteractiveContext(..), emptyInteractiveContext,
52
        icPrintUnqual, icInScopeTTs, icExtendGblRdrEnv,
53
        extendInteractiveContext, substInteractiveContext,
54 55
        setInteractivePrintName, icInteractiveModule,
        InteractiveImport(..), setInteractivePackage,
56
        mkPrintUnqualified, pprModulePrefix,
57
        mkQualPackage, mkQualModule,
58

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
59 60
        -- * Interfaces
        ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache,
61
        emptyIfaceWarnCache, 
62

63
        -- * Fixity
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
64
        FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
65

66
        -- * TyThings and type environments
67
        TyThing(..),  tyThingAvailInfo,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
68
        tyThingTyCon, tyThingDataCon,
69 70 71
        tyThingId, tyThingCoAxiom, tyThingParent_maybe, tyThingsTyVars,
        implicitTyThings, implicitTyConThings, implicitClassThings,
        isImplicitTyThing,
dterei's avatar
dterei committed
72

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
73
        TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv,
74
        typeEnvFromEntities, mkTypeEnvWithImplicits,
cactus's avatar
cactus committed
75
        extendTypeEnv, extendTypeEnvList,
76
        extendTypeEnvWithIds, 
cactus's avatar
cactus committed
77 78
        lookupTypeEnv,
        typeEnvElts, typeEnvTyCons, typeEnvIds, typeEnvPatSyns,
79
        typeEnvDataCons, typeEnvCoAxioms, typeEnvClasses,
80

81 82 83 84
        -- * MonadThings
        MonadThings(..),

        -- * Information on imports and exports
dterei's avatar
dterei committed
85
        WhetherHasOrphans, IsBootInterface, Usage(..),
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
86
        Dependencies(..), noDependencies,
87
        NameCache(..), OrigNameCache,
88
        IfaceExport,
89

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
90 91
        -- * Warnings
        Warnings(..), WarningTxt(..), plusWarns,
92

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
93
        -- * Linker stuff
94
        Linkable(..), isObjectLinkable, linkableObjs,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
95 96
        Unlinked(..), CompiledByteCode,
        isObject, nameOfObject, isInterpretable, byteCodeOfObject,
dterei's avatar
dterei committed
97

98
        -- * Program coverage
99
        HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
100

101
        -- * Breakpoints
102 103
        ModBreaks (..), BreakIndex, emptyModBreaks,

104
        -- * Vectorisation information
dterei's avatar
dterei committed
105
        VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo,
106
        noIfaceVectInfo, isNoIfaceVectInfo,
107

108 109
        -- * Safe Haskell information
        IfaceTrustInfo, getSafeMode, setSafeMode, noIfaceTrustInfo,
110
        trustInfoToNum, numToTrustInfo, IsSafeImport,
111

112 113 114
        -- * result of the parser
        HsParsedModule(..),

115 116 117 118
        -- * Compilation errors and warnings
        SourceError, GhcApiError, mkSrcErr, srcErrorMessages, mkApiErr,
        throwOneError, handleSourceError,
        handleFlagWarnings, printOrThrowWarnings,
119
    ) where
120 121 122

#include "HsVersions.h"

123
#ifdef GHCI
124
import ByteCodeAsm      ( CompiledByteCode )
125
import InteractiveEvalTypes ( Resume )
126 127
#endif

128
import HsSyn
129
import RdrName
130
import Avail
131
import Module
132
import InstEnv          ( InstEnv, ClsInst )
133
import FamInstEnv
134
import Rules            ( RuleBase )
135
import CoreSyn          ( CoreProgram )
dterei's avatar
dterei committed
136 137
import Name
import NameEnv
dterei's avatar
dterei committed
138
import NameSet
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
139
import VarEnv
140
import VarSet
141
import Var
142
import Id
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
143
import IdInfo           ( IdDetails(..) )
dterei's avatar
dterei committed
144
import Type
145

146
import Annotations      ( Annotation, AnnEnv, mkAnnEnv, plusAnnEnv )
147
import Class
148
import TyCon
149
import CoAxiom
cactus's avatar
cactus committed
150
import ConLike
151
import DataCon
cactus's avatar
cactus committed
152
import PatSyn
153
import PrelNames        ( gHC_PRIM, ioTyConName, printName, mkInteractiveModule )
dterei's avatar
dterei committed
154
import Packages hiding  ( Version(..) )
155
import DynFlags
156
import DriverPhases     ( Phase, HscSource(..), isHsBoot, hscSourceString )
157
import BasicTypes
158
import IfaceSyn
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
159
import CoreSyn          ( CoreRule, CoreVect )
160
import Maybes
161
import Outputable
162
import BreakArray
Ian Lynagh's avatar
Ian Lynagh committed
163
import SrcLoc
164
-- import Unique
165 166
import UniqFM
import UniqSupply
167
import FastString
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
168
import StringBuffer     ( StringBuffer )
169
import Fingerprint
170
import MonadUtils
171
import Bag
172
import Binary
173
import ErrUtils
174
import Platform
175
import Util
Simon Marlow's avatar
Simon Marlow committed
176

177
import Control.Monad    ( guard, liftM, when, ap )
178
import Data.Array       ( Array, array )
dterei's avatar
dterei committed
179
import Data.IORef
180
import Data.Time
181
import Data.Word
182
import Data.Typeable    ( Typeable )
dterei's avatar
dterei committed
183 184
import Exception
import System.FilePath
185

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
-- -----------------------------------------------------------------------------
-- Compilation state
-- -----------------------------------------------------------------------------

-- | Status of a compilation to hard-code
data HscStatus
    = HscNotGeneratingCode
    | HscUpToDate
    | HscUpdateBoot
    | HscRecomp CgGuts ModSummary

-- -----------------------------------------------------------------------------
-- The Hsc monad: Passing an environment and warning state

newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))

instance Functor Hsc where
    fmap = liftM

instance Applicative Hsc where
    pure = return
    (<*>) = ap

instance Monad Hsc where
    return a    = Hsc $ \_ w -> return (a, w)
    Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
                                   case k a of
                                       Hsc k' -> k' e w1

instance MonadIO Hsc where
    liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)

instance HasDynFlags Hsc where
    getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)

runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env (Hsc hsc) = do
    (a, w) <- hsc hsc_env emptyBag
    printOrThrowWarnings (hsc_dflags hsc_env) w
    return a

227
runInteractiveHsc :: HscEnv -> Hsc a -> IO a
228 229
-- A variant of runHsc that switches in the DynFlags from the
-- InteractiveContext before running the Hsc computation.
230 231 232 233
runInteractiveHsc hsc_env
  = runHsc (hsc_env { hsc_dflags = interactive_dflags })
  where
    interactive_dflags = ic_dflags (hsc_IC hsc_env)
234

235 236
-- -----------------------------------------------------------------------------
-- Source Errors
237

238 239
-- When the compiler (HscMain) discovers errors, it throws an
-- exception in the IO monad.
240 241

mkSrcErr :: ErrorMessages -> SourceError
dterei's avatar
dterei committed
242 243
mkSrcErr = SourceError

244
srcErrorMessages :: SourceError -> ErrorMessages
dterei's avatar
dterei committed
245 246
srcErrorMessages (SourceError msgs) = msgs

247
mkApiErr :: DynFlags -> SDoc -> GhcApiError
Ian Lynagh's avatar
Ian Lynagh committed
248
mkApiErr dflags msg = GhcApiError (showSDoc dflags msg)
249

250 251 252
throwOneError :: MonadIO m => ErrMsg -> m ab
throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
-- | A source error is an error that is caused by one or more errors in the
-- source code.  A 'SourceError' is thrown by many functions in the
-- compilation pipeline.  Inside GHC these errors are merely printed via
-- 'log_action', but API clients may treat them differently, for example,
-- insert them into a list box.  If you want the default behaviour, use the
-- idiom:
--
-- > handleSourceError printExceptionAndWarnings $ do
-- >   ... api calls that may fail ...
--
-- The 'SourceError's error messages can be accessed via 'srcErrorMessages'.
-- This list may be empty if the compiler failed due to @-Werror@
-- ('Opt_WarnIsError').
--
-- See 'printExceptionAndWarnings' for more information on what to take care
-- of when writing a custom error handler.
269 270
newtype SourceError = SourceError ErrorMessages
  deriving Typeable
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

instance Show SourceError where
  show (SourceError msgs) = unlines . map show . bagToList $ msgs

instance Exception SourceError

-- | Perform the given action and call the exception handler if the action
-- throws a 'SourceError'.  See 'SourceError' for more information.
handleSourceError :: (ExceptionMonad m) =>
                     (SourceError -> m a) -- ^ exception handler
                  -> m a -- ^ action to perform
                  -> m a
handleSourceError handler act =
  gcatch act (\(e :: SourceError) -> handler e)

dterei's avatar
dterei committed
286
-- | An error thrown if the GHC API is used in an incorrect fashion.
287
newtype GhcApiError = GhcApiError String
dterei's avatar
dterei committed
288
  deriving Typeable
289 290

instance Show GhcApiError where
291
  show (GhcApiError msg) = msg
292 293 294

instance Exception GhcApiError

295 296 297 298
-- | Given a bag of warnings, turn them into an exception if
-- -Werror is enabled, or print them out otherwise.
printOrThrowWarnings :: DynFlags -> Bag WarnMsg -> IO ()
printOrThrowWarnings dflags warns
ian@well-typed.com's avatar
ian@well-typed.com committed
299
  | gopt Opt_WarnIsError dflags
300
  = when (not (isEmptyBag warns)) $ do
Ian Lynagh's avatar
Ian Lynagh committed
301
      throwIO $ mkSrcErr $ warns `snocBag` warnIsErrorMsg dflags
302
  | otherwise
303
  = printBagOfErrors dflags warns
304

305
handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
306
handleFlagWarnings dflags warns
307
 = when (wopt Opt_WarnDeprecatedFlags dflags) $ do
308
        -- It would be nicer if warns :: [Located MsgDoc], but that
309
        -- has circular import problems.
Ian Lynagh's avatar
Ian Lynagh committed
310
      let bag = listToBag [ mkPlainWarnMsg dflags loc (text warn)
311
                          | L loc warn <- warns ]
312

313
      printOrThrowWarnings dflags bag
314 315
\end{code}

dterei's avatar
dterei committed
316 317 318 319 320 321
%************************************************************************
%*                                                                      *
\subsection{HscEnv}
%*                                                                      *
%************************************************************************

322
\begin{code}
dterei's avatar
dterei committed
323

324
-- | Hscenv is like 'Session', except that some of the fields are immutable.
325 326 327 328 329 330 331 332 333
-- An HscEnv is used to compile a single module from plain Haskell source
-- code (after preprocessing) to either C, assembly or C--.  Things like
-- the module graph don't change during a single compilation.
--
-- Historical note: \"hsc\" used to be the name of the compiler binary,
-- when there was a separate driver and compiler.  To compile a single
-- module, the driver would invoke hsc on the source code... so nowadays
-- we think of hsc as the layer of the compiler that deals with compiling
-- a single module.
dterei's avatar
dterei committed
334 335
data HscEnv
  = HscEnv {
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349
        hsc_dflags :: DynFlags,
                -- ^ The dynamic flag settings

        hsc_targets :: [Target],
                -- ^ The targets (or roots) of the current session

        hsc_mod_graph :: ModuleGraph,
                -- ^ The module graph of the current session

        hsc_IC :: InteractiveContext,
                -- ^ The context for evaluating interactive statements

        hsc_HPT    :: HomePackageTable,
                -- ^ The home package table describes already-compiled
dterei's avatar
dterei committed
350
                -- home-package modules, /excluding/ the module we
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
351 352
                -- are compiling right now.
                -- (In one-shot mode the current module is the only
dterei's avatar
dterei committed
353 354 355 356
                -- home-package module, so hsc_HPT is empty.  All other
                -- modules count as \"external-package\" modules.
                -- However, even in GHCi mode, hi-boot interfaces are
                -- demand-loaded into the external-package table.)
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
357
                --
dterei's avatar
dterei committed
358 359
                -- 'hsc_HPT' is not mutable because we only demand-load
                -- external packages; the home package is eagerly
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
360
                -- loaded, module by module, by the compilation manager.
dterei's avatar
dterei committed
361
                --
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
362 363 364
                -- The HPT may contain modules compiled earlier by @--make@
                -- but not actually below the current module in the dependency
                -- graph.
dterei's avatar
dterei committed
365
                --
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
366
                -- (This changes a previous invariant: changed Jan 05.)
dterei's avatar
dterei committed
367

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
368 369 370 371
        hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
                -- ^ Information about the currently loaded external packages.
                -- This is mutable because packages will be demand-loaded during
                -- a compilation run as required.
dterei's avatar
dterei committed
372

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
373 374 375 376 377 378 379 380
        hsc_NC  :: {-# UNPACK #-} !(IORef NameCache),
                -- ^ As with 'hsc_EPS', this is side-effected by compiling to
                -- reflect sucking in interface files.  They cache the state of
                -- external interface files, in effect.

        hsc_FC   :: {-# UNPACK #-} !(IORef FinderCache),
                -- ^ The cached result of performing finding in the file system
        hsc_MLC  :: {-# UNPACK #-} !(IORef ModLocationCache),
dterei's avatar
dterei committed
381
                -- ^ This caches the location of modules, so we don't have to
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
382
                -- search the filesystem multiple times. See also 'hsc_FC'.
Simon Marlow's avatar
Simon Marlow committed
383

384
        hsc_type_env_var :: Maybe (Module, IORef TypeEnv)
385
                -- ^ Used for one-shot compilation only, to initialise
dterei's avatar
dterei committed
386
                -- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for
387
                -- 'TcRunTypes.TcGblEnv'
388
 }
389

390 391 392 393
instance ContainsDynFlags HscEnv where
    extractDynFlags env = hsc_dflags env
    replaceDynFlags env dflags = env {hsc_dflags = dflags}

dterei's avatar
dterei committed
394
-- | Retrieve the ExternalPackageState cache.
395 396
hscEPS :: HscEnv -> IO ExternalPackageState
hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
397

398 399 400 401 402 403
-- | A compilation target.
--
-- A target may be supplied with the actual text of the
-- module.  If so, use this instead of the file contents (this
-- is for use in an IDE where the file hasn't been saved by
-- the user yet).
dterei's avatar
dterei committed
404 405 406 407
data Target
  = Target {
      targetId           :: TargetId, -- ^ module or filename
      targetAllowObjCode :: Bool,     -- ^ object code allowed?
408
      targetContents     :: Maybe (StringBuffer,UTCTime)
409
                                        -- ^ in-memory text buffer?
dterei's avatar
dterei committed
410
    }
411 412

data TargetId
Simon Marlow's avatar
Simon Marlow committed
413
  = TargetModule ModuleName
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
414
        -- ^ A module name: search for the file
415
  | TargetFile FilePath (Maybe Phase)
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
416 417 418 419
        -- ^ A filename: preprocess & parse it to find the module name.
        -- If specified, the Phase indicates how to compile this file
        -- (which phase to start from).  Nothing indicates the starting phase
        -- should be determined from the suffix of the filename.
420
  deriving Eq
421 422

pprTarget :: Target -> SDoc
dterei's avatar
dterei committed
423
pprTarget (Target id obj _) =
dterei's avatar
dterei committed
424
    (if obj then char '*' else empty) <> pprTargetId id
425

Ian Lynagh's avatar
Ian Lynagh committed
426 427 428
instance Outputable Target where
    ppr = pprTarget

Simon Marlow's avatar
Simon Marlow committed
429
pprTargetId :: TargetId -> SDoc
430
pprTargetId (TargetModule m) = ppr m
431
pprTargetId (TargetFile f _) = text f
432

Ian Lynagh's avatar
Ian Lynagh committed
433 434
instance Outputable TargetId where
    ppr = pprTargetId
dterei's avatar
dterei committed
435
\end{code}
Ian Lynagh's avatar
Ian Lynagh committed
436

dterei's avatar
dterei committed
437 438 439 440 441 442 443
%************************************************************************
%*                                                                      *
\subsection{Package and Module Tables}
%*                                                                      *
%************************************************************************

\begin{code}
444
-- | Helps us find information about modules in the home package
Simon Marlow's avatar
Simon Marlow committed
445
type HomePackageTable  = ModuleNameEnv HomeModInfo
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
446
        -- Domain = modules in the home package that have been fully compiled
447
        -- "home" package key cached here for convenience
448 449

-- | Helps us find information about modules in the imported packages
450
type PackageIfaceTable = ModuleEnv ModIface
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
451
        -- Domain = modules in the imported packages
452

dterei's avatar
dterei committed
453
-- | Constructs an empty HomePackageTable
Simon Marlow's avatar
Simon Marlow committed
454
emptyHomePackageTable :: HomePackageTable
Simon Marlow's avatar
Simon Marlow committed
455
emptyHomePackageTable  = emptyUFM
Simon Marlow's avatar
Simon Marlow committed
456

dterei's avatar
dterei committed
457
-- | Constructs an empty PackageIfaceTable
Simon Marlow's avatar
Simon Marlow committed
458
emptyPackageIfaceTable :: PackageIfaceTable
459 460
emptyPackageIfaceTable = emptyModuleEnv

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
pprHPT :: HomePackageTable -> SDoc
-- A bit aribitrary for now
pprHPT hpt
  = vcat [ hang (ppr (mi_module (hm_iface hm)))
              2 (ppr (md_types (hm_details hm)))
         | hm <- eltsUFM hpt ]

lookupHptByModule :: HomePackageTable -> Module -> Maybe HomeModInfo
-- The HPT is indexed by ModuleName, not Module,
-- we must check for a hit on the right Module
lookupHptByModule hpt mod
  = case lookupUFM hpt (moduleName mod) of
      Just hm | mi_module (hm_iface hm) == mod -> Just hm
      _otherwise                               -> Nothing

476
-- | Information about modules in the package being compiled
dterei's avatar
dterei committed
477
data HomeModInfo
478 479 480 481 482 483
  = HomeModInfo {
      hm_iface    :: !ModIface,
        -- ^ The basic loaded interface file: every loaded module has one of
        -- these, even if it is imported from another package
      hm_details  :: !ModDetails,
        -- ^ Extra information that has been created from the 'ModIface' for
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
484
        -- the module, typically during typechecking
485 486
      hm_linkable :: !(Maybe Linkable)
        -- ^ The actual artifact we would like to link to access things in
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
        -- this module.
        --
        -- 'hm_linkable' might be Nothing:
        --
        --   1. If this is an .hs-boot module
        --
        --   2. Temporarily during compilation if we pruned away
        --      the old linkable because it was out of date.
        --
        -- After a complete compilation ('GHC.load'), all 'hm_linkable' fields
        -- in the 'HomePackageTable' will be @Just@.
        --
        -- When re-linking a module ('HscMain.HscNoRecomp'), we construct the
        -- 'HomeModInfo' by building a new 'ModDetails' from the old
        -- 'ModIface' (only).
502
    }
503

504 505
-- | Find the 'ModIface' for a 'Module', searching in both the loaded home
-- and external package module information
Simon Marlow's avatar
Simon Marlow committed
506
lookupIfaceByModule
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
507 508 509 510 511
        :: DynFlags
        -> HomePackageTable
        -> PackageIfaceTable
        -> Module
        -> Maybe ModIface
512 513 514 515
lookupIfaceByModule _dflags hpt pit mod
  = case lookupHptByModule hpt mod of
       Just hm -> Just (hm_iface hm)
       Nothing -> lookupModuleEnv pit mod
516 517 518 519 520

-- If the module does come from the home package, why do we look in the PIT as well?
-- (a) In OneShot mode, even home-package modules accumulate in the PIT
-- (b) Even in Batch (--make) mode, there is *one* case where a home-package
--     module is in the PIT, namely GHC.Prim when compiling the base package.
521
-- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
522
-- of its own, but it doesn't seem worth the bother.
523

524

525 526 527 528
-- | Find all the instance declarations (of classes and families) from
-- the Home Package Table filtered by the provided predicate function.
-- Used in @tcRnImports@, to select the instances that are in the
-- transitive closure of imports from the currently compiled module.
529
hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([ClsInst], [FamInst])
530
hptInstances hsc_env want_this_module
531 532 533 534 535 536
  = let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do
                guard (want_this_module (moduleName (mi_module (hm_iface mod_info))))
                let details = hm_details mod_info
                return (md_insts details, md_fam_insts details)
    in (concat insts, concat famInsts)

dterei's avatar
dterei committed
537
-- | Get the combined VectInfo of all modules in the home package table. In
538
-- contrast to instances and rules, we don't care whether the modules are
dterei's avatar
dterei committed
539
-- "below" us in the dependency sense. The VectInfo of those modules not "below"
540
-- us does not affect the compilation of the current module.
dterei's avatar
dterei committed
541
hptVectInfo :: HscEnv -> VectInfo
542
hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details)
543

dterei's avatar
dterei committed
544
-- | Get rules from modules "below" this one (in the dependency sense)
Simon Marlow's avatar
Simon Marlow committed
545
hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
546 547
hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False

548

dterei's avatar
dterei committed
549
-- | Get annotations from modules "below" this one (in the dependency sense)
550 551 552 553
hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation]
hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps
hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env

554 555 556
hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a]
hptAllThings extract hsc_env = concatMap extract (eltsUFM (hsc_HPT hsc_env))

dterei's avatar
dterei committed
557
-- | Get things from modules "below" this one (in the dependency sense)
558
-- C.f Inst.hptInstances
dterei's avatar
dterei committed
559
hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a]
560
hptSomeThingsBelowUs extract include_hi_boot hsc_env deps
dterei's avatar
dterei committed
561 562
  | isOneShot (ghcMode (hsc_dflags hsc_env)) = []

563
  | otherwise
dterei's avatar
dterei committed
564
  = let hpt = hsc_HPT hsc_env
565
    in
566
    [ thing
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
567
    |   -- Find each non-hi-boot module below me
568 569
      (mod, is_boot_mod) <- deps
    , include_hi_boot || not is_boot_mod
570

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
571
        -- unsavoury: when compiling the base package with --make, we
dterei's avatar
dterei committed
572
        -- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
573
        -- be in the HPT, because we never compile it; it's in the EPT
dterei's avatar
dterei committed
574
        -- instead. ToDo: clean up, and remove this slightly bogus filter:
Simon Marlow's avatar
Simon Marlow committed
575
    , mod /= moduleName gHC_PRIM
576

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
577
        -- Look it up in the HPT
578
    , let things = case lookupUFM hpt mod of
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
579
                    Just info -> extract info
dterei's avatar
dterei committed
580
                    Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg []
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
581 582 583
          msg = vcat [ptext (sLit "missing module") <+> ppr mod,
                      ptext (sLit "Probable cause: out-of-date interface files")]
                        -- This really shouldn't happen, but see Trac #962
584

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
585
        -- And get its dfuns
586
    , thing <- things ]
587 588 589

hptObjs :: HomePackageTable -> [FilePath]
hptObjs hpt = concat (map (maybe [] linkableObjs . hm_linkable) (eltsUFM hpt))
590
\end{code}
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
591

592
%************************************************************************
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
593
%*                                                                      *
594
\subsection{Dealing with Annotations}
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
595
%*                                                                      *
596 597 598
%************************************************************************

\begin{code}
dterei's avatar
dterei committed
599
-- | Deal with gathering annotations in from all possible places
600
--   and combining them into a single 'AnnEnv'
dterei's avatar
dterei committed
601 602 603 604 605
prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv
prepareAnnotations hsc_env mb_guts = do
    eps <- hscEPS hsc_env
    let -- Extract annotations from the module being compiled if supplied one
        mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts
606 607 608
        -- Extract dependencies of the module if we are supplied one,
        -- otherwise load annotations from all home package table
        -- entries regardless of dependency ordering.
dterei's avatar
dterei committed
609 610
        home_pkg_anns  = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts
        other_pkg_anns = eps_ann_env eps
dterei's avatar
dterei committed
611 612
        ann_env        = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns,
                                                         Just home_pkg_anns,
dterei's avatar
dterei committed
613 614
                                                         Just other_pkg_anns]
    return ann_env
615 616
\end{code}

Simon Marlow's avatar
Simon Marlow committed
617
%************************************************************************
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
618
%*                                                                      *
Simon Marlow's avatar
Simon Marlow committed
619
\subsection{The Finder cache}
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
620
%*                                                                      *
Simon Marlow's avatar
Simon Marlow committed
621 622 623 624
%************************************************************************

\begin{code}
-- | The 'FinderCache' maps home module names to the result of
dterei's avatar
dterei committed
625 626
-- searching for that module. It records the results of searching for
-- modules along the search path. On @:load@, we flush the entire
Simon Marlow's avatar
Simon Marlow committed
627 628
-- contents of this cache.
--
dterei's avatar
dterei committed
629
-- Although the @FinderCache@ range is 'FindResult' for convenience,
Simon Marlow's avatar
Simon Marlow committed
630 631 632 633 634 635 636
-- in fact it will only ever contain 'Found' or 'NotFound' entries.
--
type FinderCache = ModuleNameEnv FindResult

-- | The result of searching for an imported module.
data FindResult
  = Found ModLocation Module
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
637
        -- ^ The module was found
638
  | NoPackage PackageKey
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
639
        -- ^ The requested package was not found
640
  | FoundMultiple [PackageKey]
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
641
        -- ^ _Error_: both in multiple packages
dterei's avatar
dterei committed
642

dterei's avatar
dterei committed
643 644
        -- | Not found
  | NotFound
645 646
      { fr_paths       :: [FilePath]       -- Places where I looked

647
      , fr_pkg         :: Maybe PackageKey  -- Just p => module is in this package's
648 649 650
                                           --           manifest, but couldn't find
                                           --           the .hi file

651
      , fr_mods_hidden :: [PackageKey]      -- Module is in these packages,
652 653
                                           --   but the *module* is hidden

654
      , fr_pkgs_hidden :: [PackageKey]      -- Module is in these packages,
655 656 657 658
                                           --   but the *package* is hidden

      , fr_suggestions :: [Module]         -- Possible mis-spelled modules
      }
Simon Marlow's avatar
Simon Marlow committed
659 660 661 662 663 664

-- | Cache that remembers where we found a particular module.  Contains both
-- home modules and package modules.  On @:load@, only home modules are
-- purged from this cache.
type ModLocationCache = ModuleEnv ModLocation
\end{code}
665

666
%************************************************************************
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
667
%*                                                                      *
668
\subsection{Symbol tables and Module details}
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
669
%*                                                                      *
670 671 672
%************************************************************************

\begin{code}
dterei's avatar
dterei committed
673
-- | A 'ModIface' plus a 'ModDetails' summarises everything we know
674
-- about a compiled module.  The 'ModIface' is the stuff *before* linking,
dterei's avatar
dterei committed
675
-- and can be written out to an interface file. The 'ModDetails is after
676
-- linking and can be completely recovered from just the 'ModIface'.
dterei's avatar
dterei committed
677
--
678 679 680 681
-- When we read an interface file, we also construct a 'ModIface' from it,
-- except that we explicitly make the 'mi_decls' and a few other fields empty;
-- as when reading we consolidate the declarations etc. into a number of indexed
-- maps and environments in the 'ExternalPackageState'.
dterei's avatar
dterei committed
682
data ModIface
dterei's avatar
dterei committed
683 684 685 686
  = ModIface {
        mi_module     :: !Module,             -- ^ Name of the module we are for
        mi_iface_hash :: !Fingerprint,        -- ^ Hash of the whole interface
        mi_mod_hash   :: !Fingerprint,        -- ^ Hash of the ABI only
687 688
        mi_flag_hash  :: !Fingerprint,        -- ^ Hash of the important flags
                                              -- used when compiling this module
689

dterei's avatar
dterei committed
690 691 692
        mi_orphan     :: !WhetherHasOrphans,  -- ^ Whether this module has orphans
        mi_finsts     :: !WhetherHasFamInst,  -- ^ Whether this module has family instances
        mi_boot       :: !IsBootInterface,    -- ^ Read from an hi-boot file?
693

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
694 695 696 697
        mi_deps     :: Dependencies,
                -- ^ The dependencies of the module.  This is
                -- consulted for directly-imported modules, but not
                -- for anything else (hence lazy)
Simon Marlow's avatar
Simon Marlow committed
698

699 700
        mi_usages   :: [Usage],
                -- ^ Usages; kept sorted so that it's easy to decide
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
701 702 703 704
                -- whether to write a new iface file (changing usages
                -- doesn't affect the hash of this module)
                -- NOT STRICT!  we read this field lazily from the interface file
                -- It is *only* consulted by the recompilation checker
705

706
        mi_exports  :: ![IfaceExport],
dterei's avatar
dterei committed
707 708 709
                -- ^ Exports
                -- Kept sorted by (mod,occ), to make version comparisons easier
                -- Records the modules that are the declaration points for things
710
                -- exported by this module, and the 'OccName's of those things
dterei's avatar
dterei committed
711

dterei's avatar
dterei committed
712 713
        mi_exp_hash :: !Fingerprint,
                -- ^ Hash of export list
714

dterei's avatar
dterei committed
715 716 717
        mi_used_th  :: !Bool,
                -- ^ Module required TH splices when it was compiled.
                -- This disables recompilation avoidance (see #481).
718

719
        mi_fixities :: [(OccName,Fixity)],
720
                -- ^ Fixities
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
721
                -- NOT STRICT!  we read this field lazily from the interface file
722

dterei's avatar
dterei committed
723
        mi_warns    :: Warnings,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
724 725
                -- ^ Warnings
                -- NOT STRICT!  we read this field lazily from the interface file
726

dterei's avatar
dterei committed
727
        mi_anns     :: [IfaceAnnotation],
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
728 729
                -- ^ Annotations
                -- NOT STRICT!  we read this field lazily from the interface file
730

dterei's avatar
dterei committed
731 732 733

        mi_decls    :: [(Fingerprint,IfaceDecl)],
                -- ^ Type, class and variable declarations
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
734 735
                -- The hash of an Id changes if its fixity or deprecations change
                --      (as well as its type of course)
dterei's avatar
dterei committed
736
                -- Ditto data constructors, class operations, except that
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
737
                -- the hash of the parent class/tycon changes
738

739
        mi_globals  :: !(Maybe GlobalRdrEnv),
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
                -- ^ Binds all the things defined at the top level in
                -- the /original source/ code for this module. which
                -- is NOT the same as mi_exports, nor mi_decls (which
                -- may contains declarations for things not actually
                -- defined by the user).  Used for GHCi and for inspecting
                -- the contents of modules via the GHC API only.
                --
                -- (We need the source file to figure out the
                -- top-level environment, if we didn't compile this module
                -- from source then this field contains @Nothing@).
                --
                -- Strictly speaking this field should live in the
                -- 'HomeModInfo', but that leads to more plumbing.

                -- Instance declarations and rules
755
        mi_insts       :: [IfaceClsInst],     -- ^ Sorted class instance
dterei's avatar
dterei committed
756 757
        mi_fam_insts   :: [IfaceFamInst],  -- ^ Sorted family instances
        mi_rules       :: [IfaceRule],     -- ^ Sorted rules
758 759
        mi_orphan_hash :: !Fingerprint,    -- ^ Hash for orphan rules, class and family
                                           -- instances, and vectorise pragmas combined
760

dterei's avatar
dterei committed
761
        mi_vect_info :: !IfaceVectInfo,    -- ^ Vectorisation information
762

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
763 764 765
                -- Cached environments for easy lookup
                -- These are computed (lazily) from other fields
                -- and are not put into the interface file
dterei's avatar
dterei committed
766
        mi_warn_fn   :: Name -> Maybe WarningTxt,        -- ^ Cached lookup for 'mi_warns'
767
        mi_fix_fn    :: OccName -> Fixity,               -- ^ Cached lookup for 'mi_fixities'
dterei's avatar
dterei committed
768 769 770 771 772 773 774 775
        mi_hash_fn   :: OccName -> Maybe (OccName, Fingerprint),
                -- ^ Cached lookup for 'mi_decls'.
                -- The @Nothing@ in 'mi_hash_fn' means that the thing
                -- isn't in decls. It's useful to know that when
                -- seeing if we are up to date wrt. the old interface.
                -- The 'OccName' is the parent of the name, if it has one.

        mi_hpc       :: !AnyHpcUsage,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
776
                -- ^ True if this program uses Hpc at any point in the program.
dterei's avatar
dterei committed
777 778

        mi_trust     :: !IfaceTrustInfo,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
779
                -- ^ Safe Haskell Trust information for this module.
dterei's avatar
dterei committed
780

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
781 782 783 784 785 786
        mi_trust_pkg :: !Bool
                -- ^ Do we require the package this module resides in be trusted
                -- to trust this module? This is used for the situation where a
                -- module is Safe (so doesn't require the package be trusted
                -- itself) but imports some trustworthy modules from its own
                -- package (which does require its own package be trusted).
787
                -- See Note [RnNames . Trust Own Package]
788
     }
789

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
instance Binary ModIface where
   put_ bh (ModIface {
                 mi_module    = mod,
                 mi_boot      = is_boot,
                 mi_iface_hash= iface_hash,
                 mi_mod_hash  = mod_hash,
                 mi_flag_hash = flag_hash,
                 mi_orphan    = orphan,
                 mi_finsts    = hasFamInsts,
                 mi_deps      = deps,
                 mi_usages    = usages,
                 mi_exports   = exports,
                 mi_exp_hash  = exp_hash,
                 mi_used_th   = used_th,
                 mi_fixities  = fixities,
                 mi_warns     = warns,
                 mi_anns      = anns,
                 mi_decls     = decls,
                 mi_insts     = insts,
                 mi_fam_insts = fam_insts,
                 mi_rules     = rules,
                 mi_orphan_hash = orphan_hash,
                 mi_vect_info = vect_info,
                 mi_hpc       = hpc_info,
                 mi_trust     = trust,
                 mi_trust_pkg = trust_pkg }) = do
        put_ bh mod
        put_ bh is_boot
        put_ bh iface_hash
        put_ bh mod_hash
        put_ bh flag_hash
        put_ bh orphan
        put_ bh hasFamInsts
        lazyPut bh deps
        lazyPut bh usages
        put_ bh exports
        put_ bh exp_hash
        put_ bh used_th
        put_ bh fixities
        lazyPut bh warns
        lazyPut bh anns
        put_ bh decls
        put_ bh insts
        put_ bh fam_insts
        lazyPut bh rules
        put_ bh orphan_hash
        put_ bh vect_info
        put_ bh hpc_info
        put_ bh trust
        put_ bh trust_pkg

   get bh = do
        mod_name    <- get bh
        is_boot     <- get bh
        iface_hash  <- get bh
        mod_hash    <- get bh
        flag_hash   <- get bh
        orphan      <- get bh
        hasFamInsts <- get bh
        deps        <- lazyGet bh
        usages      <- {-# SCC "bin_usages" #-} lazyGet bh
        exports     <- {-# SCC "bin_exports" #-} get bh
        exp_hash    <- get bh
        used_th     <- get bh
        fixities    <- {-# SCC "bin_fixities" #-} get bh
        warns       <- {-# SCC "bin_warns" #-} lazyGet bh
        anns        <- {-# SCC "bin_anns" #-} lazyGet bh
        decls       <- {-# SCC "bin_tycldecls" #-} get bh
        insts       <- {-# SCC "bin_insts" #-} get bh
        fam_insts   <- {-# SCC "bin_fam_insts" #-} get bh
        rules       <- {-# SCC "bin_rules" #-} lazyGet bh
        orphan_hash <- get bh
        vect_info   <- get bh
        hpc_info    <- get bh
        trust       <- get bh
        trust_pkg   <- get bh
        return (ModIface {
                 mi_module      = mod_name,
                 mi_boot        = is_boot,
                 mi_iface_hash  = iface_hash,
                 mi_mod_hash    = mod_hash,
                 mi_flag_hash   = flag_hash,
                 mi_orphan      = orphan,
                 mi_finsts      = hasFamInsts,
                 mi_deps        = deps,
                 mi_usages      = usages,
                 mi_exports     = exports,
                 mi_exp_hash    = exp_hash,
                 mi_used_th     = used_th,
                 mi_anns        = anns,
                 mi_fixities    = fixities,
                 mi_warns       = warns,
                 mi_decls       = decls,
                 mi_globals     = Nothing,
                 mi_insts       = insts,
                 mi_fam_insts   = fam_insts,
                 mi_rules       = rules,
                 mi_orphan_hash = orphan_hash,
                 mi_vect_info   = vect_info,
                 mi_hpc         = hpc_info,
                 mi_trust       = trust,
                 mi_trust_pkg   = trust_pkg,
                        -- And build the cached values
                 mi_warn_fn     = mkIfaceWarnCache warns,
                 mi_fix_fn      = mkIfaceFixCache fixities,
                 mi_hash_fn     = mkIfaceHashCache decls })

897 898 899
-- | The original names declared of a certain module that are exported
type IfaceExport = AvailInfo

dterei's avatar
dterei committed
900 901 902 903 904 905
-- | Constructs an empty ModIface
emptyModIface :: Module -> ModIface
emptyModIface mod
  = ModIface { mi_module      = mod,
               mi_iface_hash  = fingerprint0,
               mi_mod_hash    = fingerprint0,
906
               mi_flag_hash   = fingerprint0,
dterei's avatar
dterei committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
               mi_orphan      = False,
               mi_finsts      = False,
               mi_boot        = False,
               mi_deps        = noDependencies,
               mi_usages      = [],
               mi_exports     = [],
               mi_exp_hash    = fingerprint0,
               mi_used_th     = False,
               mi_fixities    = [],
               mi_warns       = NoWarnings,
               mi_anns        = [],
               mi_insts       = [],
               mi_fam_insts   = [],
               mi_rules       = [],
               mi_decls       = [],
               mi_globals     = Nothing,
               mi_orphan_hash = fingerprint0,
               mi_vect_info   = noIfaceVectInfo,
               mi_warn_fn     = emptyIfaceWarnCache,
               mi_fix_fn      = emptyIfaceFixCache,
               mi_hash_fn     = emptyIfaceHashCache,
               mi_hpc         = False,
               mi_trust       = noIfaceTrustInfo,
dterei's avatar
dterei committed
930
               mi_trust_pkg   = False }
dterei's avatar
dterei committed
931

932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947

-- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
                 -> (OccName -> Maybe (OccName, Fingerprint))
mkIfaceHashCache pairs
  = \occ -> lookupOccEnv env occ
  where
    env = foldr add_decl emptyOccEnv pairs
    add_decl (v,d) env0 = foldr add env0 (ifaceDeclFingerprints v d)
      where
        add (occ,hash) env0 = extendOccEnv env0 occ (occ,hash)

emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
emptyIfaceHashCache _occ = Nothing


948 949 950
-- | The 'ModDetails' is essentially a cache for information in the 'ModIface'
-- for home modules only. Information relating to packages will be loaded into
-- global environments in 'ExternalPackageState'.
951
data ModDetails
dterei's avatar
dterei committed
952
  = ModDetails {
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
953 954
        -- The next two fields are created by the typechecker
        md_exports   :: [AvailInfo],
955
        md_types     :: !TypeEnv,       -- ^ Local type environment for this particular module
956 957
                                        -- Includes Ids, TyCons, PatSyns
        md_insts     :: ![ClsInst],     -- ^ 'DFunId's for the instances in this module
958
        md_fam_insts :: ![FamInst],
959
        md_rules     :: ![CoreRule],    -- ^ Domain may include 'Id's from other modules
dterei's avatar
dterei committed
960
        md_anns      :: ![Annotation],  -- ^ Annotations present in this module: currently
961
                                        -- they only annotate things also declared in this module
962
        md_vect_info :: !VectInfo       -- ^ Module vectorisation information
963
     }
964

dterei's avatar
dterei committed
965
-- | Constructs an empty ModDetails
Simon Marlow's avatar
Simon Marlow committed
966
emptyModDetails :: ModDetails
dterei's avatar
dterei committed
967 968 969 970 971 972 973
emptyModDetails
  = ModDetails { md_types     = emptyTypeEnv,
                 md_exports   = [],
                 md_insts     = [],
                 md_rules     = [],
                 md_fam_insts = [],
                 md_anns      = [],
dterei's avatar
dterei committed
974
                 md_vect_info = noVectInfo }
975