FIX #1650: ".boot modules interact badly with the ghci debugger"
[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 {-# OPTIONS -w #-}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
12 -- for details
13
14 module HscTypes ( 
15         -- * Sessions and compilation state
16         Session(..), withSession, modifySession, 
17         HscEnv(..), hscEPS,
18         FinderCache, FindResult(..), ModLocationCache,
19         Target(..), TargetId(..), pprTarget, pprTargetId,
20         ModuleGraph, emptyMG,
21
22         ModDetails(..), emptyModDetails,
23         ModGuts(..), CgGuts(..), ModImports(..), ForeignStubs(..),
24
25         ModSummary(..), ms_mod_name, showModMsg, isBootSummary,
26         msHsFilePath, msHiFilePath, msObjFilePath, 
27
28         HscSource(..), isHsBoot, hscSourceString,       -- Re-exported from DriverPhases
29         
30         HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
31         hptInstances, hptRules, hptVectInfo,
32
33         ExternalPackageState(..), EpsStats(..), addEpsInStats,
34         PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
35         lookupIfaceByModule, emptyModIface,
36
37         InteractiveContext(..), emptyInteractiveContext, 
38         icPrintUnqual, mkPrintUnqualified, extendInteractiveContext,
39         substInteractiveContext,
40
41         ModIface(..), mkIfaceDepCache, mkIfaceVerCache, mkIfaceFixCache,
42         emptyIfaceDepCache,
43
44         Deprecs(..), IfaceDeprecs,
45
46         FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
47
48         implicitTyThings, isImplicitTyThing,
49
50         TyThing(..), tyThingClass, tyThingTyCon, tyThingDataCon, tyThingId,
51         TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
52         extendTypeEnv, extendTypeEnvList, extendTypeEnvWithIds, lookupTypeEnv,
53         typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
54         typeEnvDataCons,
55
56         WhetherHasOrphans, IsBootInterface, Usage(..), 
57         Dependencies(..), noDependencies,
58         NameCache(..), OrigNameCache, OrigIParamCache,
59         Avails, availsToNameSet, availsToNameEnv, availName, availNames,
60         GenAvailInfo(..), AvailInfo, RdrAvailInfo, 
61         IfaceExport,
62
63         Deprecations, DeprecTxt, plusDeprecs,
64
65         PackageInstEnv, PackageRuleBase,
66
67         -- Linker stuff
68         Linkable(..), isObjectLinkable,
69         Unlinked(..), CompiledByteCode,
70         isObject, nameOfObject, isInterpretable, byteCodeOfObject,
71         HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
72
73         -- Breakpoints
74         ModBreaks (..), BreakIndex, emptyModBreaks,
75
76         -- Vectorisation information
77         VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo, 
78         noIfaceVectInfo
79     ) where
80
81 #include "HsVersions.h"
82
83 #ifdef GHCI
84 import ByteCodeAsm      ( CompiledByteCode )
85 import {-# SOURCE #-}  InteractiveEval ( Resume )
86 #endif
87
88 import RdrName          ( GlobalRdrEnv, emptyGlobalRdrEnv, GlobalRdrElt(..), 
89                           mkRdrUnqual, ImpDeclSpec(..), Provenance(..),
90                           ImportSpec(..), lookupGlobalRdrEnv, lookupGRE_RdrName )
91 import Name             ( Name, NamedThing, getName, nameOccName, nameModule )
92 import NameEnv
93 import NameSet  
94 import OccName          ( OccName, OccEnv, lookupOccEnv, mkOccEnv, emptyOccEnv, 
95                           extendOccEnv )
96 import Module
97 import InstEnv          ( InstEnv, Instance )
98 import FamInstEnv       ( FamInstEnv, FamInst )
99 import Rules            ( RuleBase )
100 import CoreSyn          ( CoreBind )
101 import VarEnv
102 import VarSet
103 import Var       hiding ( setIdType )
104 import Id
105 import Type             
106
107 import Class            ( Class, classSelIds, classATs, classTyCon )
108 import TyCon
109 import DataCon          ( DataCon, dataConImplicitIds )
110 import PrelNames        ( gHC_PRIM )
111 import Packages         ( PackageId )
112 import DynFlags         ( DynFlags(..), isOneShot, HscTarget (..) )
113 import DriverPhases     ( HscSource(..), isHsBoot, hscSourceString, Phase )
114 import BasicTypes       ( Version, initialVersion, IPName, 
115                           Fixity, defaultFixity, DeprecTxt )
116 import IfaceSyn
117 import FiniteMap        ( FiniteMap )
118 import CoreSyn          ( CoreRule )
119 import Maybes           ( orElse, expectJust, catMaybes, seqMaybe )
120 import Outputable
121 import BreakArray
122 import SrcLoc           ( SrcSpan, Located )
123 import UniqFM           ( lookupUFM, eltsUFM, emptyUFM )
124 import UniqSupply       ( UniqSupply )
125 import FastString       ( FastString )
126 import StringBuffer     ( StringBuffer )
127
128 import System.Time      ( ClockTime )
129 import Data.IORef
130 import Data.Array       ( Array, array )
131 import Data.List
132 \end{code}
133
134
135 %************************************************************************
136 %*                                                                      *
137 \subsection{Compilation environment}
138 %*                                                                      *
139 %************************************************************************
140
141
142 \begin{code}
143 -- | The Session is a handle to the complete state of a compilation
144 -- session.  A compilation session consists of a set of modules
145 -- constituting the current program or library, the context for
146 -- interactive evaluation, and various caches.
147 newtype Session = Session (IORef HscEnv)
148
149 withSession :: Session -> (HscEnv -> IO a) -> IO a
150 withSession (Session ref) f = do h <- readIORef ref; f h
151
152 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
153 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
154 \end{code}
155
156 HscEnv is like Session, except that some of the fields are immutable.
157 An HscEnv is used to compile a single module from plain Haskell source
158 code (after preprocessing) to either C, assembly or C--.  Things like
159 the module graph don't change during a single compilation.
160
161 Historical note: "hsc" used to be the name of the compiler binary,
162 when there was a separate driver and compiler.  To compile a single
163 module, the driver would invoke hsc on the source code... so nowadays
164 we think of hsc as the layer of the compiler that deals with compiling
165 a single module.
166
167 \begin{code}
168 data HscEnv 
169   = HscEnv { 
170         hsc_dflags :: DynFlags,
171                 -- The dynamic flag settings
172
173         hsc_targets :: [Target],
174                 -- The targets (or roots) of the current session
175
176         hsc_mod_graph :: ModuleGraph,
177                 -- The module graph of the current session
178
179         hsc_IC :: InteractiveContext,
180                 -- The context for evaluating interactive statements
181
182         hsc_HPT    :: HomePackageTable,
183                 -- The home package table describes already-compiled
184                 -- home-packge modules, *excluding* the module we 
185                 -- are compiling right now.
186                 -- (In one-shot mode the current module is the only
187                 --  home-package module, so hsc_HPT is empty.  All other
188                 --  modules count as "external-package" modules.
189                 --  However, even in GHCi mode, hi-boot interfaces are
190                 --  demand-loadeded into the external-package table.)
191                 --
192                 -- hsc_HPT is not mutable because we only demand-load 
193                 -- external packages; the home package is eagerly 
194                 -- loaded, module by module, by the compilation manager.
195                 --      
196                 -- The HPT may contain modules compiled earlier by --make
197                 -- but not actually below the current module in the dependency
198                 -- graph.  (This changes a previous invariant: changed Jan 05.)
199         
200         hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
201         hsc_NC  :: {-# UNPACK #-} !(IORef NameCache),
202                 -- These are side-effected by compiling to reflect
203                 -- sucking in interface files.  They cache the state of
204                 -- external interface files, in effect.
205
206         hsc_FC   :: {-# UNPACK #-} !(IORef FinderCache),
207         hsc_MLC  :: {-# UNPACK #-} !(IORef ModLocationCache),
208                 -- The finder's cache.  This caches the location of modules,
209                 -- so we don't have to search the filesystem multiple times.
210
211         hsc_global_rdr_env :: GlobalRdrEnv,
212         hsc_global_type_env :: TypeEnv
213  }
214
215 hscEPS :: HscEnv -> IO ExternalPackageState
216 hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
217
218 -- | A compilation target.
219 --
220 -- A target may be supplied with the actual text of the
221 -- module.  If so, use this instead of the file contents (this
222 -- is for use in an IDE where the file hasn't been saved by
223 -- the user yet).
224 data Target = Target TargetId (Maybe (StringBuffer,ClockTime))
225
226 data TargetId
227   = TargetModule ModuleName
228         -- ^ A module name: search for the file
229   | TargetFile FilePath (Maybe Phase)
230         -- ^ A filename: preprocess & parse it to find the module name.
231         -- If specified, the Phase indicates how to compile this file
232         -- (which phase to start from).  Nothing indicates the starting phase
233         -- should be determined from the suffix of the filename.
234   deriving Eq
235
236 pprTarget :: Target -> SDoc
237 pprTarget (Target id _) = pprTargetId id
238
239 instance Outputable Target where
240     ppr = pprTarget
241
242 pprTargetId (TargetModule m) = ppr m
243 pprTargetId (TargetFile f _) = text f
244
245 instance Outputable TargetId where
246     ppr = pprTargetId
247
248 type HomePackageTable  = ModuleNameEnv HomeModInfo
249         -- Domain = modules in the home package
250         -- "home" package name cached here for convenience
251 type PackageIfaceTable = ModuleEnv ModIface
252         -- Domain = modules in the imported packages
253
254 emptyHomePackageTable  = emptyUFM
255 emptyPackageIfaceTable = emptyModuleEnv
256
257 data HomeModInfo 
258   = HomeModInfo { hm_iface    :: !ModIface,
259                   hm_details  :: !ModDetails,
260                   hm_linkable :: !(Maybe Linkable) }
261                 -- hm_linkable might be Nothing if:
262                 --   a) this is an .hs-boot module
263                 --   b) temporarily during compilation if we pruned away
264                 --      the old linkable because it was out of date.
265                 -- after a complete compilation (GHC.load), all hm_linkable
266                 -- fields in the HPT will be Just.
267                 --
268                 -- When re-linking a module (hscNoRecomp), we construct
269                 -- the HomModInfo by building a new ModDetails from the
270                 -- old ModIface (only).
271
272 -- | Find the 'ModIface' for a 'Module'
273 lookupIfaceByModule
274         :: DynFlags
275         -> HomePackageTable
276         -> PackageIfaceTable
277         -> Module
278         -> Maybe ModIface
279 lookupIfaceByModule dflags hpt pit mod
280   | modulePackageId mod == thisPackage dflags
281   =     -- The module comes from the home package, so look first
282         -- in the HPT.  If it's not from the home package it's wrong to look
283         -- in the HPT, because the HPT is indexed by *ModuleName* not Module
284     fmap hm_iface (lookupUFM hpt (moduleName mod)) 
285     `seqMaybe` lookupModuleEnv pit mod
286
287   | otherwise = lookupModuleEnv pit mod         -- Look in PIT only 
288
289 -- If the module does come from the home package, why do we look in the PIT as well?
290 -- (a) In OneShot mode, even home-package modules accumulate in the PIT
291 -- (b) Even in Batch (--make) mode, there is *one* case where a home-package
292 --     module is in the PIT, namely GHC.Prim when compiling the base package.
293 -- We could eliminate (b) if we wanted, by making GHC.Prim belong to a packake
294 -- of its own, but it doesn't seem worth the bother.
295 \end{code}
296
297
298 \begin{code}
299 hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([Instance], [FamInst])
300 -- Find all the instance declarations (of classes and families) that are in
301 -- modules imported by this one, directly or indirectly, and are in the Home
302 -- Package Table.  This ensures that we don't see instances from modules --make
303 -- compiled before this one, but which are not below this one.
304 hptInstances hsc_env want_this_module
305   = let (insts, famInsts) = unzip
306           [ (md_insts details, md_fam_insts details)
307           | mod_info <- eltsUFM (hsc_HPT hsc_env)
308           , want_this_module (moduleName (mi_module (hm_iface mod_info)))
309           , let details = hm_details mod_info ]
310     in
311     (concat insts, concat famInsts)
312
313 hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
314 -- Get rules from modules "below" this one (in the dependency sense)
315 -- C.f Inst.hptInstances
316 hptRules hsc_env deps
317   | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
318   | otherwise
319   = let 
320         hpt = hsc_HPT hsc_env
321     in
322     [ rule
323     |   -- Find each non-hi-boot module below me
324       (mod, False) <- deps
325
326         -- unsavoury: when compiling the base package with --make, we
327         -- sometimes try to look up RULES for GHC.Prim.  GHC.Prim won't
328         -- be in the HPT, because we never compile it; it's in the EPT
329         -- instead.  ToDo: clean up, and remove this slightly bogus
330         -- filter:
331     , mod /= moduleName gHC_PRIM
332
333         -- Look it up in the HPT
334     , let rules = case lookupUFM hpt mod of
335                     Just info -> md_rules (hm_details info)
336                     Nothing -> pprTrace "WARNING in hptRules" msg [] 
337           msg = vcat [ptext SLIT("missing module") <+> ppr mod,
338                       ptext SLIT("Probable cause: out-of-date interface files")]
339                         -- This really shouldn't happen, but see Trac #962
340
341         -- And get its dfuns
342     , rule <- rules ]
343
344 hptVectInfo :: HscEnv -> VectInfo
345 -- Get the combined VectInfo of all modules in the home package table.  In
346 -- contrast to instances and rules, we don't care whether the modules are
347 -- "below" or us.  The VectInfo of those modules not "below" us does not
348 -- affect the compilation of the current module.
349 hptVectInfo hsc_env 
350   = foldr plusVectInfo noVectInfo [ md_vect_info (hm_details mod_info)
351                                   | mod_info <- eltsUFM (hsc_HPT hsc_env)]
352 \end{code}
353
354 %************************************************************************
355 %*                                                                      *
356 \subsection{The Finder cache}
357 %*                                                                      *
358 %************************************************************************
359
360 \begin{code}
361 -- | The 'FinderCache' maps home module names to the result of
362 -- searching for that module.  It records the results of searching for
363 -- modules along the search path.  On @:load@, we flush the entire
364 -- contents of this cache.
365 --
366 -- Although the @FinderCache@ range is 'FindResult' for convenience ,
367 -- in fact it will only ever contain 'Found' or 'NotFound' entries.
368 --
369 type FinderCache = ModuleNameEnv FindResult
370
371 -- | The result of searching for an imported module.
372 data FindResult
373   = Found ModLocation Module
374         -- the module was found
375   | NoPackage PackageId
376         -- the requested package was not found
377   | FoundMultiple [PackageId]
378         -- *error*: both in multiple packages
379   | PackageHidden PackageId
380         -- for an explicit source import: the package containing the module is
381         -- not exposed.
382   | ModuleHidden  PackageId
383         -- for an explicit source import: the package containing the module is
384         -- exposed, but the module itself is hidden.
385   | NotFound [FilePath] (Maybe PackageId)
386         -- the module was not found, the specified places were searched
387   | NotFoundInPackage PackageId
388         -- the module was not found in this package
389
390 -- | Cache that remembers where we found a particular module.  Contains both
391 -- home modules and package modules.  On @:load@, only home modules are
392 -- purged from this cache.
393 type ModLocationCache = ModuleEnv ModLocation
394 \end{code}
395
396 %************************************************************************
397 %*                                                                      *
398 \subsection{Symbol tables and Module details}
399 %*                                                                      *
400 %************************************************************************
401
402 A @ModIface@ plus a @ModDetails@ summarises everything we know 
403 about a compiled module.  The @ModIface@ is the stuff *before* linking,
404 and can be written out to an interface file.  (The @ModDetails@ is after 
405 linking; it is the "linked" form of the mi_decls field.)
406
407 When we *read* an interface file, we also construct a @ModIface@ from it,
408 except that the mi_decls part is empty; when reading we consolidate
409 the declarations into a single indexed map in the @PersistentRenamerState@.
410
411 \begin{code}
412 data ModIface 
413    = ModIface {
414         mi_module   :: !Module,
415         mi_mod_vers :: !Version,            -- Module version: changes when anything changes
416
417         mi_orphan   :: !WhetherHasOrphans,  -- Whether this module has orphans
418         mi_finsts   :: !WhetherHasFamInst,  -- Whether module has family insts
419         mi_boot     :: !IsBootInterface,    -- Read from an hi-boot file?
420
421         mi_deps     :: Dependencies,
422                 -- This is consulted for directly-imported modules,
423                 -- but not for anything else (hence lazy)
424
425                 -- Usages; kept sorted so that it's easy to decide
426                 -- whether to write a new iface file (changing usages
427                 -- doesn't affect the version of this module)
428         mi_usages   :: [Usage],
429                 -- NOT STRICT!  we read this field lazily from the interface file
430                 -- It is *only* consulted by the recompilation checker
431
432                 -- Exports
433                 -- Kept sorted by (mod,occ), to make version comparisons easier
434         mi_exports  :: ![IfaceExport],
435         mi_exp_vers :: !Version,        -- Version number of export list
436
437                 -- Fixities
438         mi_fixities :: [(OccName,Fixity)],
439                 -- NOT STRICT!  we read this field lazily from the interface file
440
441                 -- Deprecations
442         mi_deprecs  :: IfaceDeprecs,
443                 -- NOT STRICT!  we read this field lazily from the interface file
444
445                 -- Type, class and variable declarations
446                 -- The version of an Id changes if its fixity or deprecations change
447                 --      (as well as its type of course)
448                 -- Ditto data constructors, class operations, except that 
449                 -- the version of the parent class/tycon changes
450         mi_decls :: [(Version,IfaceDecl)],      -- Sorted
451
452         mi_globals  :: !(Maybe GlobalRdrEnv),
453                 -- Binds all the things defined at the top level in
454                 -- the *original source* code for this module. which
455                 -- is NOT the same as mi_exports, nor mi_decls (which
456                 -- may contains declarations for things not actually
457                 -- defined by the user).  Used for GHCi and for inspecting
458                 -- the contents of modules via the GHC API only.
459                 --
460                 -- (We need the source file to figure out the
461                 -- top-level environment, if we didn't compile this module
462                 -- from source then this field contains Nothing).
463                 --
464                 -- Strictly speaking this field should live in the
465                 -- HomeModInfo, but that leads to more plumbing.
466
467                 -- Instance declarations and rules
468         mi_insts     :: [IfaceInst],                    -- Sorted
469         mi_fam_insts :: [IfaceFamInst],                 -- Sorted
470         mi_rules     :: [IfaceRule],                    -- Sorted
471         mi_rule_vers :: !Version,       -- Version number for rules and 
472                                         -- instances (for classes and families)
473                                         -- combined
474
475                 -- Vectorisation information
476         mi_vect_info :: !IfaceVectInfo,
477
478                 -- Cached environments for easy lookup
479                 -- These are computed (lazily) from other fields
480                 -- and are not put into the interface file
481         mi_dep_fn  :: Name -> Maybe DeprecTxt,  -- Cached lookup for mi_deprecs
482         mi_fix_fn  :: OccName -> Fixity,        -- Cached lookup for mi_fixities
483         mi_ver_fn  :: OccName -> Maybe (OccName, Version),
484                         -- Cached lookup for mi_decls
485                         -- The Nothing in mi_ver_fn means that the thing
486                         -- isn't in decls. It's useful to know that when
487                         -- seeing if we are up to date wrt the old interface
488                         -- The 'OccName' is the parent of the name, if it has one.
489         mi_hpc    :: !AnyHpcUsage
490           -- True if this program uses Hpc at any point in the program.
491      }
492
493 -- Should be able to construct ModDetails from mi_decls in ModIface
494 data ModDetails
495    = ModDetails {
496         -- The next two fields are created by the typechecker
497         md_exports   :: [AvailInfo],
498         md_types     :: !TypeEnv,
499         md_insts     :: ![Instance],  -- Dfun-ids for the instances in this module
500         md_fam_insts :: ![FamInst],
501         md_rules     :: ![CoreRule],  -- Domain may include Ids from other modules
502         md_vect_info :: !VectInfo     -- Vectorisation information
503      }
504
505 emptyModDetails = ModDetails { md_types = emptyTypeEnv,
506                                md_exports = [],
507                                md_insts     = [],
508                                md_rules     = [],
509                                md_fam_insts = [],
510                                md_vect_info = noVectInfo
511                              } 
512
513 -- A ModGuts is carried through the compiler, accumulating stuff as it goes
514 -- There is only one ModGuts at any time, the one for the module
515 -- being compiled right now.  Once it is compiled, a ModIface and 
516 -- ModDetails are extracted and the ModGuts is dicarded.
517
518 data ModGuts
519   = ModGuts {
520         mg_module    :: !Module,
521         mg_boot      :: IsBootInterface, -- Whether it's an hs-boot module
522         mg_exports   :: ![AvailInfo],    -- What it exports
523         mg_deps      :: !Dependencies,   -- What is below it, directly or
524                                          --   otherwise 
525         mg_dir_imps  :: ![Module],       -- Directly-imported modules; used to
526                                          --     generate initialisation code
527         mg_usages    :: ![Usage],        -- Version info for what it needed
528
529         mg_rdr_env   :: !GlobalRdrEnv,   -- Top-level lexical environment
530
531         -- These fields all describe the things **declared in this module**
532         mg_fix_env   :: !FixityEnv,      -- Fixities
533         mg_types     :: !TypeEnv,
534         mg_insts     :: ![Instance],     -- Instances 
535         mg_fam_insts :: ![FamInst],      -- Instances 
536         mg_rules     :: ![CoreRule],     -- Rules from this module
537         mg_binds     :: ![CoreBind],     -- Bindings for this module
538         mg_foreign   :: !ForeignStubs,
539         mg_deprecs   :: !Deprecations,   -- Deprecations declared in the module
540         mg_hpc_info  :: !HpcInfo,        -- info about coverage tick boxes
541         mg_modBreaks :: !ModBreaks,
542         mg_vect_info :: !VectInfo,        -- Pool of vectorised declarations
543
544         -- The next two fields are unusual, because they give instance
545         -- environments for *all* modules in the home package, including
546         -- this module, rather than for *just* this module.  
547         -- Reason: when looking up an instance we don't want to have to
548         --        look at each module in the home package in turn
549         mg_inst_env     :: InstEnv,      -- Class instance enviroment fro
550                                          -- *home-package* modules (including
551                                          -- this one); c.f. tcg_inst_env
552         mg_fam_inst_env :: FamInstEnv    -- Type-family instance enviroment
553                                          -- for *home-package* modules (including
554                                          -- this one); c.f. tcg_fam_inst_env
555     }
556
557 -- The ModGuts takes on several slightly different forms:
558 --
559 -- After simplification, the following fields change slightly:
560 --      mg_rules        Orphan rules only (local ones now attached to binds)
561 --      mg_binds        With rules attached
562
563
564 ---------------------------------------------------------
565 -- The Tidy pass forks the information about this module: 
566 --      * one lot goes to interface file generation (ModIface)
567 --        and later compilations (ModDetails)
568 --      * the other lot goes to code generation (CgGuts)
569 data CgGuts 
570   = CgGuts {
571         cg_module   :: !Module,
572
573         cg_tycons   :: [TyCon],
574                 -- Algebraic data types (including ones that started
575                 -- life as classes); generate constructors and info
576                 -- tables Includes newtypes, just for the benefit of
577                 -- External Core
578
579         cg_binds    :: [CoreBind],
580                 -- The tidied main bindings, including
581                 -- previously-implicit bindings for record and class
582                 -- selectors, and data construtor wrappers.  But *not*
583                 -- data constructor workers; reason: we we regard them
584                 -- as part of the code-gen of tycons
585
586         cg_dir_imps :: ![Module],
587                 -- Directly-imported modules; used to generate
588                 -- initialisation code
589
590         cg_foreign  :: !ForeignStubs,   
591         cg_dep_pkgs :: ![PackageId],    -- Used to generate #includes for C code gen
592         cg_hpc_info :: !HpcInfo,         -- info about coverage tick boxes
593         cg_modBreaks :: !ModBreaks
594     }
595
596 -----------------------------------
597 data ModImports
598   = ModImports {
599         imp_direct     :: ![(Module,Bool)],     -- Explicitly-imported modules
600                                                 -- Boolean is true if we imported the whole
601                                                 --      module (apart, perhaps, from hiding some)
602         imp_pkg_mods   :: !ModuleSet,           -- Non-home-package modules on which we depend,
603                                                 --      directly or indirectly
604         imp_home_names :: !NameSet              -- Home package things on which we depend,
605                                                 --      directly or indirectly
606     }
607
608 -----------------------------------
609 data ForeignStubs = NoStubs
610                   | ForeignStubs
611                         SDoc            -- Header file prototypes for
612                                         --      "foreign exported" functions
613                         SDoc            -- C stubs to use when calling
614                                         --      "foreign exported" functions
615                         [FastString]    -- Headers that need to be included
616                                         --      into C code generated for this module
617
618 \end{code}
619
620 \begin{code}
621 emptyModIface :: Module -> ModIface
622 emptyModIface mod
623   = ModIface { mi_module   = mod,
624                mi_mod_vers = initialVersion,
625                mi_orphan   = False,
626                mi_finsts   = False,
627                mi_boot     = False,
628                mi_deps     = noDependencies,
629                mi_usages   = [],
630                mi_exports  = [],
631                mi_exp_vers = initialVersion,
632                mi_fixities = [],
633                mi_deprecs  = NoDeprecs,
634                mi_insts     = [],
635                mi_fam_insts = [],
636                mi_rules     = [],
637                mi_decls     = [],
638                mi_globals   = Nothing,
639                mi_rule_vers = initialVersion,
640                mi_vect_info = noIfaceVectInfo,
641                mi_dep_fn = emptyIfaceDepCache,
642                mi_fix_fn = emptyIfaceFixCache,
643                mi_ver_fn = emptyIfaceVerCache,
644                mi_hpc    = False
645     }           
646 \end{code}
647
648
649 %************************************************************************
650 %*                                                                      *
651 \subsection{The interactive context}
652 %*                                                                      *
653 %************************************************************************
654
655 \begin{code}
656 data InteractiveContext 
657   = InteractiveContext { 
658         ic_toplev_scope :: [Module],    -- Include the "top-level" scope of
659                                         -- these modules
660
661         ic_exports :: [Module],         -- Include just the exports of these
662                                         -- modules
663
664         ic_rn_gbl_env :: GlobalRdrEnv,  -- The cached GlobalRdrEnv, built from
665                                         -- ic_toplev_scope and ic_exports
666
667         ic_tmp_ids :: [Id],             -- Names bound during interaction.
668                                         -- Later Ids shadow
669                                         -- earlier ones with the same OccName.
670
671         ic_tyvars :: TyVarSet           -- skolem type variables free in
672                                         -- ic_tmp_ids.  These arise at
673                                         -- breakpoints in a polymorphic 
674                                         -- context, where we have only partial
675                                         -- type information.
676
677 #ifdef GHCI
678         , ic_resume :: [Resume]         -- the stack of breakpoint contexts
679 #endif
680     }
681
682
683 emptyInteractiveContext
684   = InteractiveContext { ic_toplev_scope = [],
685                          ic_exports = [],
686                          ic_rn_gbl_env = emptyGlobalRdrEnv,
687                          ic_tmp_ids = [],
688                          ic_tyvars = emptyVarSet
689 #ifdef GHCI
690                          , ic_resume = []
691 #endif
692                        }
693
694 icPrintUnqual :: InteractiveContext -> PrintUnqualified
695 icPrintUnqual ictxt = mkPrintUnqualified (ic_rn_gbl_env ictxt)
696
697
698 extendInteractiveContext
699         :: InteractiveContext
700         -> [Id]
701         -> TyVarSet
702         -> InteractiveContext
703 extendInteractiveContext ictxt ids tyvars
704   = ictxt { ic_tmp_ids =  ic_tmp_ids ictxt ++ ids,
705                           -- NB. must be this way around, because we want
706                           -- new ids to shadow existing bindings.
707             ic_tyvars   = ic_tyvars ictxt `unionVarSet` tyvars }
708
709
710 substInteractiveContext :: InteractiveContext -> TvSubst -> InteractiveContext
711 substInteractiveContext ictxt subst | isEmptyTvSubst subst = ictxt
712 substInteractiveContext ictxt@InteractiveContext{ic_tmp_ids=ids} subst =
713    let ids'     = map (\id -> id `setIdType` substTy subst (idType id)) ids
714        subst_dom= varEnvKeys$ getTvSubstEnv subst
715        subst_ran= varEnvElts$ getTvSubstEnv subst
716        new_tvs  = [ tv | Just tv <- map getTyVar_maybe subst_ran]  
717        ic_tyvars'= (`delVarSetListByKey` subst_dom) 
718                  . (`extendVarSetList`   new_tvs)
719                    $ ic_tyvars ictxt
720     in ictxt { ic_tmp_ids = ids'
721              , ic_tyvars   = ic_tyvars' }
722
723           where delVarSetListByKey = foldl' delVarSetByKey
724 \end{code}
725
726 %************************************************************************
727 %*                                                                      *
728         Building a PrintUnqualified             
729 %*                                                                      *
730 %************************************************************************
731
732 \begin{code}
733 mkPrintUnqualified :: GlobalRdrEnv -> PrintUnqualified
734 mkPrintUnqualified env = (qual_name, qual_mod)
735   where
736   qual_name mod occ     -- The (mod,occ) pair is the original name of the thing
737         | [gre] <- unqual_gres, right_name gre = Nothing
738                 -- If there's a unique entity that's in scope unqualified with 'occ'
739                 -- AND that entity is the right one, then we can use the unqualified name
740
741         | [gre] <- qual_gres = Just (get_qual_mod (gre_prov gre))
742
743         | null qual_gres = Just (moduleName mod)
744                 -- it isn't in scope at all, this probably shouldn't happen,
745                 -- but we'll qualify it by the original module anyway.
746
747         | otherwise = panic "mkPrintUnqualified"
748       where
749         right_name gre = nameModule (gre_name gre) == mod
750
751         unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
752         qual_gres   = filter right_name (lookupGlobalRdrEnv env occ)
753
754         get_qual_mod LocalDef      = moduleName mod
755         get_qual_mod (Imported is) = ASSERT( not (null is) ) is_as (is_decl (head is))
756
757   qual_mod mod = Nothing       -- For now, we never qualify module names with their packages
758 \end{code}
759
760
761 %************************************************************************
762 %*                                                                      *
763                 TyThing
764 %*                                                                      *
765 %************************************************************************
766
767 \begin{code}
768 implicitTyThings :: TyThing -> [TyThing]
769 -- If you change this, make sure you change LoadIface.ifaceDeclSubBndrs in sync
770
771 implicitTyThings (AnId id)   = []
772
773         -- For type constructors, add the data cons (and their extras),
774         -- and the selectors and generic-programming Ids too
775         --
776         -- Newtypes don't have a worker Id, so don't generate that?
777 implicitTyThings (ATyCon tc) = implicitCoTyCon tc ++
778                                map AnId (tyConSelIds tc) ++ 
779                                concatMap (extras_plus . ADataCon) 
780                                          (tyConDataCons tc)
781                      
782         -- For classes, add the class selector Ids, and assoicated TyCons
783         -- and the class TyCon too (and its extras)
784 implicitTyThings (AClass cl) 
785   = map AnId (classSelIds cl) ++
786     map ATyCon (classATs cl) ++
787         -- No extras_plus for the classATs, because they
788         -- are only the family decls; they have no implicit things
789     extras_plus (ATyCon (classTyCon cl))
790
791         -- For data cons add the worker and wrapper (if any)
792 implicitTyThings (ADataCon dc) = map AnId (dataConImplicitIds dc)
793
794 -- | returns 'True' if there should be no interface-file declaration
795 -- for this thing on its own: either it is built-in, or it is part
796 -- of some other declaration, or it is generated implicitly by some
797 -- other declaration.
798 isImplicitTyThing :: TyThing -> Bool
799 isImplicitTyThing (ADataCon _)  = True
800 isImplicitTyThing (AnId     id) = isImplicitId id
801 isImplicitTyThing (AClass   _)  = False
802 isImplicitTyThing (ATyCon   tc) = isImplicitTyCon tc
803
804         -- For newtypes and indexed data types, add the implicit coercion tycon
805 implicitCoTyCon tc 
806   = map ATyCon . catMaybes $ [newTyConCo_maybe tc, 
807                               tyConFamilyCoercion_maybe tc]
808
809 extras_plus thing = thing : implicitTyThings thing
810
811 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
812 extendTypeEnvWithIds env ids
813   = extendNameEnvList env [(getName id, AnId id) | id <- ids]
814 \end{code}
815
816 %************************************************************************
817 %*                                                                      *
818                 TypeEnv
819 %*                                                                      *
820 %************************************************************************
821
822 \begin{code}
823 type TypeEnv = NameEnv TyThing
824
825 emptyTypeEnv    :: TypeEnv
826 typeEnvElts     :: TypeEnv -> [TyThing]
827 typeEnvClasses  :: TypeEnv -> [Class]
828 typeEnvTyCons   :: TypeEnv -> [TyCon]
829 typeEnvIds      :: TypeEnv -> [Id]
830 typeEnvDataCons :: TypeEnv -> [DataCon]
831 lookupTypeEnv   :: TypeEnv -> Name -> Maybe TyThing
832
833 emptyTypeEnv        = emptyNameEnv
834 typeEnvElts     env = nameEnvElts env
835 typeEnvClasses  env = [cl | AClass cl   <- typeEnvElts env]
836 typeEnvTyCons   env = [tc | ATyCon tc   <- typeEnvElts env] 
837 typeEnvIds      env = [id | AnId id     <- typeEnvElts env] 
838 typeEnvDataCons env = [dc | ADataCon dc <- typeEnvElts env] 
839
840 mkTypeEnv :: [TyThing] -> TypeEnv
841 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
842                 
843 lookupTypeEnv = lookupNameEnv
844
845 -- Extend the type environment
846 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
847 extendTypeEnv env thing = extendNameEnv env (getName thing) thing 
848
849 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
850 extendTypeEnvList env things = foldl extendTypeEnv env things
851 \end{code}
852
853 \begin{code}
854 lookupType :: DynFlags
855            -> HomePackageTable
856            -> PackageTypeEnv
857            -> Name
858            -> Maybe TyThing
859
860 lookupType dflags hpt pte name
861   -- in one-shot, we don't use the HPT
862   | not (isOneShot (ghcMode dflags)) && modulePackageId mod == this_pkg 
863   = do hm <- lookupUFM hpt (moduleName mod) -- Maybe monad
864        lookupNameEnv (md_types (hm_details hm)) name
865   | otherwise
866   = lookupNameEnv pte name
867   where mod = nameModule name
868         this_pkg = thisPackage dflags
869 \end{code}
870
871 \begin{code}
872 tyThingTyCon (ATyCon tc) = tc
873 tyThingTyCon other       = pprPanic "tyThingTyCon" (ppr other)
874
875 tyThingClass (AClass cls) = cls
876 tyThingClass other        = pprPanic "tyThingClass" (ppr other)
877
878 tyThingDataCon (ADataCon dc) = dc
879 tyThingDataCon other         = pprPanic "tyThingDataCon" (ppr other)
880
881 tyThingId (AnId id) = id
882 tyThingId other     = pprPanic "tyThingId" (ppr other)
883 \end{code}
884
885 %************************************************************************
886 %*                                                                      *
887 \subsection{Auxiliary types}
888 %*                                                                      *
889 %************************************************************************
890
891 These types are defined here because they are mentioned in ModDetails,
892 but they are mostly elaborated elsewhere
893
894 \begin{code}
895 mkIfaceVerCache :: [(Version,IfaceDecl)]
896                 -> (OccName -> Maybe (OccName, Version))
897 mkIfaceVerCache pairs 
898   = \occ -> lookupOccEnv env occ
899   where
900     env = foldr add_decl emptyOccEnv pairs
901     add_decl (v,d) env0 = foldr add_imp env1 (ifaceDeclSubBndrs d)
902       where
903           decl_name = ifName d
904           env1 = extendOccEnv env0 decl_name (decl_name, v)
905           add_imp bndr env = extendOccEnv env bndr (decl_name, v)
906
907 emptyIfaceVerCache :: OccName -> Maybe (OccName, Version)
908 emptyIfaceVerCache occ = Nothing
909
910 ------------------ Deprecations -------------------------
911 data Deprecs a
912   = NoDeprecs
913   | DeprecAll DeprecTxt -- Whole module deprecated
914   | DeprecSome a        -- Some specific things deprecated
915   deriving( Eq )
916
917 type IfaceDeprecs = Deprecs [(OccName,DeprecTxt)]
918 type Deprecations = Deprecs (NameEnv (OccName,DeprecTxt))
919         -- Keep the OccName so we can flatten the NameEnv to
920         -- get an IfaceDeprecs from a Deprecations
921         -- Only an OccName is needed, because a deprecation always
922         -- applies to things defined in the module in which the
923         -- deprecation appears.
924
925 mkIfaceDepCache:: IfaceDeprecs -> Name -> Maybe DeprecTxt
926 mkIfaceDepCache NoDeprecs         = \n -> Nothing
927 mkIfaceDepCache (DeprecAll t)     = \n -> Just t
928 mkIfaceDepCache (DeprecSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
929
930 emptyIfaceDepCache :: Name -> Maybe DeprecTxt
931 emptyIfaceDepCache n = Nothing
932
933 plusDeprecs :: Deprecations -> Deprecations -> Deprecations
934 plusDeprecs d NoDeprecs = d
935 plusDeprecs NoDeprecs d = d
936 plusDeprecs d (DeprecAll t) = DeprecAll t
937 plusDeprecs (DeprecAll t) d = DeprecAll t
938 plusDeprecs (DeprecSome v1) (DeprecSome v2) = DeprecSome (v1 `plusNameEnv` v2)
939 \end{code}
940
941
942 \begin{code}
943 type Avails       = [AvailInfo]
944 type AvailInfo    = GenAvailInfo Name
945 type RdrAvailInfo = GenAvailInfo OccName
946
947 data GenAvailInfo name  = Avail name     -- An ordinary identifier
948                         | AvailTC name   -- The name of the type or class
949                                   [name] -- The available pieces of type/class.
950                                          -- NB: If the type or class is itself
951                                          -- to be in scope, it must be in this list.
952                                          -- Thus, typically: AvailTC Eq [Eq, ==, /=]
953                         deriving( Eq )
954                         -- Equality used when deciding if the interface has changed
955
956 type IfaceExport = (Module, [GenAvailInfo OccName])
957
958 availsToNameSet :: [AvailInfo] -> NameSet
959 availsToNameSet avails = foldr add emptyNameSet avails
960       where add avail set = addListToNameSet set (availNames avail)
961
962 availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo
963 availsToNameEnv avails = foldr add emptyNameEnv avails
964      where add avail env = extendNameEnvList env
965                                 (zip (availNames avail) (repeat avail))
966
967 availName :: GenAvailInfo name -> name
968 availName (Avail n)     = n
969 availName (AvailTC n _) = n
970
971 availNames :: GenAvailInfo name -> [name]
972 availNames (Avail n)      = [n]
973 availNames (AvailTC n ns) = ns
974
975 instance Outputable n => Outputable (GenAvailInfo n) where
976    ppr = pprAvail
977
978 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
979 pprAvail (Avail n)      = ppr n
980 pprAvail (AvailTC n ns) = ppr n <> braces (hsep (punctuate comma (map ppr ns)))
981 \end{code}
982
983 \begin{code}
984 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
985 mkIfaceFixCache pairs 
986   = \n -> lookupOccEnv env n `orElse` defaultFixity
987   where
988    env = mkOccEnv pairs
989
990 emptyIfaceFixCache :: OccName -> Fixity
991 emptyIfaceFixCache n = defaultFixity
992
993 -- This fixity environment is for source code only
994 type FixityEnv = NameEnv FixItem
995
996 -- We keep the OccName in the range so that we can generate an interface from it
997 data FixItem = FixItem OccName Fixity SrcSpan
998
999 instance Outputable FixItem where
1000   ppr (FixItem occ fix loc) = ppr fix <+> ppr occ <+> parens (ppr loc)
1001
1002 emptyFixityEnv :: FixityEnv
1003 emptyFixityEnv = emptyNameEnv
1004
1005 lookupFixity :: FixityEnv -> Name -> Fixity
1006 lookupFixity env n = case lookupNameEnv env n of
1007                         Just (FixItem _ fix _) -> fix
1008                         Nothing                -> defaultFixity
1009 \end{code}
1010
1011
1012 %************************************************************************
1013 %*                                                                      *
1014 \subsection{WhatsImported}
1015 %*                                                                      *
1016 %************************************************************************
1017
1018 \begin{code}
1019 type WhetherHasOrphans   = Bool
1020         -- An "orphan" is 
1021         --      * an instance decl in a module other than the defn module for 
1022         --              one of the tycons or classes in the instance head
1023         --      * a transformation rule in a module other than the one defining
1024         --              the function in the head of the rule.
1025
1026 type WhetherHasFamInst = Bool        -- This module defines family instances?
1027
1028 type IsBootInterface = Bool
1029
1030 -- Dependency info about modules and packages below this one
1031 -- in the import hierarchy.  See TcRnTypes.ImportAvails for details.
1032 -- The orphan modules in `dep_orphs' do *not* include family instance orphans,
1033 -- as they are anyway included in `dep_finsts'.
1034 --
1035 -- Invariant: the dependencies of a module M never includes M
1036 -- Invariant: the lists are unordered, with no duplicates
1037 data Dependencies
1038   = Deps { dep_mods   :: [(ModuleName,      -- Home-package module dependencies
1039                            IsBootInterface)]
1040          , dep_pkgs   :: [PackageId]        -- External package dependencies
1041          , dep_orphs  :: [Module]           -- Orphan modules (whether home or
1042                                             -- external pkg)
1043          , dep_finsts :: [Module]           -- Modules that contain family
1044                                             -- instances (whether home or
1045                                             -- external pkg)
1046          }
1047   deriving( Eq )
1048         -- Equality used only for old/new comparison in MkIface.addVersionInfo
1049
1050 noDependencies :: Dependencies
1051 noDependencies = Deps [] [] [] []
1052           
1053 data Usage
1054   = Usage { usg_name     :: ModuleName,                 -- Name of the module
1055             usg_mod      :: Version,                    -- Module version
1056             usg_entities :: [(OccName,Version)],        -- Sorted by occurrence name
1057                 -- NB. usages are for parent names only, eg. tycon but not constructors.
1058             usg_exports  :: Maybe Version,              -- Export-list version, if we depend on it
1059             usg_rules    :: Version                     -- Orphan-rules version (for non-orphan
1060                                                         -- modules this will always be initialVersion)
1061     }       deriving( Eq )
1062         -- This type doesn't let you say "I imported f but none of the rules in
1063         -- the module". If you use anything in the module you get its rule version
1064         -- So if the rules change, you'll recompile, even if you don't use them.
1065         -- This is easy to implement, and it's safer: you might not have used the rules last
1066         -- time round, but if someone has added a new rule you might need it this time
1067
1068         -- The export list field is (Just v) if we depend on the export list:
1069         --      i.e. we imported the module directly, whether or not we
1070         --           enumerated the things we imported, or just imported everything
1071         -- We need to recompile if M's exports change, because 
1072         -- if the import was    import M,       we might now have a name clash in the 
1073         --                                      importing module.
1074         -- if the import was    import M(x)     M might no longer export x
1075         -- The only way we don't depend on the export list is if we have
1076         --                      import M()
1077         -- And of course, for modules that aren't imported directly we don't
1078         -- depend on their export lists
1079 \end{code}
1080
1081
1082 %************************************************************************
1083 %*                                                                      *
1084                 The External Package State
1085 %*                                                                      *
1086 %************************************************************************
1087
1088 \begin{code}
1089 type PackageTypeEnv    = TypeEnv
1090 type PackageRuleBase   = RuleBase
1091 type PackageInstEnv    = InstEnv
1092 type PackageFamInstEnv = FamInstEnv
1093 type PackageVectInfo   = VectInfo
1094
1095 data ExternalPackageState
1096   = EPS {
1097         eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
1098                 -- In OneShot mode (only), home-package modules
1099                 -- accumulate in the external package state, and are
1100                 -- sucked in lazily.  For these home-pkg modules
1101                 -- (only) we need to record which are boot modules.
1102                 -- We set this field after loading all the
1103                 -- explicitly-imported interfaces, but before doing
1104                 -- anything else
1105                 --
1106                 -- The ModuleName part is not necessary, but it's useful for
1107                 -- debug prints, and it's convenient because this field comes
1108                 -- direct from TcRnTypes.ImportAvails.imp_dep_mods
1109
1110         eps_PIT :: !PackageIfaceTable,
1111                 -- The ModuleIFaces for modules in external packages
1112                 -- whose interfaces we have opened
1113                 -- The declarations in these interface files are held in
1114                 -- eps_decls, eps_inst_env, eps_fam_inst_env, eps_rules
1115                 -- (below), not in the mi_decls fields of the iPIT.  
1116                 -- What _is_ in the iPIT is:
1117                 --      * The Module 
1118                 --      * Version info
1119                 --      * Its exports
1120                 --      * Fixities
1121                 --      * Deprecations
1122
1123         eps_PTE :: !PackageTypeEnv,        -- Domain = external-package modules
1124
1125         eps_inst_env     :: !PackageInstEnv,   -- The total InstEnv accumulated
1126                                                -- from all the external-package
1127                                                -- modules 
1128         eps_fam_inst_env :: !PackageFamInstEnv,-- Ditto FamInstEnv
1129         eps_rule_base    :: !PackageRuleBase,  -- Ditto RuleEnv
1130         eps_vect_info    :: !PackageVectInfo,  -- Ditto VectInfo
1131
1132         eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- identifies family
1133                                                        -- instances of each mod 
1134         eps_stats :: !EpsStats
1135   }
1136
1137 -- "In" means read from iface files
1138 -- "Out" means actually sucked in and type-checked
1139 data EpsStats = EpsStats { n_ifaces_in
1140                          , n_decls_in, n_decls_out 
1141                          , n_rules_in, n_rules_out
1142                          , n_insts_in, n_insts_out :: !Int }
1143
1144 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
1145 -- Add stats for one newly-read interface
1146 addEpsInStats stats n_decls n_insts n_rules
1147   = stats { n_ifaces_in = n_ifaces_in stats + 1
1148           , n_decls_in  = n_decls_in stats + n_decls
1149           , n_insts_in  = n_insts_in stats + n_insts
1150           , n_rules_in  = n_rules_in stats + n_rules }
1151 \end{code}
1152
1153 The NameCache makes sure that there is just one Unique assigned for
1154 each original name; i.e. (module-name, occ-name) pair.  The Name is
1155 always stored as a Global, and has the SrcLoc of its binding location.
1156 Actually that's not quite right.  When we first encounter the original
1157 name, we might not be at its binding site (e.g. we are reading an
1158 interface file); so we give it 'noSrcLoc' then.  Later, when we find
1159 its binding site, we fix it up.
1160
1161 \begin{code}
1162 data NameCache
1163  = NameCache {  nsUniqs :: UniqSupply,
1164                 -- Supply of uniques
1165                 nsNames :: OrigNameCache,
1166                 -- Ensures that one original name gets one unique
1167                 nsIPs   :: OrigIParamCache
1168                 -- Ensures that one implicit parameter name gets one unique
1169    }
1170
1171 type OrigNameCache   = ModuleEnv (OccEnv Name)
1172 type OrigIParamCache = FiniteMap (IPName OccName) (IPName Name)
1173 \end{code}
1174
1175
1176
1177 %************************************************************************
1178 %*                                                                      *
1179                 The module graph and ModSummary type
1180         A ModSummary is a node in the compilation manager's
1181         dependency graph, and it's also passed to hscMain
1182 %*                                                                      *
1183 %************************************************************************
1184
1185 A ModuleGraph contains all the nodes from the home package (only).  
1186 There will be a node for each source module, plus a node for each hi-boot
1187 module.
1188
1189 \begin{code}
1190 type ModuleGraph = [ModSummary]  -- The module graph, 
1191                                  -- NOT NECESSARILY IN TOPOLOGICAL ORDER
1192
1193 emptyMG :: ModuleGraph
1194 emptyMG = []
1195
1196 -- The nodes of the module graph are
1197 --      EITHER a regular Haskell source module
1198 --      OR     a hi-boot source module
1199
1200 data ModSummary
1201    = ModSummary {
1202         ms_mod       :: Module,                 -- Identity of the module
1203         ms_hsc_src   :: HscSource,              -- Source is Haskell, hs-boot, external core
1204         ms_location  :: ModLocation,            -- Location
1205         ms_hs_date   :: ClockTime,              -- Timestamp of source file
1206         ms_obj_date  :: Maybe ClockTime,        -- Timestamp of object, maybe
1207         ms_srcimps   :: [Located ModuleName],   -- Source imports
1208         ms_imps      :: [Located ModuleName],   -- Non-source imports
1209         ms_hspp_file :: FilePath,               -- Filename of preprocessed source.
1210         ms_hspp_opts :: DynFlags,               -- Cached flags from OPTIONS, INCLUDE
1211                                                 -- and LANGUAGE pragmas.
1212         ms_hspp_buf  :: Maybe StringBuffer      -- The actual preprocessed source, maybe.
1213      }
1214
1215 ms_mod_name :: ModSummary -> ModuleName
1216 ms_mod_name = moduleName . ms_mod
1217
1218 -- The ModLocation contains both the original source filename and the
1219 -- filename of the cleaned-up source file after all preprocessing has been
1220 -- done.  The point is that the summariser will have to cpp/unlit/whatever
1221 -- all files anyway, and there's no point in doing this twice -- just 
1222 -- park the result in a temp file, put the name of it in the location,
1223 -- and let @compile@ read from that file on the way back up.
1224
1225 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
1226 -- the ms_hs_date and imports can, of course, change
1227
1228 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
1229 msHsFilePath  ms = expectJust "msHsFilePath" (ml_hs_file  (ms_location ms))
1230 msHiFilePath  ms = ml_hi_file  (ms_location ms)
1231 msObjFilePath ms = ml_obj_file (ms_location ms)
1232
1233 isBootSummary :: ModSummary -> Bool
1234 isBootSummary ms = isHsBoot (ms_hsc_src ms)
1235
1236 instance Outputable ModSummary where
1237    ppr ms
1238       = sep [text "ModSummary {",
1239              nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1240                           text "ms_mod =" <+> ppr (ms_mod ms) 
1241                                 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
1242                           text "ms_imps =" <+> ppr (ms_imps ms),
1243                           text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1244              char '}'
1245             ]
1246
1247 showModMsg :: HscTarget -> Bool -> ModSummary -> String
1248 showModMsg target recomp mod_summary
1249   = showSDoc (hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
1250                     char '(', text (msHsFilePath mod_summary) <> comma,
1251                     case target of
1252                       HscInterpreted | recomp 
1253                                  -> text "interpreted"
1254                       HscNothing -> text "nothing"
1255                       _other     -> text (msObjFilePath mod_summary),
1256                     char ')'])
1257  where 
1258     mod     = moduleName (ms_mod mod_summary)
1259     mod_str = showSDoc (ppr mod) ++ hscSourceString (ms_hsc_src mod_summary)
1260 \end{code}
1261
1262
1263 %************************************************************************
1264 %*                                                                      *
1265 \subsection{Hpc Support}
1266 %*                                                                      *
1267 %************************************************************************
1268
1269 \begin{code}
1270 data HpcInfo 
1271   = HpcInfo 
1272      { hpcInfoTickCount :: Int 
1273      , hpcInfoHash      :: Int  
1274      }
1275   | NoHpcInfo 
1276      { hpcUsed          :: AnyHpcUsage  -- is hpc used anywhere on the module tree?
1277      }
1278
1279 -- This is used to mean there is no module-local hpc usage,
1280 -- but one of my imports used hpc instrumentation.
1281
1282 type AnyHpcUsage = Bool
1283
1284 emptyHpcInfo :: AnyHpcUsage -> HpcInfo
1285 emptyHpcInfo = NoHpcInfo 
1286
1287 isHpcUsed :: HpcInfo -> AnyHpcUsage
1288 isHpcUsed (HpcInfo {})                   = True
1289 isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
1290 \end{code}
1291
1292 %************************************************************************
1293 %*                                                                      *
1294 \subsection{Vectorisation Support}
1295 %*                                                                      *
1296 %************************************************************************
1297
1298 The following information is generated and consumed by the vectorisation
1299 subsystem.  It communicates the vectorisation status of declarations from one
1300 module to another.
1301
1302 Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
1303 below?  We need to know `f' when converting to IfaceVectInfo.  However, during
1304 vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
1305 on just the OccName easily in a Core pass.
1306
1307 \begin{code}
1308 -- ModGuts/ModDetails/EPS version
1309 data VectInfo      
1310   = VectInfo {
1311       vectInfoVar     :: VarEnv  (Var    , Var  ),   -- (f, f_v) keyed on f
1312       vectInfoTyCon   :: NameEnv (TyCon  , TyCon),   -- (T, T_v) keyed on T
1313       vectInfoDataCon :: NameEnv (DataCon, DataCon), -- (C, C_v) keyed on C
1314       vectInfoPADFun  :: NameEnv (TyCon  , Var),     -- (T_v, paT) keyed on T_v
1315       vectInfoIso     :: NameEnv (TyCon  , Var)      -- (T, isoT) keyed on T
1316     }
1317     -- all of this is always tidy, even in ModGuts
1318
1319 -- ModIface version
1320 data IfaceVectInfo 
1321   = IfaceVectInfo {
1322       ifaceVectInfoVar        :: [Name],
1323         -- all variables in here have a vectorised variant;
1324         -- the name of the vectorised variant is determined by `mkCloVect'
1325       ifaceVectInfoTyCon      :: [Name],
1326         -- all tycons in here have a vectorised variant;
1327         -- the name of the vectorised variant and those of its
1328         -- data constructors are determined by `mkVectTyConOcc'
1329         -- and `mkVectDataConOcc'; the names of
1330         -- the isomorphisms is determined by `mkVectIsoOcc'
1331       ifaceVectInfoTyConReuse :: [Name]              
1332         -- the vectorised form of all the tycons in here coincids with
1333         -- the unconverted from; the names of the isomorphisms is determined
1334         -- by `mkVectIsoOcc'
1335     }
1336
1337 noVectInfo :: VectInfo
1338 noVectInfo = VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyNameEnv emptyNameEnv
1339
1340 plusVectInfo :: VectInfo -> VectInfo -> VectInfo
1341 plusVectInfo vi1 vi2 = 
1342   VectInfo (vectInfoVar     vi1 `plusVarEnv`  vectInfoVar     vi2)
1343            (vectInfoTyCon   vi1 `plusNameEnv` vectInfoTyCon   vi2)
1344            (vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
1345            (vectInfoPADFun  vi1 `plusNameEnv` vectInfoPADFun  vi2)
1346            (vectInfoIso     vi1 `plusNameEnv` vectInfoIso     vi2)
1347
1348 noIfaceVectInfo :: IfaceVectInfo
1349 noIfaceVectInfo = IfaceVectInfo [] [] []
1350 \end{code}
1351
1352 %************************************************************************
1353 %*                                                                      *
1354 \subsection{Linkable stuff}
1355 %*                                                                      *
1356 %************************************************************************
1357
1358 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
1359 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
1360
1361 \begin{code}
1362 data Linkable = LM {
1363   linkableTime     :: ClockTime,        -- Time at which this linkable was built
1364                                         -- (i.e. when the bytecodes were produced,
1365                                         --       or the mod date on the files)
1366   linkableModule   :: Module,           -- Should be Module, but see below
1367   linkableUnlinked :: [Unlinked]
1368  }
1369
1370 isObjectLinkable :: Linkable -> Bool
1371 isObjectLinkable l = not (null unlinked) && all isObject unlinked
1372   where unlinked = linkableUnlinked l
1373         -- A linkable with no Unlinked's is treated as a BCO.  We can
1374         -- generate a linkable with no Unlinked's as a result of
1375         -- compiling a module in HscNothing mode, and this choice
1376         -- happens to work well with checkStability in module GHC.
1377
1378 instance Outputable Linkable where
1379    ppr (LM when_made mod unlinkeds)
1380       = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
1381         $$ nest 3 (ppr unlinkeds)
1382
1383 -------------------------------------------
1384 data Unlinked
1385    = DotO FilePath
1386    | DotA FilePath
1387    | DotDLL FilePath
1388    | BCOs CompiledByteCode ModBreaks
1389
1390 #ifndef GHCI
1391 data CompiledByteCode = NoByteCode
1392 #endif
1393
1394 instance Outputable Unlinked where
1395    ppr (DotO path)   = text "DotO" <+> text path
1396    ppr (DotA path)   = text "DotA" <+> text path
1397    ppr (DotDLL path) = text "DotDLL" <+> text path
1398 #ifdef GHCI
1399    ppr (BCOs bcos _)   = text "BCOs" <+> ppr bcos
1400 #else
1401    ppr (BCOs bcos _)   = text "No byte code"
1402 #endif
1403
1404 isObject (DotO _)   = True
1405 isObject (DotA _)   = True
1406 isObject (DotDLL _) = True
1407 isObject _          = False
1408
1409 isInterpretable = not . isObject
1410
1411 nameOfObject (DotO fn)   = fn
1412 nameOfObject (DotA fn)   = fn
1413 nameOfObject (DotDLL fn) = fn
1414 nameOfObject other       = pprPanic "nameOfObject" (ppr other)
1415
1416 byteCodeOfObject (BCOs bc _) = bc
1417 byteCodeOfObject other       = pprPanic "byteCodeOfObject" (ppr other)
1418 \end{code}
1419
1420 %************************************************************************
1421 %*                                                                      *
1422 \subsection{Breakpoint Support}
1423 %*                                                                      *
1424 %************************************************************************
1425
1426 \begin{code}
1427 type BreakIndex = Int
1428
1429 -- | all the information about the breakpoints for a given module
1430 data ModBreaks
1431    = ModBreaks
1432    { modBreaks_flags :: BreakArray
1433         -- The array of flags, one per breakpoint, 
1434         -- indicating which breakpoints are enabled.
1435    , modBreaks_locs :: !(Array BreakIndex SrcSpan)
1436         -- An array giving the source span of each breakpoint.
1437    , modBreaks_vars :: !(Array BreakIndex [OccName])
1438         -- An array giving the names of the free variables at each breakpoint.
1439    }
1440
1441 emptyModBreaks :: ModBreaks
1442 emptyModBreaks = ModBreaks
1443    { modBreaks_flags = error "ModBreaks.modBreaks_array not initialised"
1444          -- Todo: can we avoid this? 
1445    , modBreaks_locs = array (0,-1) []
1446    , modBreaks_vars = array (0,-1) []
1447    }
1448 \end{code}