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