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