[project @ 2005-04-28 10:09:41 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / HscTypes.lhs
1
2 % (c) The University of Glasgow, 2000
3 %
4 \section[HscTypes]{Types for the per-module compiler}
5
6 \begin{code}
7 module HscTypes ( 
8         -- * Sessions and compilation state
9         Session(..), HscEnv(..), hscEPS,
10         FinderCache, FinderCacheEntry,
11         Target(..), TargetId(..), pprTarget, pprTargetId,
12         ModuleGraph, emptyMG,
13
14         ModDetails(..), emptyModDetails,
15         ModGuts(..), ModImports(..), ForeignStubs(..),
16
17         ModSummary(..), showModMsg, isBootSummary,
18         msHsFilePath, msHiFilePath, msObjFilePath, 
19
20         HscSource(..), isHsBoot, hscSourceString,       -- Re-exported from DriverPhases
21         
22         HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
23         hptInstances, hptRules,
24
25         ExternalPackageState(..), EpsStats(..), addEpsInStats,
26         PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
27         lookupIface, lookupIfaceByModule, emptyModIface,
28
29         InteractiveContext(..), emptyInteractiveContext, 
30         icPrintUnqual, unQualInScope,
31
32         ModIface(..), mkIfaceDepCache, mkIfaceVerCache, mkIfaceFixCache,
33         emptyIfaceDepCache, 
34
35         Deprecs(..), IfaceDeprecs,
36
37         FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
38
39         implicitTyThings, 
40
41         TyThing(..), tyThingClass, tyThingTyCon, tyThingDataCon, tyThingId,
42         TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
43         extendTypeEnv, extendTypeEnvList, extendTypeEnvWithIds, lookupTypeEnv,
44         typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
45
46         WhetherHasOrphans, IsBootInterface, Usage(..), 
47         Dependencies(..), noDependencies,
48         NameCache(..), OrigNameCache, OrigIParamCache,
49         Avails, availsToNameSet, availName, availNames,
50         GenAvailInfo(..), AvailInfo, RdrAvailInfo, 
51         IfaceExport,
52
53         Deprecations, DeprecTxt, lookupDeprec, plusDeprecs,
54
55         PackageInstEnv, PackageRuleBase,
56
57         -- Linker stuff
58         Linkable(..), isObjectLinkable,
59         Unlinked(..), CompiledByteCode,
60         isObject, nameOfObject, isInterpretable, byteCodeOfObject
61     ) where
62
63 #include "HsVersions.h"
64
65 #ifdef GHCI
66 import ByteCodeAsm      ( CompiledByteCode )
67 #endif
68
69 import RdrName          ( GlobalRdrEnv, emptyGlobalRdrEnv,
70                           LocalRdrEnv, emptyLocalRdrEnv,
71                           GlobalRdrElt(..), mkRdrUnqual, lookupGRE_RdrName )
72 import Name             ( Name, NamedThing, getName, nameOccName, nameModule )
73 import NameEnv
74 import NameSet  
75 import OccName          ( OccName, OccEnv, lookupOccEnv, mkOccEnv, emptyOccEnv, 
76                           extendOccEnv )
77 import Module
78 import InstEnv          ( InstEnv, Instance )
79 import Rules            ( RuleBase )
80 import CoreSyn          ( CoreBind )
81 import Id               ( Id )
82 import Type             ( TyThing(..) )
83
84 import Class            ( Class, classSelIds, classTyCon )
85 import TyCon            ( TyCon, tyConSelIds, tyConDataCons )
86 import DataCon          ( dataConImplicitIds )
87 import Packages         ( PackageIdH, PackageId, PackageConfig )
88 import DynFlags         ( DynFlags(..), isOneShot )
89 import DriverPhases     ( HscSource(..), isHsBoot, hscSourceString )
90 import BasicTypes       ( Version, initialVersion, IPName, 
91                           Fixity, defaultFixity, DeprecTxt )
92
93 import IfaceSyn         ( IfaceInst, IfaceRule, IfaceDecl(ifName) )
94
95 import FiniteMap        ( FiniteMap )
96 import CoreSyn          ( CoreRule )
97 import Maybes           ( orElse, fromJust, expectJust )
98 import Outputable
99 import SrcLoc           ( SrcSpan )
100 import UniqSupply       ( UniqSupply )
101 import FastString       ( FastString )
102
103 import DATA_IOREF       ( IORef, readIORef )
104 import StringBuffer     ( StringBuffer )
105 import Time             ( ClockTime )
106 \end{code}
107
108
109 %************************************************************************
110 %*                                                                      *
111 \subsection{Compilation environment}
112 %*                                                                      *
113 %************************************************************************
114
115
116 \begin{code}
117 -- | The Session is a handle to the complete state of a compilation
118 -- session.  A compilation session consists of a set of modules
119 -- constituting the current program or library, the context for
120 -- interactive evaluation, and various caches.
121 newtype Session = Session (IORef HscEnv)
122 \end{code}
123
124 HscEnv is like Session, except that some of the fields are immutable.
125 An HscEnv is used to compile a single module from plain Haskell source
126 code (after preprocessing) to either C, assembly or C--.  Things like
127 the module graph don't change during a single compilation.
128
129 Historical note: "hsc" used to be the name of the compiler binary,
130 when there was a separate driver and compiler.  To compile a single
131 module, the driver would invoke hsc on the source code... so nowadays
132 we think of hsc as the layer of the compiler that deals with compiling
133 a single module.
134
135 \begin{code}
136 data HscEnv 
137   = HscEnv { 
138         hsc_dflags :: DynFlags,
139                 -- The dynamic flag settings
140
141         hsc_targets :: [Target],
142                 -- The targets (or roots) of the current session
143
144         hsc_mod_graph :: ModuleGraph,
145                 -- The module graph of the current session
146
147         hsc_IC :: InteractiveContext,
148                 -- The context for evaluating interactive statements
149
150         hsc_HPT    :: HomePackageTable,
151                 -- The home package table describes already-compiled
152                 -- home-packge modules, *excluding* the module we 
153                 -- are compiling right now.
154                 -- (In one-shot mode the current module is the only
155                 --  home-package module, so hsc_HPT is empty.  All other
156                 --  modules count as "external-package" modules.
157                 --  However, even in GHCi mode, hi-boot interfaces are
158                 --  demand-loadeded into the external-package table.)
159                 --
160                 -- hsc_HPT is not mutable because we only demand-load 
161                 -- external packages; the home package is eagerly 
162                 -- loaded, module by module, by the compilation manager.
163                 --      
164                 -- The HPT may contain modules compiled earlier by --make
165                 -- but not actually below the current module in the dependency
166                 -- graph.  (This changes a previous invariant: changed Jan 05.)
167         
168         hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
169         hsc_NC  :: {-# UNPACK #-} !(IORef NameCache),
170                 -- These are side-effected by compiling to reflect
171                 -- sucking in interface files.  They cache the state of
172                 -- external interface files, in effect.
173
174         hsc_FC  :: {-# UNPACK #-} !(IORef FinderCache)
175                 -- The finder's cache.  This caches the location of modules,
176                 -- so we don't have to search the filesystem multiple times.
177  }
178
179 hscEPS :: HscEnv -> IO ExternalPackageState
180 hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
181
182 -- | A compilation target.
183 --
184 -- A target may be supplied with the actual text of the
185 -- module.  If so, use this instead of the file contents (this
186 -- is for use in an IDE where the file hasn't been saved by
187 -- the user yet).
188 data Target = Target TargetId (Maybe (StringBuffer,ClockTime))
189
190 data TargetId
191   = TargetModule Module    -- ^ A module name: search for the file
192   | TargetFile   FilePath  -- ^ A filename: parse it to find the module name.
193   deriving Eq
194
195 pprTarget :: Target -> SDoc
196 pprTarget (Target id _) = pprTargetId id
197
198 pprTargetId (TargetModule m) = ppr m
199 pprTargetId (TargetFile f)   = text f
200
201 type FinderCache = ModuleEnv FinderCacheEntry
202 type FinderCacheEntry = (ModLocation, Maybe (PackageConfig,Bool))
203         -- The finder's cache (see module Finder)
204
205 type HomePackageTable  = ModuleEnv HomeModInfo
206         -- Domain = modules in the home package
207 type PackageIfaceTable = ModuleEnv ModIface
208         -- Domain = modules in the imported packages
209
210 emptyHomePackageTable  = emptyModuleEnv
211 emptyPackageIfaceTable = emptyModuleEnv
212
213 data HomeModInfo 
214   = HomeModInfo { hm_iface    :: !ModIface,
215                   hm_details  :: !ModDetails,
216                   hm_linkable :: !(Maybe Linkable) }
217                 -- hm_linkable might be Nothing if:
218                 --   a) this is an .hs-boot module
219                 --   b) temporarily during compilation if we pruned away
220                 --      the old linkable because it was out of date.
221                 -- after a complete compilation (GHC.load), all hm_linkable
222                 -- fields in the HPT will be Just.
223 \end{code}
224
225 Simple lookups in the symbol table.
226
227 \begin{code}
228 lookupIface :: HomePackageTable -> PackageIfaceTable -> Module -> Maybe ModIface
229 -- We often have two IfaceTables, and want to do a lookup
230 lookupIface hpt pit mod
231   = case lookupModuleEnv hpt mod of
232         Just mod_info -> Just (hm_iface mod_info)
233         Nothing       -> lookupModuleEnv pit mod
234
235 lookupIfaceByModule :: HomePackageTable -> PackageIfaceTable -> Module -> Maybe ModIface
236 -- We often have two IfaceTables, and want to do a lookup
237 lookupIfaceByModule hpt pit mod
238   = case lookupModuleEnv hpt mod of
239         Just mod_info -> Just (hm_iface mod_info)
240         Nothing       -> lookupModuleEnv pit mod
241 \end{code}
242
243
244 \begin{code}
245 hptInstances :: HscEnv -> (Module -> Bool) -> [Instance]
246 -- Find all the instance declarations that are in modules imported 
247 -- by this one, directly or indirectly, and are in the Home Package Table
248 -- This ensures that we don't see instances from modules --make compiled 
249 -- before this one, but which are not below this one
250 hptInstances hsc_env want_this_module
251   = [ ispec 
252     | mod_info <- moduleEnvElts (hsc_HPT hsc_env)
253     , want_this_module (mi_module (hm_iface mod_info))
254     , ispec <- md_insts (hm_details mod_info) ]
255
256 hptRules :: HscEnv -> [(Module, IsBootInterface)] -> [CoreRule]
257 -- Get rules from modules "below" this one (in the dependency sense)
258 -- C.f Inst.hptInstances
259 hptRules hsc_env deps
260   | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
261   | otherwise
262   = let 
263         hpt = hsc_HPT hsc_env
264     in
265     [ rule
266     |   -- Find each non-hi-boot module below me
267       (mod, False) <- deps
268
269         -- Look it up in the HPT
270     , let mod_info = ASSERT( mod `elemModuleEnv` hpt )
271                      fromJust (lookupModuleEnv hpt mod)
272
273         -- And get its dfuns
274     , rule <- md_rules (hm_details mod_info) ]
275 \end{code}
276
277
278 %************************************************************************
279 %*                                                                      *
280 \subsection{Symbol tables and Module details}
281 %*                                                                      *
282 %************************************************************************
283
284 A @ModIface@ plus a @ModDetails@ summarises everything we know 
285 about a compiled module.  The @ModIface@ is the stuff *before* linking,
286 and can be written out to an interface file.  (The @ModDetails@ is after 
287 linking; it is the "linked" form of the mi_decls field.)
288
289 When we *read* an interface file, we also construct a @ModIface@ from it,
290 except that the mi_decls part is empty; when reading we consolidate
291 the declarations into a single indexed map in the @PersistentRenamerState@.
292
293 \begin{code}
294 data ModIface 
295    = ModIface {
296         mi_package  :: !PackageIdH,         -- Which package the module comes from
297         mi_module   :: !Module,
298         mi_mod_vers :: !Version,            -- Module version: changes when anything changes
299
300         mi_orphan   :: !WhetherHasOrphans,  -- Whether this module has orphans
301         mi_boot     :: !IsBootInterface,    -- Read from an hi-boot file?
302
303         mi_deps     :: Dependencies,
304                 -- This is consulted for directly-imported modules,
305                 -- but not for anything else (hence lazy)
306
307                 -- Usages; kept sorted so that it's easy to decide
308                 -- whether to write a new iface file (changing usages
309                 -- doesn't affect the version of this module)
310         mi_usages   :: [Usage],
311                 -- NOT STRICT!  we read this field lazily from the interface file
312                 -- It is *only* consulted by the recompilation checker
313
314                 -- Exports
315                 -- Kept sorted by (mod,occ), to make version comparisons easier
316         mi_exports  :: ![IfaceExport],
317         mi_exp_vers :: !Version,        -- Version number of export list
318
319                 -- Fixities
320         mi_fixities :: [(OccName,Fixity)],
321                 -- NOT STRICT!  we read this field lazily from the interface file
322
323                 -- Deprecations
324         mi_deprecs  :: IfaceDeprecs,
325                 -- NOT STRICT!  we read this field lazily from the interface file
326
327                 -- Type, class and variable declarations
328                 -- The version of an Id changes if its fixity or deprecations change
329                 --      (as well as its type of course)
330                 -- Ditto data constructors, class operations, except that 
331                 -- the version of the parent class/tycon changes
332         mi_decls :: [(Version,IfaceDecl)],      -- Sorted
333
334         mi_globals  :: !(Maybe GlobalRdrEnv),
335                 -- Its top level environment or Nothing if we read this
336                 -- interface from an interface file.  (We need the source
337                 -- file to figure out the top-level environment.)
338
339                 -- Instance declarations and rules
340         mi_insts     :: [IfaceInst],    -- Sorted
341         mi_rules     :: [IfaceRule],    -- Sorted
342         mi_rule_vers :: !Version,       -- Version number for rules and instances combined
343
344                 -- Cached environments for easy lookup
345                 -- These are computed (lazily) from other fields
346                 -- and are not put into the interface file
347         mi_dep_fn  :: Name -> Maybe DeprecTxt,  -- Cached lookup for mi_deprecs
348         mi_fix_fn  :: OccName -> Fixity,        -- Cached lookup for mi_fixities
349         mi_ver_fn  :: OccName -> Maybe Version  -- Cached lookup for mi_decls
350                         -- The Nothing in mi_ver_fn means that the thing
351                         -- isn't in decls. It's useful to know that when
352                         -- seeing if we are up to date wrt the old interface
353      }
354
355 -- Should be able to construct ModDetails from mi_decls in ModIface
356 data ModDetails
357    = ModDetails {
358         -- The next three fields are created by the typechecker
359         md_exports  :: NameSet,
360         md_types    :: !TypeEnv,
361         md_insts    :: ![Instance],     -- Dfun-ids for the instances in this module
362         md_rules    :: ![CoreRule]      -- Domain may include Ids from other modules
363      }
364
365 emptyModDetails = ModDetails { md_types = emptyTypeEnv,
366                                md_exports = emptyNameSet,
367                                md_insts = [],
368                                md_rules = [] }
369
370 -- A ModGuts is carried through the compiler, accumulating stuff as it goes
371 -- There is only one ModGuts at any time, the one for the module
372 -- being compiled right now.  Once it is compiled, a ModIface and 
373 -- ModDetails are extracted and the ModGuts is dicarded.
374
375 data ModGuts
376   = ModGuts {
377         mg_module   :: !Module,
378         mg_boot     :: IsBootInterface, -- Whether it's an hs-boot module
379         mg_exports  :: !NameSet,        -- What it exports
380         mg_deps     :: !Dependencies,   -- What is below it, directly or otherwise
381         mg_dir_imps :: ![Module],       -- Directly-imported modules; used to
382                                         --      generate initialisation code
383         mg_usages   :: ![Usage],        -- Version info for what it needed
384
385         mg_rdr_env  :: !GlobalRdrEnv,   -- Top-level lexical environment
386         mg_fix_env  :: !FixityEnv,      -- Fixity env, for things declared in this module
387         mg_deprecs  :: !Deprecations,   -- Deprecations declared in the module
388
389         mg_types    :: !TypeEnv,
390         mg_insts    :: ![Instance],     -- Instances 
391         mg_rules    :: ![CoreRule],     -- Rules from this module
392         mg_binds    :: ![CoreBind],     -- Bindings for this module
393         mg_foreign  :: !ForeignStubs
394     }
395
396 -- The ModGuts takes on several slightly different forms:
397 --
398 -- After simplification, the following fields change slightly:
399 --      mg_rules        Orphan rules only (local ones now attached to binds)
400 --      mg_binds        With rules attached
401 --
402 -- After CoreTidy, the following fields change slightly:
403 --      mg_types        Now contains Ids as well, replete with final IdInfo
404 --                         The Ids are only the ones that are visible from
405 --                         importing modules.  Without -O that means only
406 --                         exported Ids, but with -O importing modules may
407 --                         see ids mentioned in unfoldings of exported Ids
408 --
409 --      mg_insts        Same DFunIds as before, but with final IdInfo,
410 --                         and the unique might have changed; remember that
411 --                         CoreTidy links up the uniques of old and new versions
412 --
413 --      mg_rules        All rules for exported things, substituted with final Ids
414 --
415 --      mg_binds        Tidied
416
417
418
419 data ModImports
420   = ModImports {
421         imp_direct     :: ![(Module,Bool)],     -- Explicitly-imported modules
422                                                 -- Boolean is true if we imported the whole
423                                                 --      module (apart, perhaps, from hiding some)
424         imp_pkg_mods   :: !ModuleSet,           -- Non-home-package modules on which we depend,
425                                                 --      directly or indirectly
426         imp_home_names :: !NameSet              -- Home package things on which we depend,
427                                                 --      directly or indirectly
428     }
429
430 data ForeignStubs = NoStubs
431                   | ForeignStubs
432                         SDoc            -- Header file prototypes for
433                                         --      "foreign exported" functions
434                         SDoc            -- C stubs to use when calling
435                                         --      "foreign exported" functions
436                         [FastString]    -- Headers that need to be included
437                                         --      into C code generated for this module
438                         [Id]            -- Foreign-exported binders
439                                         --      we have to generate code to register these
440
441 \end{code}
442
443 \begin{code}
444 emptyModIface :: PackageIdH -> Module -> ModIface
445 emptyModIface pkg mod
446   = ModIface { mi_package  = pkg,
447                mi_module   = mod,
448                mi_mod_vers = initialVersion,
449                mi_orphan   = False,
450                mi_boot     = False,
451                mi_deps     = noDependencies,
452                mi_usages   = [],
453                mi_exports  = [],
454                mi_exp_vers = initialVersion,
455                mi_fixities = [],
456                mi_deprecs  = NoDeprecs,
457                mi_insts = [],
458                mi_rules = [],
459                mi_decls = [],
460                mi_globals  = Nothing,
461                mi_rule_vers = initialVersion,
462                mi_dep_fn = emptyIfaceDepCache,
463                mi_fix_fn = emptyIfaceFixCache,
464                mi_ver_fn = emptyIfaceVerCache
465     }           
466 \end{code}
467
468
469 %************************************************************************
470 %*                                                                      *
471 \subsection{The interactive context}
472 %*                                                                      *
473 %************************************************************************
474
475 \begin{code}
476 data InteractiveContext 
477   = InteractiveContext { 
478         ic_toplev_scope :: [Module],    -- Include the "top-level" scope of
479                                         -- these modules
480
481         ic_exports :: [Module],         -- Include just the exports of these
482                                         -- modules
483
484         ic_rn_gbl_env :: GlobalRdrEnv,  -- The cached GlobalRdrEnv, built from
485                                         -- ic_toplev_scope and ic_exports
486
487         ic_rn_local_env :: LocalRdrEnv, -- Lexical context for variables bound
488                                         -- during interaction
489
490         ic_type_env :: TypeEnv          -- Ditto for types
491     }
492
493 emptyInteractiveContext
494   = InteractiveContext { ic_toplev_scope = [],
495                          ic_exports = [],
496                          ic_rn_gbl_env = emptyGlobalRdrEnv,
497                          ic_rn_local_env = emptyLocalRdrEnv,
498                          ic_type_env = emptyTypeEnv }
499
500 icPrintUnqual :: InteractiveContext -> PrintUnqualified
501 icPrintUnqual ictxt = unQualInScope (ic_rn_gbl_env ictxt)
502 \end{code}
503
504 @unQualInScope@ returns a function that takes a @Name@ and tells whether
505 its unqualified name is in scope.  This is put as a boolean flag in
506 the @Name@'s provenance to guide whether or not to print the name qualified
507 in error messages.
508
509 \begin{code}
510 unQualInScope :: GlobalRdrEnv -> PrintUnqualified
511 -- True if 'f' is in scope, and has only one binding,
512 -- and the thing it is bound to is the name we are looking for
513 -- (i.e. false if A.f and B.f are both in scope as unqualified 'f')
514 --
515 -- [Out of date] Also checks for built-in syntax, which is always 'in scope'
516 unQualInScope env mod occ
517   = case lookupGRE_RdrName (mkRdrUnqual occ) env of
518         [gre] -> nameModule (gre_name gre) == mod
519         other -> False
520 \end{code}
521
522
523 %************************************************************************
524 %*                                                                      *
525                 TyThing
526 %*                                                                      *
527 %************************************************************************
528
529 \begin{code}
530 implicitTyThings :: TyThing -> [TyThing]
531 implicitTyThings (AnId id)   = []
532
533         -- For type constructors, add the data cons (and their extras),
534         -- and the selectors and generic-programming Ids too
535         --
536         -- Newtypes don't have a worker Id, so don't generate that?
537 implicitTyThings (ATyCon tc) = map AnId (tyConSelIds tc) ++ 
538                                concatMap (extras_plus . ADataCon) (tyConDataCons tc)
539                      
540         -- For classes, add the class TyCon too (and its extras)
541         -- and the class selector Ids
542 implicitTyThings (AClass cl) = map AnId (classSelIds cl) ++
543                                extras_plus (ATyCon (classTyCon cl))
544                          
545
546         -- For data cons add the worker and wrapper (if any)
547 implicitTyThings (ADataCon dc) = map AnId (dataConImplicitIds dc)
548
549 extras_plus thing = thing : implicitTyThings thing
550
551 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
552 extendTypeEnvWithIds env ids
553   = extendNameEnvList env [(getName id, AnId id) | id <- ids]
554 \end{code}
555
556 %************************************************************************
557 %*                                                                      *
558                 TypeEnv
559 %*                                                                      *
560 %************************************************************************
561
562 \begin{code}
563 type TypeEnv = NameEnv TyThing
564
565 emptyTypeEnv   :: TypeEnv
566 typeEnvElts    :: TypeEnv -> [TyThing]
567 typeEnvClasses :: TypeEnv -> [Class]
568 typeEnvTyCons  :: TypeEnv -> [TyCon]
569 typeEnvIds     :: TypeEnv -> [Id]
570 lookupTypeEnv  :: TypeEnv -> Name -> Maybe TyThing
571
572 emptyTypeEnv       = emptyNameEnv
573 typeEnvElts    env = nameEnvElts env
574 typeEnvClasses env = [cl | AClass cl <- typeEnvElts env]
575 typeEnvTyCons  env = [tc | ATyCon tc <- typeEnvElts env] 
576 typeEnvIds     env = [id | AnId id   <- typeEnvElts env] 
577
578 mkTypeEnv :: [TyThing] -> TypeEnv
579 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
580                 
581 lookupTypeEnv = lookupNameEnv
582
583 -- Extend the type environment
584 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
585 extendTypeEnv env thing = extendNameEnv env (getName thing) thing 
586
587 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
588 extendTypeEnvList env things = foldl extendTypeEnv env things
589 \end{code}
590
591 \begin{code}
592 lookupType :: HomePackageTable -> PackageTypeEnv -> Name -> Maybe TyThing
593 lookupType hpt pte name
594   = case lookupModuleEnv hpt (nameModule name) of
595         Just details -> lookupNameEnv (md_types (hm_details details)) name
596         Nothing      -> lookupNameEnv pte name
597 \end{code}
598
599
600 \begin{code}
601 tyThingTyCon (ATyCon tc) = tc
602 tyThingTyCon other       = pprPanic "tyThingTyCon" (ppr other)
603
604 tyThingClass (AClass cls) = cls
605 tyThingClass other        = pprPanic "tyThingClass" (ppr other)
606
607 tyThingDataCon (ADataCon dc) = dc
608 tyThingDataCon other         = pprPanic "tyThingDataCon" (ppr other)
609
610 tyThingId (AnId id) = id
611 tyThingId other     = pprPanic "tyThingId" (ppr other)
612 \end{code}
613
614 %************************************************************************
615 %*                                                                      *
616 \subsection{Auxiliary types}
617 %*                                                                      *
618 %************************************************************************
619
620 These types are defined here because they are mentioned in ModDetails,
621 but they are mostly elaborated elsewhere
622
623 \begin{code}
624 mkIfaceVerCache :: [(Version,IfaceDecl)] -> OccName -> Maybe Version
625 mkIfaceVerCache pairs 
626   = \occ -> lookupOccEnv env occ
627   where
628     env = foldl add emptyOccEnv pairs
629     add env (v,d) = extendOccEnv env (ifName d) v
630
631 emptyIfaceVerCache :: OccName -> Maybe Version
632 emptyIfaceVerCache occ = Nothing
633
634 ------------------ Deprecations -------------------------
635 data Deprecs a
636   = NoDeprecs
637   | DeprecAll DeprecTxt -- Whole module deprecated
638   | DeprecSome a        -- Some specific things deprecated
639   deriving( Eq )
640
641 type IfaceDeprecs = Deprecs [(OccName,DeprecTxt)]
642 type Deprecations = Deprecs (NameEnv (OccName,DeprecTxt))
643
644 mkIfaceDepCache:: IfaceDeprecs -> Name -> Maybe DeprecTxt
645 mkIfaceDepCache NoDeprecs         = \n -> Nothing
646 mkIfaceDepCache (DeprecAll t)     = \n -> Just t
647 mkIfaceDepCache (DeprecSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
648
649 emptyIfaceDepCache :: Name -> Maybe DeprecTxt
650 emptyIfaceDepCache n = Nothing
651
652 lookupDeprec :: Deprecations -> Name -> Maybe DeprecTxt
653 lookupDeprec NoDeprecs        name = Nothing
654 lookupDeprec (DeprecAll  txt) name = Just txt
655 lookupDeprec (DeprecSome env) name = case lookupNameEnv env name of
656                                             Just (_, txt) -> Just txt
657                                             Nothing       -> Nothing
658
659 plusDeprecs :: Deprecations -> Deprecations -> Deprecations
660 plusDeprecs d NoDeprecs = d
661 plusDeprecs NoDeprecs d = d
662 plusDeprecs d (DeprecAll t) = DeprecAll t
663 plusDeprecs (DeprecAll t) d = DeprecAll t
664 plusDeprecs (DeprecSome v1) (DeprecSome v2) = DeprecSome (v1 `plusNameEnv` v2)
665 \end{code}
666
667
668 \begin{code}
669 type Avails       = [AvailInfo]
670 type AvailInfo    = GenAvailInfo Name
671 type RdrAvailInfo = GenAvailInfo OccName
672
673 data GenAvailInfo name  = Avail name     -- An ordinary identifier
674                         | AvailTC name   -- The name of the type or class
675                                   [name] -- The available pieces of type/class.
676                                          -- NB: If the type or class is itself
677                                          -- to be in scope, it must be in this list.
678                                          -- Thus, typically: AvailTC Eq [Eq, ==, /=]
679                         deriving( Eq )
680                         -- Equality used when deciding if the interface has changed
681
682 type IfaceExport = (Module, [GenAvailInfo OccName])
683
684 availsToNameSet :: [AvailInfo] -> NameSet
685 availsToNameSet avails = foldl add emptyNameSet avails
686                        where
687                          add set avail = addListToNameSet set (availNames avail)
688
689 availName :: GenAvailInfo name -> name
690 availName (Avail n)     = n
691 availName (AvailTC n _) = n
692
693 availNames :: GenAvailInfo name -> [name]
694 availNames (Avail n)      = [n]
695 availNames (AvailTC n ns) = ns
696
697 instance Outputable n => Outputable (GenAvailInfo n) where
698    ppr = pprAvail
699
700 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
701 pprAvail (AvailTC n ns) = ppr n <> case {- filter (/= n) -} ns of
702                                         []  -> empty
703                                         ns' -> braces (hsep (punctuate comma (map ppr ns')))
704
705 pprAvail (Avail n) = ppr n
706 \end{code}
707
708 \begin{code}
709 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
710 mkIfaceFixCache pairs 
711   = \n -> lookupOccEnv env n `orElse` defaultFixity
712   where
713    env = mkOccEnv pairs
714
715 emptyIfaceFixCache :: OccName -> Fixity
716 emptyIfaceFixCache n = defaultFixity
717
718 -- This fixity environment is for source code only
719 type FixityEnv = NameEnv FixItem
720
721 -- We keep the OccName in the range so that we can generate an interface from it
722 data FixItem = FixItem OccName Fixity SrcSpan
723
724 instance Outputable FixItem where
725   ppr (FixItem occ fix loc) = ppr fix <+> ppr occ <+> parens (ppr loc)
726
727 emptyFixityEnv :: FixityEnv
728 emptyFixityEnv = emptyNameEnv
729
730 lookupFixity :: FixityEnv -> Name -> Fixity
731 lookupFixity env n = case lookupNameEnv env n of
732                         Just (FixItem _ fix _) -> fix
733                         Nothing                -> defaultFixity
734 \end{code}
735
736
737 %************************************************************************
738 %*                                                                      *
739 \subsection{WhatsImported}
740 %*                                                                      *
741 %************************************************************************
742
743 \begin{code}
744 type WhetherHasOrphans   = Bool
745         -- An "orphan" is 
746         --      * an instance decl in a module other than the defn module for 
747         --              one of the tycons or classes in the instance head
748         --      * a transformation rule in a module other than the one defining
749         --              the function in the head of the rule.
750
751 type IsBootInterface = Bool
752
753 -- Dependency info about modules and packages below this one
754 -- in the import hierarchy.  See TcRnTypes.ImportAvails for details.
755 --
756 -- Invariant: the dependencies of a module M never includes M
757 -- Invariant: the lists are unordered, with no duplicates
758 data Dependencies
759   = Deps { dep_mods  :: [(Module,IsBootInterface)],     -- Home-package module dependencies
760            dep_pkgs  :: [PackageId],                    -- External package dependencies
761            dep_orphs :: [Module] }                      -- Orphan modules (whether home or external pkg)
762   deriving( Eq )
763         -- Equality used only for old/new comparison in MkIface.addVersionInfo
764
765 noDependencies :: Dependencies
766 noDependencies = Deps [] [] []
767           
768 data Usage
769   = Usage { usg_name     :: Module,                     -- Name of the module
770             usg_mod      :: Version,                    -- Module version
771             usg_entities :: [(OccName,Version)],        -- Sorted by occurrence name
772             usg_exports  :: Maybe Version,              -- Export-list version, if we depend on it
773             usg_rules    :: Version                     -- Orphan-rules version (for non-orphan
774                                                         -- modules this will always be initialVersion)
775     }       deriving( Eq )
776         -- This type doesn't let you say "I imported f but none of the rules in
777         -- the module". If you use anything in the module you get its rule version
778         -- So if the rules change, you'll recompile, even if you don't use them.
779         -- This is easy to implement, and it's safer: you might not have used the rules last
780         -- time round, but if someone has added a new rule you might need it this time
781
782         -- The export list field is (Just v) if we depend on the export list:
783         --      i.e. we imported the module without saying exactly what we imported
784         -- We need to recompile if the module exports changes, because we might
785         -- now have a name clash in the importing module.
786 \end{code}
787
788
789 %************************************************************************
790 %*                                                                      *
791                 The External Package State
792 %*                                                                      *
793 %************************************************************************
794
795 \begin{code}
796 type PackageTypeEnv  = TypeEnv
797 type PackageRuleBase = RuleBase
798 type PackageInstEnv  = InstEnv
799
800 data ExternalPackageState
801   = EPS {
802         eps_is_boot :: !(ModuleEnv (Module, IsBootInterface)),
803                 -- In OneShot mode (only), home-package modules accumulate in the
804                 -- external package state, and are sucked in lazily.
805                 -- For these home-pkg modules (only) we need to record which are
806                 -- boot modules.  We set this field after loading all the 
807                 -- explicitly-imported interfaces, but before doing anything else
808                 --
809                 -- The Module part is not necessary, but it's useful for
810                 -- debug prints, and it's convenient because this field comes
811                 -- direct from TcRnTypes.ImportAvails.imp_dep_mods
812
813         eps_PIT :: !PackageIfaceTable,
814                 -- The ModuleIFaces for modules in external packages
815                 -- whose interfaces we have opened
816                 -- The declarations in these interface files are held in
817                 -- eps_decls, eps_inst_env, eps_rules (below), not in the 
818                 -- mi_decls fields of the iPIT.  
819                 -- What _is_ in the iPIT is:
820                 --      * The Module 
821                 --      * Version info
822                 --      * Its exports
823                 --      * Fixities
824                 --      * Deprecations
825
826         eps_PTE :: !PackageTypeEnv,             -- Domain = external-package modules
827
828         eps_inst_env :: !PackageInstEnv,        -- The total InstEnv accumulated from
829                                                 --   all the external-package modules
830         eps_rule_base :: !PackageRuleBase,      -- Ditto RuleEnv
831
832         eps_stats :: !EpsStats
833   }
834
835 -- "In" means read from iface files
836 -- "Out" means actually sucked in and type-checked
837 data EpsStats = EpsStats { n_ifaces_in
838                          , n_decls_in, n_decls_out 
839                          , n_rules_in, n_rules_out
840                          , n_insts_in, n_insts_out :: !Int }
841
842 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
843 -- Add stats for one newly-read interface
844 addEpsInStats stats n_decls n_insts n_rules
845   = stats { n_ifaces_in = n_ifaces_in stats + 1
846           , n_decls_in  = n_decls_in stats + n_decls
847           , n_insts_in  = n_insts_in stats + n_insts
848           , n_rules_in  = n_rules_in stats + n_rules }
849 \end{code}
850
851 The NameCache makes sure that there is just one Unique assigned for
852 each original name; i.e. (module-name, occ-name) pair.  The Name is
853 always stored as a Global, and has the SrcLoc of its binding location.
854 Actually that's not quite right.  When we first encounter the original
855 name, we might not be at its binding site (e.g. we are reading an
856 interface file); so we give it 'noSrcLoc' then.  Later, when we find
857 its binding site, we fix it up.
858
859 \begin{code}
860 data NameCache
861  = NameCache {  nsUniqs :: UniqSupply,
862                 -- Supply of uniques
863                 nsNames :: OrigNameCache,
864                 -- Ensures that one original name gets one unique
865                 nsIPs   :: OrigIParamCache
866                 -- Ensures that one implicit parameter name gets one unique
867    }
868
869 type OrigNameCache   = ModuleEnv (OccEnv Name)
870 type OrigIParamCache = FiniteMap (IPName OccName) (IPName Name)
871 \end{code}
872
873
874
875 %************************************************************************
876 %*                                                                      *
877                 The module graph and ModSummary type
878         A ModSummary is a node in the compilation manager's
879         dependency graph, and it's also passed to hscMain
880 %*                                                                      *
881 %************************************************************************
882
883 A ModuleGraph contains all the nodes from the home package (only).  
884 There will be a node for each source module, plus a node for each hi-boot
885 module.
886
887 \begin{code}
888 type ModuleGraph = [ModSummary]  -- The module graph, 
889                                  -- NOT NECESSARILY IN TOPOLOGICAL ORDER
890
891 emptyMG :: ModuleGraph
892 emptyMG = []
893
894 -- The nodes of the module graph are
895 --      EITHER a regular Haskell source module
896 --      OR     a hi-boot source module
897
898 data ModSummary
899    = ModSummary {
900         ms_mod       :: Module,                 -- Name of the module
901         ms_hsc_src   :: HscSource,              -- Source is Haskell, hs-boot, external core
902         ms_location  :: ModLocation,            -- Location
903         ms_hs_date   :: ClockTime,              -- Timestamp of source file
904         ms_obj_date  :: Maybe ClockTime,        -- Timestamp of object, maybe
905         ms_srcimps   :: [Module],               -- Source imports
906         ms_imps      :: [Module],               -- Non-source imports
907         ms_hspp_file :: Maybe FilePath,         -- Filename of preprocessed source,
908                                                 -- once we have preprocessed it.
909         ms_hspp_buf  :: Maybe StringBuffer      -- The actual preprocessed source, maybe.
910      }
911
912 -- The ModLocation contains both the original source filename and the
913 -- filename of the cleaned-up source file after all preprocessing has been
914 -- done.  The point is that the summariser will have to cpp/unlit/whatever
915 -- all files anyway, and there's no point in doing this twice -- just 
916 -- park the result in a temp file, put the name of it in the location,
917 -- and let @compile@ read from that file on the way back up.
918
919 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
920 -- the ms_hs_date and imports can, of course, change
921
922 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
923 msHsFilePath  ms = expectJust "msHsFilePath" (ml_hs_file  (ms_location ms))
924 msHiFilePath  ms = ml_hi_file  (ms_location ms)
925 msObjFilePath ms = ml_obj_file (ms_location ms)
926
927 isBootSummary :: ModSummary -> Bool
928 isBootSummary ms = isHsBoot (ms_hsc_src ms)
929
930 instance Outputable ModSummary where
931    ppr ms
932       = sep [text "ModSummary {",
933              nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
934                           text "ms_mod =" <+> ppr (ms_mod ms) 
935                                 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
936                           text "ms_imps =" <+> ppr (ms_imps ms),
937                           text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
938              char '}'
939             ]
940
941 showModMsg :: Bool -> ModSummary -> String
942 showModMsg use_object mod_summary
943   = showSDoc (hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
944                     char '(', text (msHsFilePath mod_summary) <> comma,
945                     if use_object then text (msObjFilePath mod_summary)
946                               else text "interpreted",
947                     char ')'])
948  where 
949     mod     = ms_mod mod_summary 
950     mod_str = moduleUserString mod ++ hscSourceString (ms_hsc_src mod_summary)
951 \end{code}
952
953
954 %************************************************************************
955 %*                                                                      *
956 \subsection{Linkable stuff}
957 %*                                                                      *
958 %************************************************************************
959
960 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
961 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
962
963 \begin{code}
964 data Linkable = LM {
965   linkableTime     :: ClockTime,        -- Time at which this linkable was built
966                                         -- (i.e. when the bytecodes were produced,
967                                         --       or the mod date on the files)
968   linkableModule   :: Module,           -- Should be Module, but see below
969   linkableUnlinked :: [Unlinked]
970  }
971
972 isObjectLinkable :: Linkable -> Bool
973 isObjectLinkable l = all isObject (linkableUnlinked l)
974
975 instance Outputable Linkable where
976    ppr (LM when_made mod unlinkeds)
977       = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
978         $$ nest 3 (ppr unlinkeds)
979
980 -------------------------------------------
981 data Unlinked
982    = DotO FilePath
983    | DotA FilePath
984    | DotDLL FilePath
985    | BCOs CompiledByteCode
986
987 #ifndef GHCI
988 data CompiledByteCode = NoByteCode
989 #endif
990
991 instance Outputable Unlinked where
992    ppr (DotO path)   = text "DotO" <+> text path
993    ppr (DotA path)   = text "DotA" <+> text path
994    ppr (DotDLL path) = text "DotDLL" <+> text path
995 #ifdef GHCI
996    ppr (BCOs bcos)   = text "BCOs" <+> ppr bcos
997 #else
998    ppr (BCOs bcos)   = text "No byte code"
999 #endif
1000
1001 isObject (DotO _)   = True
1002 isObject (DotA _)   = True
1003 isObject (DotDLL _) = True
1004 isObject _          = False
1005
1006 isInterpretable = not . isObject
1007
1008 nameOfObject (DotO fn)   = fn
1009 nameOfObject (DotA fn)   = fn
1010 nameOfObject (DotDLL fn) = fn
1011
1012 byteCodeOfObject (BCOs bc) = bc
1013 \end{code}
1014
1015
1016