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