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