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