[project @ 2002-01-23 16:50:46 by simonmar]
[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         GhciMode(..),
9
10         ModuleLocation(..), showModMsg,
11
12         ModDetails(..), ModIface(..), 
13         HomeSymbolTable, emptySymbolTable,
14         PackageTypeEnv,
15         HomeIfaceTable, PackageIfaceTable, emptyIfaceTable,
16         lookupIface, lookupIfaceByModName,
17         emptyModIface,
18
19         InteractiveContext(..),
20
21         IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
22
23         VersionInfo(..), initialVersionInfo, lookupVersion,
24
25         TyThing(..), isTyClThing, implicitTyThingIds,
26
27         TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
28         extendTypeEnvList, extendTypeEnvWithIds,
29         typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
30
31         ImportedModuleInfo, WhetherHasOrphans, ImportVersion, WhatsImported(..),
32         PersistentRenamerState(..), IsBootInterface, DeclsMap,
33         IfaceInsts, IfaceRules, GatedDecl, GatedDecls, GateFn, IsExported,
34         NameSupply(..), OrigNameCache, OrigIParamCache,
35         Avails, AvailEnv, emptyAvailEnv,
36         GenAvailInfo(..), AvailInfo, RdrAvailInfo, 
37         PersistentCompilerState(..),
38
39         Deprecations(..), lookupDeprec,
40
41         InstEnv, ClsInstEnv, DFunId,
42         PackageInstEnv, PackageRuleBase,
43
44         GlobalRdrEnv, GlobalRdrElt(..), pprGlobalRdrEnv,
45         LocalRdrEnv, extendLocalRdrEnv,
46         
47
48         -- Provenance
49         Provenance(..), ImportReason(..), 
50         pprNameProvenance, hasBetterProv
51
52     ) where
53
54 #include "HsVersions.h"
55
56 import RdrName          ( RdrName, RdrNameEnv, addListToRdrEnv, emptyRdrEnv, 
57                           mkRdrUnqual, rdrEnvToList )
58 import Name             ( Name, NamedThing, getName, nameOccName, nameModule, nameSrcLoc )
59 import NameEnv
60 import OccName          ( OccName )
61 import Module           ( Module, ModuleName, ModuleEnv,
62                           lookupModuleEnv, lookupModuleEnvByName, 
63                           emptyModuleEnv, moduleUserString
64                         )
65 import InstEnv          ( InstEnv, ClsInstEnv, DFunId )
66 import Rules            ( RuleBase )
67 import CoreSyn          ( CoreBind )
68 import Id               ( Id )
69 import Class            ( Class, classSelIds )
70 import TyCon            ( TyCon, isNewTyCon, tyConGenIds, tyConSelIds, tyConDataConsIfAvailable )
71 import DataCon          ( dataConId, dataConWrapId )
72
73 import BasicTypes       ( Version, initialVersion, Fixity, IPName )
74
75 import HsSyn            ( DeprecTxt, tyClDeclName, ifaceRuleDeclName )
76 import RdrHsSyn         ( RdrNameInstDecl, RdrNameRuleDecl, RdrNameTyClDecl )
77 import RnHsSyn          ( RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl )
78
79 import CoreSyn          ( IdCoreRule )
80
81 import FiniteMap        ( FiniteMap )
82 import Bag              ( Bag )
83 import Maybes           ( seqMaybe, orElse )
84 import Outputable
85 import SrcLoc           ( SrcLoc, isGoodSrcLoc )
86 import Util             ( thenCmp, sortLt, unJust )
87 import UniqSupply       ( UniqSupply )
88 \end{code}
89
90 %************************************************************************
91 %*                                                                      *
92 \subsection{Which mode we're in
93 %*                                                                      *
94 %************************************************************************
95
96 \begin{code}
97 data GhciMode = Batch | Interactive | OneShot 
98      deriving Eq
99 \end{code}
100
101
102 %************************************************************************
103 %*                                                                      *
104 \subsection{Module locations}
105 %*                                                                      *
106 %************************************************************************
107
108 \begin{code}
109 data ModuleLocation
110    = ModuleLocation {
111         ml_hs_file   :: Maybe FilePath,
112         ml_hspp_file :: Maybe FilePath,  -- path of preprocessed source
113         ml_hi_file   :: FilePath,
114         ml_obj_file  :: Maybe FilePath
115      }
116      deriving Show
117
118 instance Outputable ModuleLocation where
119    ppr = text . show
120
121 -- Probably doesn't really belong here, but used in HscMain and InteractiveUI.
122
123 showModMsg :: Bool -> Module -> ModuleLocation -> String
124 showModMsg use_object mod location =
125     mod_str ++ replicate (max 0 (16 - length mod_str)) ' '
126     ++" ( " ++ unJust "showModMsg" (ml_hs_file location) ++ ", "
127     ++ (if use_object
128           then unJust "showModMsg" (ml_obj_file location)
129           else "interpreted")
130     ++ " )"
131  where mod_str = moduleUserString mod
132 \end{code}
133
134 For a module in another package, the hs_file and obj_file
135 components of ModuleLocation are undefined.  
136
137 The locations specified by a ModuleLocation may or may not
138 correspond to actual files yet: for example, even if the object
139 file doesn't exist, the ModuleLocation still contains the path to
140 where the object file will reside if/when it is created.
141
142
143 %************************************************************************
144 %*                                                                      *
145 \subsection{Symbol tables and Module details}
146 %*                                                                      *
147 %************************************************************************
148
149 A @ModIface@ plus a @ModDetails@ summarises everything we know 
150 about a compiled module.  The @ModIface@ is the stuff *before* linking,
151 and can be written out to an interface file.  (The @ModDetails@ is after 
152 linking; it is the "linked" form of the mi_decls field.)
153
154 When we *read* an interface file, we also construct a @ModIface@ from it,
155 except that the mi_decls part is empty; when reading we consolidate
156 the declarations into a single indexed map in the @PersistentRenamerState@.
157
158 \begin{code}
159 data ModIface 
160    = ModIface {
161         mi_module   :: !Module,             -- Complete with package info
162         mi_version  :: !VersionInfo,        -- Module version number
163
164         mi_orphan   :: WhetherHasOrphans,   -- Whether this module has orphans
165                 -- NOT STRICT!  we fill this field with _|_ sometimes
166
167         mi_boot     :: !IsBootInterface,    -- read from an hi-boot file?
168
169         mi_usages   :: ![ImportVersion Name],   
170                 -- Usages; kept sorted so that it's easy to decide
171                 -- whether to write a new iface file (changing usages
172                 -- doesn't affect the version of this module)
173
174         mi_exports  :: ![(ModuleName,Avails)],
175                 -- What it exports Kept sorted by (mod,occ), to make
176                 -- version comparisons easier
177
178         mi_globals  :: !(Maybe GlobalRdrEnv),
179                 -- Its top level environment or Nothing if we read this
180                 -- interface from a file.
181
182         mi_fixities :: !(NameEnv Fixity),   -- Fixities
183         mi_deprecs  :: !Deprecations,       -- Deprecations
184
185         mi_decls    :: IfaceDecls           -- The RnDecls form of ModDetails
186                 -- NOT STRICT!  we fill this field with _|_ sometimes
187      }
188
189 data IfaceDecls = IfaceDecls { dcl_tycl  :: [RenamedTyClDecl],  -- Sorted
190                                dcl_rules :: [RenamedRuleDecl],  -- Sorted
191                                dcl_insts :: [RenamedInstDecl] } -- Unsorted
192
193 mkIfaceDecls :: [RenamedTyClDecl] -> [RenamedRuleDecl] -> [RenamedInstDecl] -> IfaceDecls
194 mkIfaceDecls tycls rules insts
195   = IfaceDecls { dcl_tycl  = sortLt lt_tycl tycls,
196                  dcl_rules = sortLt lt_rule rules,
197                  dcl_insts = insts }
198   where
199     d1 `lt_tycl` d2 = tyClDeclName      d1 < tyClDeclName      d2
200     r1 `lt_rule` r2 = ifaceRuleDeclName r1 < ifaceRuleDeclName r2
201
202
203 -- typechecker should only look at this, not ModIface
204 -- Should be able to construct ModDetails from mi_decls in ModIface
205 data ModDetails
206    = ModDetails {
207         -- The next three fields are created by the typechecker
208         md_types    :: !TypeEnv,
209         md_insts    :: ![DFunId],       -- Dfun-ids for the instances in this module
210         md_rules    :: ![IdCoreRule],   -- Domain may include Ids from other modules
211         md_binds    :: ![CoreBind]
212      }
213
214 -- The ModDetails takes on several slightly different forms:
215 --
216 -- After typecheck + desugar
217 --      md_types        Contains TyCons, Classes, and implicit Ids
218 --      md_insts        All instances from this module (incl derived ones)
219 --      md_rules        All rules from this module
220 --      md_binds        Desugared bindings
221 --
222 -- After simplification
223 --      md_types        Same as after typecheck
224 --      md_insts        Ditto
225 --      md_rules        Orphan rules only (local ones now attached to binds)
226 --      md_binds        With rules attached
227 --
228 -- After CoreTidy
229 --      md_types        Now contains Ids as well, replete with final IdInfo
230 --                         The Ids are only the ones that are visible from
231 --                         importing modules.  Without -O that means only
232 --                         exported Ids, but with -O importing modules may
233 --                         see ids mentioned in unfoldings of exported Ids
234 --
235 --      md_insts        Same DFunIds as before, but with final IdInfo,
236 --                         and the unique might have changed; remember that
237 --                         CoreTidy links up the uniques of old and new versions
238 --
239 --      md_rules        All rules for exported things, substituted with final Ids
240 --
241 --      md_binds        Tidied
242 --
243 -- Passed back to compilation manager
244 --      Just as after CoreTidy, but with md_binds nuked
245
246 \end{code}
247
248 \begin{code}
249 emptyModIface :: Module -> ModIface
250 emptyModIface mod
251   = ModIface { mi_module   = mod,
252                mi_version  = initialVersionInfo,
253                mi_usages   = [],
254                mi_orphan   = False,
255                mi_boot     = False,
256                mi_exports  = [],
257                mi_fixities = emptyNameEnv,
258                mi_globals  = Nothing,
259                mi_deprecs  = NoDeprecs,
260                mi_decls    = panic "emptyModIface: decls"
261     }           
262 \end{code}
263
264 Symbol tables map modules to ModDetails:
265
266 \begin{code}
267 type SymbolTable        = ModuleEnv ModDetails
268 type IfaceTable         = ModuleEnv ModIface
269
270 type HomeIfaceTable     = IfaceTable
271 type PackageIfaceTable  = IfaceTable
272
273 type HomeSymbolTable    = SymbolTable   -- Domain = modules in the home package
274
275 emptySymbolTable :: SymbolTable
276 emptySymbolTable = emptyModuleEnv
277
278 emptyIfaceTable :: IfaceTable
279 emptyIfaceTable = emptyModuleEnv
280 \end{code}
281
282 Simple lookups in the symbol table.
283
284 \begin{code}
285 lookupIface :: HomeIfaceTable -> PackageIfaceTable -> Name -> Maybe ModIface
286 -- We often have two IfaceTables, and want to do a lookup
287 lookupIface hit pit name
288   = lookupModuleEnv hit mod `seqMaybe` lookupModuleEnv pit mod
289   where
290     mod = nameModule name
291
292 lookupIfaceByModName :: HomeIfaceTable -> PackageIfaceTable -> ModuleName -> Maybe ModIface
293 -- We often have two IfaceTables, and want to do a lookup
294 lookupIfaceByModName hit pit mod
295   = lookupModuleEnvByName hit mod `seqMaybe` lookupModuleEnvByName pit mod
296 \end{code}
297
298
299 %************************************************************************
300 %*                                                                      *
301 \subsection{The interactive context}
302 %*                                                                      *
303 %************************************************************************
304
305 \begin{code}
306 data InteractiveContext 
307   = InteractiveContext { 
308         ic_toplev_scope :: [Module],    -- Include the "top-level" scope of
309                                         -- these modules
310
311         ic_exports :: [Module],         -- Include just the exports of these
312                                         -- modules
313
314         ic_rn_gbl_env :: GlobalRdrEnv,  -- The cached GlobalRdrEnv, built from
315                                         -- ic_toplev_scope and ic_exports
316
317         ic_print_unqual :: PrintUnqualified,
318                                         -- cached PrintUnqualified, as above
319
320         ic_rn_local_env :: LocalRdrEnv, -- Lexical context for variables bound
321                                         -- during interaction
322
323         ic_type_env :: TypeEnv          -- Ditto for types
324     }
325 \end{code}
326
327
328 %************************************************************************
329 %*                                                                      *
330 \subsection{Type environment stuff}
331 %*                                                                      *
332 %************************************************************************
333
334 \begin{code}
335 data TyThing = AnId   Id
336              | ATyCon TyCon
337              | AClass Class
338
339 isTyClThing :: TyThing -> Bool
340 isTyClThing (ATyCon _) = True
341 isTyClThing (AClass _) = True
342 isTyClThing (AnId   _) = False
343
344 instance NamedThing TyThing where
345   getName (AnId id)   = getName id
346   getName (ATyCon tc) = getName tc
347   getName (AClass cl) = getName cl
348
349 instance Outputable TyThing where
350   ppr (AnId   id) = ptext SLIT("AnId")   <+> ppr id
351   ppr (ATyCon tc) = ptext SLIT("ATyCon") <+> ppr tc
352   ppr (AClass cl) = ptext SLIT("AClass") <+> ppr cl
353
354
355 typeEnvElts    :: TypeEnv -> [TyThing]
356 typeEnvClasses :: TypeEnv -> [Class]
357 typeEnvTyCons  :: TypeEnv -> [TyCon]
358 typeEnvIds     :: TypeEnv -> [Id]
359
360 typeEnvElts    env = nameEnvElts env
361 typeEnvClasses env = [cl | AClass cl <- typeEnvElts env]
362 typeEnvTyCons  env = [tc | ATyCon tc <- typeEnvElts env] 
363 typeEnvIds     env = [id | AnId id   <- typeEnvElts env] 
364
365 implicitTyThingIds :: [TyThing] -> [Id]
366 -- Add the implicit data cons and selectors etc 
367 implicitTyThingIds things
368   = concat (map go things)
369   where
370     go (AnId f)    = []
371     go (AClass cl) = classSelIds cl
372     go (ATyCon tc) = tyConGenIds tc ++
373                      tyConSelIds tc ++
374                      [ n | dc <- tyConDataConsIfAvailable tc, 
375                            n  <- implicitConIds tc dc]
376                 -- Synonyms return empty list of constructors and selectors
377
378     implicitConIds tc dc        -- Newtypes have a constructor wrapper,
379                                 -- but no worker
380         | isNewTyCon tc = [dataConWrapId dc]
381         | otherwise     = [dataConId dc, dataConWrapId dc]
382 \end{code}
383
384
385 \begin{code}
386 type TypeEnv = NameEnv TyThing
387
388 emptyTypeEnv = emptyNameEnv
389
390 mkTypeEnv :: [TyThing] -> TypeEnv
391 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
392                 
393 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
394 extendTypeEnvList env things
395   = extendNameEnvList env [(getName thing, thing) | thing <- things]
396
397 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
398 extendTypeEnvWithIds env ids
399   = extendNameEnvList env [(getName id, AnId id) | id <- ids]
400 \end{code}
401
402 \begin{code}
403 lookupType :: HomeSymbolTable -> PackageTypeEnv -> Name -> Maybe TyThing
404 lookupType hst pte name
405   = case lookupModuleEnv hst (nameModule name) of
406         Just details -> lookupNameEnv (md_types details) name
407         Nothing      -> lookupNameEnv pte name
408 \end{code}
409
410 %************************************************************************
411 %*                                                                      *
412 \subsection{Auxiliary types}
413 %*                                                                      *
414 %************************************************************************
415
416 These types are defined here because they are mentioned in ModDetails,
417 but they are mostly elaborated elsewhere
418
419 \begin{code}
420 data VersionInfo 
421   = VersionInfo {
422         vers_module  :: Version,        -- Changes when anything changes
423         vers_exports :: Version,        -- Changes when export list changes
424         vers_rules   :: Version,        -- Changes when any rule changes
425         vers_decls   :: NameEnv Version
426                 -- Versions for "big" names only (not data constructors, class ops)
427                 -- The version of an Id changes if its fixity changes
428                 -- Ditto data constructors, class operations, except that the version of
429                 -- the parent class/tycon changes
430                 --
431                 -- If a name isn't in the map, it means 'initialVersion'
432     }
433
434 initialVersionInfo :: VersionInfo
435 initialVersionInfo = VersionInfo { vers_module  = initialVersion,
436                                    vers_exports = initialVersion,
437                                    vers_rules   = initialVersion,
438                                    vers_decls   = emptyNameEnv
439                         }
440
441 lookupVersion :: NameEnv Version -> Name -> Version
442 lookupVersion env name = lookupNameEnv env name `orElse` initialVersion
443
444 data Deprecations = NoDeprecs
445                   | DeprecAll DeprecTxt                         -- Whole module deprecated
446                   | DeprecSome (NameEnv (Name,DeprecTxt))       -- Some things deprecated
447                                                                 -- Just "big" names
448                 -- We keep the Name in the range, so we can print them out
449
450 lookupDeprec :: Deprecations -> Name -> Maybe DeprecTxt
451 lookupDeprec NoDeprecs        name = Nothing
452 lookupDeprec (DeprecAll  txt) name = Just txt
453 lookupDeprec (DeprecSome env) name = case lookupNameEnv env name of
454                                             Just (_, txt) -> Just txt
455                                             Nothing       -> Nothing
456
457 instance Eq Deprecations where
458   -- Used when checking whether we need write a new interface
459   NoDeprecs       == NoDeprecs       = True
460   (DeprecAll t1)  == (DeprecAll t2)  = t1 == t2
461   (DeprecSome e1) == (DeprecSome e2) = nameEnvElts e1 == nameEnvElts e2
462   d1              == d2              = False
463 \end{code}
464
465
466 \begin{code}
467 type Avails       = [AvailInfo]
468 type AvailInfo    = GenAvailInfo Name
469 type RdrAvailInfo = GenAvailInfo OccName
470
471 data GenAvailInfo name  = Avail name     -- An ordinary identifier
472                         | AvailTC name   -- The name of the type or class
473                                   [name] -- The available pieces of type/class.
474                                          -- NB: If the type or class is itself
475                                          -- to be in scope, it must be in this list.
476                                          -- Thus, typically: AvailTC Eq [Eq, ==, /=]
477                         deriving( Eq )
478                         -- Equality used when deciding if the interface has changed
479
480 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
481
482 emptyAvailEnv :: AvailEnv
483 emptyAvailEnv = emptyNameEnv
484                                 
485 instance Outputable n => Outputable (GenAvailInfo n) where
486    ppr = pprAvail
487
488 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
489 pprAvail (AvailTC n ns) = ppr n <> case {- filter (/= n) -} ns of
490                                         []  -> empty
491                                         ns' -> braces (hsep (punctuate comma (map ppr ns')))
492
493 pprAvail (Avail n) = ppr n
494 \end{code}
495
496
497 %************************************************************************
498 %*                                                                      *
499 \subsection{ModIface}
500 %*                                                                      *
501 %************************************************************************
502
503 \begin{code}
504 type WhetherHasOrphans   = Bool
505         -- An "orphan" is 
506         --      * an instance decl in a module other than the defn module for 
507         --              one of the tycons or classes in the instance head
508         --      * a transformation rule in a module other than the one defining
509         --              the function in the head of the rule.
510
511 type IsBootInterface     = Bool
512
513 type ImportVersion name  = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)
514
515 data WhatsImported name  = NothingAtAll                         -- The module is below us in the
516                                                                 -- hierarchy, but we import nothing
517
518                          | Everything Version           -- Used for modules from other packages;
519                                                         -- we record only the module's version number
520
521                          | Specifically 
522                                 Version                 -- Module version
523                                 (Maybe Version)         -- Export-list version, if we depend on it
524                                 [(name,Version)]        -- List guaranteed non-empty
525                                 Version                 -- Rules version
526
527                          deriving( Eq )
528         -- 'Specifically' doesn't let you say "I imported f but none of the rules in
529         -- the module". If you use anything in the module you get its rule version
530         -- So if the rules change, you'll recompile, even if you don't use them.
531         -- This is easy to implement, and it's safer: you might not have used the rules last
532         -- time round, but if someone has added a new rule you might need it this time
533
534         -- The export list field is (Just v) if we depend on the export list:
535         --      we imported the module without saying exactly what we imported
536         -- We need to recompile if the module exports changes, because we might
537         -- now have a name clash in the importing module.
538
539 type IsExported = Name -> Bool          -- True for names that are exported from this module
540 \end{code}
541
542
543 %************************************************************************
544 %*                                                                      *
545 \subsection{The persistent compiler state}
546 %*                                                                      *
547 %************************************************************************
548
549 The @PersistentCompilerState@ persists across successive calls to the
550 compiler.
551
552   * A ModIface for each non-home-package module
553
554   * An accumulated TypeEnv from all the modules in imported packages
555
556   * An accumulated InstEnv from all the modules in imported packages
557     The point is that we don't want to keep recreating it whenever
558     we compile a new module.  The InstEnv component of pcPST is empty.
559     (This means we might "see" instances that we shouldn't "really" see;
560     but the Haskell Report is vague on what is meant to be visible, 
561     so we just take the easy road here.)
562
563   * Ditto for rules
564  
565   * The persistent renamer state
566
567 \begin{code}
568 data PersistentCompilerState 
569    = PCS {
570         pcs_PIT :: !PackageIfaceTable,  -- Domain = non-home-package modules
571                                         --   the mi_decls component is empty
572
573         pcs_PTE :: !PackageTypeEnv,     -- Domain = non-home-package modules
574                                         --   except that the InstEnv components is empty
575
576         pcs_insts :: !PackageInstEnv,   -- The total InstEnv accumulated from all
577                                         --   the non-home-package modules
578
579         pcs_rules :: !PackageRuleBase,  -- Ditto RuleEnv
580
581         pcs_PRS :: !PersistentRenamerState
582      }
583 \end{code}
584
585
586 The persistent renamer state contains:
587
588   * A name supply, which deals with allocating unique names to
589     (Module,OccName) original names, 
590  
591   * A "holding pen" for declarations that have been read out of
592     interface files but not yet sucked in, renamed, and typechecked
593
594 \begin{code}
595 type PackageTypeEnv  = TypeEnv
596 type PackageRuleBase = RuleBase
597 type PackageInstEnv  = InstEnv
598
599 data PersistentRenamerState
600   = PRS { prsOrig    :: !NameSupply,
601           prsImpMods :: !ImportedModuleInfo,
602
603                 -- Holding pens for stuff that has been read in
604                 -- but not yet slurped into the renamer
605           prsDecls   :: !DeclsMap,
606           prsInsts   :: !IfaceInsts,
607           prsRules   :: !IfaceRules
608     }
609 \end{code}
610
611 The NameSupply makes sure that there is just one Unique assigned for
612 each original name; i.e. (module-name, occ-name) pair.  The Name is
613 always stored as a Global, and has the SrcLoc of its binding location.
614 Actually that's not quite right.  When we first encounter the original
615 name, we might not be at its binding site (e.g. we are reading an
616 interface file); so we give it 'noSrcLoc' then.  Later, when we find
617 its binding site, we fix it up.
618
619 Exactly the same is true of the Module stored in the Name.  When we first
620 encounter the occurrence, we may not know the details of the module, so
621 we just store junk.  Then when we find the binding site, we fix it up.
622
623 \begin{code}
624 data NameSupply
625  = NameSupply { nsUniqs :: UniqSupply,
626                 -- Supply of uniques
627                 nsNames :: OrigNameCache,
628                 -- Ensures that one original name gets one unique
629                 nsIPs   :: OrigIParamCache
630                 -- Ensures that one implicit parameter name gets one unique
631    }
632
633 type OrigNameCache   = FiniteMap (ModuleName,OccName) Name
634 type OrigIParamCache = FiniteMap (IPName RdrName) (IPName Name)
635 \end{code}
636
637 @ImportedModuleInfo@ contains info ONLY about modules that have not yet 
638 been loaded into the iPIT.  These modules are mentioned in interfaces we've
639 already read, so we know a tiny bit about them, but we havn't yet looked
640 at the interface file for the module itself.  It needs to persist across 
641 invocations of the renamer, at least from Rename.checkOldIface to Rename.renameSource.
642 And there's no harm in it persisting across multiple compilations.
643
644 \begin{code}
645 type ImportedModuleInfo = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface)
646 \end{code}
647
648 A DeclsMap contains a binding for each Name in the declaration
649 including the constructors of a type decl etc.  The Bool is True just
650 for the 'main' Name.
651
652 \begin{code}
653 type DeclsMap = (NameEnv (AvailInfo, Bool, (Module, RdrNameTyClDecl)), Int)
654                                                 -- The Int says how many have been sucked in
655
656 type IfaceInsts = GatedDecls RdrNameInstDecl
657 type IfaceRules = GatedDecls RdrNameRuleDecl
658
659 type GatedDecls d = (Bag (GatedDecl d), Int)    -- The Int says how many have been sucked in
660 type GatedDecl  d = (GateFn, (Module, d))
661 type GateFn       = (Name -> Bool) -> Bool      -- Returns True <=> gate is open
662                                                 -- The (Name -> Bool) fn returns True for visible Names
663         -- For example, suppose this is in an interface file
664         --      instance C T where ...
665         -- We want to slurp this decl if both C and T are "visible" in 
666         -- the importing module.  See "The gating story" in RnIfaces for details.
667 \end{code}
668
669
670 %************************************************************************
671 %*                                                                      *
672 \subsection{Provenance and export info}
673 %*                                                                      *
674 %************************************************************************
675
676 A LocalRdrEnv is used for local bindings (let, where, lambda, case)
677
678 \begin{code}
679 type LocalRdrEnv = RdrNameEnv Name
680
681 extendLocalRdrEnv :: LocalRdrEnv -> [Name] -> LocalRdrEnv
682 extendLocalRdrEnv env names
683   = addListToRdrEnv env [(mkRdrUnqual (nameOccName n), n) | n <- names]
684 \end{code}
685
686 The GlobalRdrEnv gives maps RdrNames to Names.  There is a separate
687 one for each module, corresponding to that module's top-level scope.
688
689 \begin{code}
690 type GlobalRdrEnv = RdrNameEnv [GlobalRdrElt]
691         -- The list is because there may be name clashes
692         -- These only get reported on lookup, not on construction
693
694 data GlobalRdrElt = GRE Name Provenance (Maybe DeprecTxt)
695         -- The Maybe DeprecTxt tells whether this name is deprecated
696
697 pprGlobalRdrEnv env
698   = vcat (map pp (rdrEnvToList env))
699   where
700     pp (rn, nps) = ppr rn <> colon <+> 
701                    vcat [ppr n <+> pprNameProvenance n p | (GRE n p _) <- nps]
702 \end{code}
703
704 The "provenance" of something says how it came to be in scope.
705
706 \begin{code}
707 data Provenance
708   = LocalDef                    -- Defined locally
709
710   | NonLocalDef                 -- Defined non-locally
711         ImportReason
712
713 -- Just used for grouping error messages (in RnEnv.warnUnusedBinds)
714 instance Eq Provenance where
715   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
716
717 instance Eq ImportReason where
718   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
719
720 instance Ord Provenance where
721    compare LocalDef LocalDef = EQ
722    compare LocalDef (NonLocalDef _) = LT
723    compare (NonLocalDef _) LocalDef = GT
724
725    compare (NonLocalDef reason1) (NonLocalDef reason2) 
726       = compare reason1 reason2
727
728 instance Ord ImportReason where
729    compare ImplicitImport ImplicitImport = EQ
730    compare ImplicitImport (UserImport _ _ _) = LT
731    compare (UserImport _ _ _) ImplicitImport = GT
732    compare (UserImport m1 loc1 _) (UserImport m2 loc2 _) 
733       = (m1 `compare` m2) `thenCmp` (loc1 `compare` loc2)
734
735
736 data ImportReason
737   = UserImport Module SrcLoc Bool       -- Imported from module M on line L
738                                         -- Note the M may well not be the defining module
739                                         -- for this thing!
740         -- The Bool is true iff the thing was named *explicitly* in the import spec,
741         -- rather than being imported as part of a group; e.g.
742         --      import B
743         --      import C( T(..) )
744         -- Here, everything imported by B, and the constructors of T
745         -- are not named explicitly; only T is named explicitly.
746         -- This info is used when warning of unused names.
747
748   | ImplicitImport                      -- Imported implicitly for some other reason
749 \end{code}
750
751 \begin{code}
752 hasBetterProv :: Provenance -> Provenance -> Bool
753 -- Choose 
754 --      a local thing                 over an   imported thing
755 --      a user-imported thing         over a    non-user-imported thing
756 --      an explicitly-imported thing  over an   implicitly imported thing
757 hasBetterProv LocalDef                            _                            = True
758 hasBetterProv (NonLocalDef (UserImport _ _ _   )) (NonLocalDef ImplicitImport) = True
759 hasBetterProv _                                   _                            = False
760
761 pprNameProvenance :: Name -> Provenance -> SDoc
762 pprNameProvenance name LocalDef          = ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
763 pprNameProvenance name (NonLocalDef why) = sep [ppr_reason why, 
764                                                 nest 2 (ppr_defn (nameSrcLoc name))]
765
766 ppr_reason ImplicitImport         = ptext SLIT("implicitly imported")
767 ppr_reason (UserImport mod loc _) = ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc
768
769 ppr_defn loc | isGoodSrcLoc loc = parens (ptext SLIT("at") <+> ppr loc)
770              | otherwise        = empty
771 \end{code}