HscTypes.lhs 23.9 KB
Newer Older
1
2
3
4
5
6
%
% (c) The University of Glasgow, 2000
%
\section[HscTypes]{Types for the per-module compiler}

\begin{code}
7
module HscTypes ( 
8
9
	GhciMode(..),

10
	ModuleLocation(..),
11

12
	ModDetails(..),	ModIface(..), 
13
14
	HomeSymbolTable, emptySymbolTable,
	PackageTypeEnv,
15
	HomeIfaceTable, PackageIfaceTable, emptyIfaceTable,
16
	lookupIface, lookupIfaceByModName,
17
	emptyModIface,
18

19
20
	InteractiveContext(..),

21
	IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
22

23
	VersionInfo(..), initialVersionInfo, lookupVersion,
24

25
	TyThing(..), isTyClThing, implicitTyThingIds,
26

27
28
	TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
	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, GenAvailInfo(..), AvailInfo, RdrAvailInfo, 
36
	PersistentCompilerState(..),
37

38
39
	Deprecations(..), lookupDeprec,

40
	InstEnv, ClsInstEnv, DFunId,
41
	PackageInstEnv, PackageRuleBase,
42

43
44
45
	GlobalRdrEnv, GlobalRdrElt(..), pprGlobalRdrEnv,
	LocalRdrEnv, extendLocalRdrEnv,
	
46

47
	-- Provenance
48
	Provenance(..), ImportReason(..), 
49
        pprNameProvenance, hasBetterProv
50
51

    ) where
52
53
54

#include "HsVersions.h"

55
56
import RdrName		( RdrNameEnv, addListToRdrEnv, emptyRdrEnv, mkRdrUnqual, rdrEnvToList )
import Name		( Name, NamedThing, getName, nameOccName, nameModule, nameSrcLoc )
57
import NameEnv
58
import OccName		( OccName )
59
import Module		( Module, ModuleName, ModuleEnv,
60
			  lookupModuleEnv, lookupModuleEnvByName, emptyModuleEnv
61
			)
62
import InstEnv		( InstEnv, ClsInstEnv, DFunId )
63
import Rules		( RuleBase )
64
import CoreSyn		( CoreBind )
65
import Id		( Id )
66
import Class		( Class, classSelIds )
67
import TyCon		( TyCon, isNewTyCon, tyConGenIds, tyConSelIds, tyConDataConsIfAvailable )
68
import DataCon		( dataConId, dataConWrapId )
69

70
import BasicTypes	( Version, initialVersion, Fixity )
71

72
import HsSyn		( DeprecTxt, tyClDeclName, ifaceRuleDeclName )
73
import RdrHsSyn		( RdrNameInstDecl, RdrNameRuleDecl, RdrNameTyClDecl )
74
import RnHsSyn		( RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl )
75

76
import CoreSyn		( IdCoreRule )
77

78
import FiniteMap	( FiniteMap )
79
import Bag		( Bag )
80
import Maybes		( seqMaybe, orElse )
81
82
import Outputable
import SrcLoc		( SrcLoc, isGoodSrcLoc )
83
import Util		( thenCmp, sortLt )
84
import UniqSupply	( UniqSupply )
85
86
\end{code}

87
88
89
90
91
92
93
94
95
96
97
98
%************************************************************************
%*									*
\subsection{Which mode we're in
%*									*
%************************************************************************

\begin{code}
data GhciMode = Batch | Interactive | OneShot 
     deriving Eq
\end{code}


99
100
%************************************************************************
%*									*
101
\subsection{Module locations}
102
103
104
105
106
107
%*									*
%************************************************************************

\begin{code}
data ModuleLocation
   = ModuleLocation {
108
109
        ml_hs_file   :: Maybe FilePath,
        ml_hspp_file :: Maybe FilePath,  -- path of preprocessed source
110
        ml_hi_file   :: FilePath,
111
        ml_obj_file  :: Maybe FilePath
112
113
114
115
116
     }
     deriving Show

instance Outputable ModuleLocation where
   ppr = text . show
117
118
119
120
121
122
123
124
125
126
127
\end{code}

For a module in another package, the hs_file and obj_file
components of ModuleLocation are undefined.  

The locations specified by a ModuleLocation may or may not
correspond to actual files yet: for example, even if the object
file doesn't exist, the ModuleLocation still contains the path to
where the object file will reside if/when it is created.


128
129
%************************************************************************
%*									*
130
\subsection{Symbol tables and Module details}
131
132
133
%*									*
%************************************************************************

134
135
136
137
A @ModIface@ plus a @ModDetails@ summarises everything we know 
about a compiled module.  The @ModIface@ is the stuff *before* linking,
and can be written out to an interface file.  The @ModDetails@ is after
linking; it is the "linked" form of the mi_decls field.
138
139

\begin{code}
140
141
data ModIface 
   = ModIface {
142
143
144
145
        mi_module   :: !Module,		    -- Complete with package info
        mi_version  :: !VersionInfo,	    -- Module version number
        mi_orphan   :: WhetherHasOrphans,   -- Whether this module has orphans
	mi_boot	    :: !IsBootInterface,    -- read from an hi-boot file?
146

147
148
149
150
        mi_usages   :: ![ImportVersion Name],	
		-- Usages; kept sorted so that it's easy to decide
		-- whether to write a new iface file (changing usages
		-- doesn't affect the version of this module)
151

152
153
154
        mi_exports  :: ![(ModuleName,Avails)],
		-- What it exports Kept sorted by (mod,occ), to make
		-- version comparisons easier
155

156
        mi_globals  :: !GlobalRdrEnv,	    -- Its top level environment
157

158
159
        mi_fixities :: !(NameEnv Fixity),   -- Fixities
	mi_deprecs  :: !Deprecations,	    -- Deprecations
160

161
	mi_decls    :: IfaceDecls	    -- The RnDecls form of ModDetails
162
     }
163

164
165
166
167
data IfaceDecls = IfaceDecls { dcl_tycl  :: [RenamedTyClDecl],	-- Sorted
			       dcl_rules :: [RenamedRuleDecl],	-- Sorted
			       dcl_insts :: [RenamedInstDecl] }	-- Unsorted

168
169
170
171
172
173
mkIfaceDecls :: [RenamedTyClDecl] -> [RenamedRuleDecl] -> [RenamedInstDecl] -> IfaceDecls
mkIfaceDecls tycls rules insts
  = IfaceDecls { dcl_tycl  = sortLt lt_tycl tycls,
		 dcl_rules = sortLt lt_rule rules,
		 dcl_insts = insts }
  where
174
175
    d1 `lt_tycl` d2 = tyClDeclName      d1 < tyClDeclName      d2
    r1 `lt_rule` r2 = ifaceRuleDeclName r1 < ifaceRuleDeclName r2
176
177


178
179
180
181
-- typechecker should only look at this, not ModIface
-- Should be able to construct ModDetails from mi_decls in ModIface
data ModDetails
   = ModDetails {
182
	-- The next three fields are created by the typechecker
183
184
185
186
        md_types    :: !TypeEnv,
        md_insts    :: ![DFunId],	-- Dfun-ids for the instances in this module
        md_rules    :: ![IdCoreRule],	-- Domain may include Ids from other modules
	md_binds    :: ![CoreBind]
187
     }
188
189
190
191

-- The ModDetails takes on several slightly different forms:
--
-- After typecheck + desugar
192
--	md_types	Contains TyCons, Classes, and implicit Ids
193
194
195
--	md_insts	All instances from this module (incl derived ones)
--	md_rules	All rules from this module
--	md_binds	Desugared bindings
196
197
--
-- After simplification
198
199
200
201
--	md_types	Same as after typecheck
--	md_insts	Ditto
--	md_rules	Orphan rules only (local ones now attached to binds)
--	md_binds	With rules attached
202
--
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
-- After CoreTidy
--	md_types	Now contains Ids as well, replete with final IdInfo
--			   The Ids are only the ones that are visible from
--			   importing modules.  Without -O that means only
--			   exported Ids, but with -O importing modules may
--			   see ids mentioned in unfoldings of exported Ids
--
--	md_insts	Same DFunIds as before, but with final IdInfo,
--			   and the unique might have changed; remember that
--			   CoreTidy links up the uniques of old and new versions
--
--	md_rules	All rules for exported things, substituted with final Ids
--
--	md_binds	Tidied
--
-- Passed back to compilation manager
--	Just as after CoreTidy, but with md_binds nuked

221
222
223
\end{code}

\begin{code}
224
225
226
emptyModIface :: Module -> ModIface
emptyModIface mod
  = ModIface { mi_module   = mod,
227
228
229
230
	       mi_version  = initialVersionInfo,
	       mi_usages   = [],
	       mi_orphan   = False,
	       mi_boot	   = False,
231
	       mi_exports  = [],
232
	       mi_fixities = emptyNameEnv,
233
	       mi_globals  = emptyRdrEnv,
234
235
	       mi_deprecs  = NoDeprecs,
	       mi_decls    = panic "emptyModIface: decls"
236
    }		
237
238
\end{code}

239
240
241
Symbol tables map modules to ModDetails:

\begin{code}
242
type SymbolTable	= ModuleEnv ModDetails
243
244
245
246
247
type IfaceTable		= ModuleEnv ModIface

type HomeIfaceTable     = IfaceTable
type PackageIfaceTable  = IfaceTable

248
type HomeSymbolTable    = SymbolTable	-- Domain = modules in the home package
249

250
251
252
emptySymbolTable :: SymbolTable
emptySymbolTable = emptyModuleEnv

253
emptyIfaceTable :: IfaceTable
254
emptyIfaceTable = emptyModuleEnv
255
256
\end{code}

257
Simple lookups in the symbol table.
258
259

\begin{code}
260
lookupIface :: HomeIfaceTable -> PackageIfaceTable -> Name -> Maybe ModIface
261
-- We often have two IfaceTables, and want to do a lookup
262
263
lookupIface hit pit name
  = lookupModuleEnv hit mod `seqMaybe` lookupModuleEnv pit mod
264
265
  where
    mod = nameModule name
266

267
268
269
lookupIfaceByModName :: HomeIfaceTable -> PackageIfaceTable -> ModuleName -> Maybe ModIface
-- We often have two IfaceTables, and want to do a lookup
lookupIfaceByModName hit pit mod
270
  = lookupModuleEnvByName hit mod `seqMaybe` lookupModuleEnvByName pit mod
271
272
273
\end{code}


274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
%************************************************************************
%*									*
\subsection{The interactive context}
%*									*
%************************************************************************

\begin{code}
data InteractiveContext 
  = InteractiveContext { 
	ic_module :: Module,		-- The current module in which 
					-- the  user is sitting

	ic_rn_env :: LocalRdrEnv,	-- Lexical context for variables bound
					-- during interaction

	ic_type_env :: TypeEnv		-- Ditto for types
    }
\end{code}


294
295
296
297
298
299
300
301
302
303
%************************************************************************
%*									*
\subsection{Type environment stuff}
%*									*
%************************************************************************

\begin{code}
data TyThing = AnId   Id
	     | ATyCon TyCon
	     | AClass Class
304

305
306
307
308
309
isTyClThing :: TyThing -> Bool
isTyClThing (ATyCon _) = True
isTyClThing (AClass _) = True
isTyClThing (AnId   _) = False

310
311
312
313
instance NamedThing TyThing where
  getName (AnId id)   = getName id
  getName (ATyCon tc) = getName tc
  getName (AClass cl) = getName cl
314

315
316
317
318
319
instance Outputable TyThing where
  ppr (AnId   id) = ptext SLIT("AnId")   <+> ppr id
  ppr (ATyCon tc) = ptext SLIT("ATyCon") <+> ppr tc
  ppr (AClass cl) = ptext SLIT("AClass") <+> ppr cl

320
321
322
323
324
325
326
327
328
329

typeEnvElts    :: TypeEnv -> [TyThing]
typeEnvClasses :: TypeEnv -> [Class]
typeEnvTyCons  :: TypeEnv -> [TyCon]
typeEnvIds     :: TypeEnv -> [Id]

typeEnvElts    env = nameEnvElts env
typeEnvClasses env = [cl | AClass cl <- typeEnvElts env]
typeEnvTyCons  env = [tc | ATyCon tc <- typeEnvElts env] 
typeEnvIds     env = [id | AnId id   <- typeEnvElts env] 
330

331
332
333
334
335
336
337
338
339
340
implicitTyThingIds :: [TyThing] -> [Id]
-- Add the implicit data cons and selectors etc 
implicitTyThingIds things
  = concat (map go things)
  where
    go (AnId f)    = []
    go (AClass cl) = classSelIds cl
    go (ATyCon tc) = tyConGenIds tc ++
		     tyConSelIds tc ++
		     [ n | dc <- tyConDataConsIfAvailable tc, 
341
			   n  <- implicitConIds tc dc]
342
		-- Synonyms return empty list of constructors and selectors
343
344
345
346
347

    implicitConIds tc dc	-- Newtypes have a constructor wrapper,
				-- but no worker
	| isNewTyCon tc = [dataConWrapId dc]
	| otherwise     = [dataConId dc, dataConWrapId dc]
348
349
350
351
\end{code}


\begin{code}
352
type TypeEnv = NameEnv TyThing
353

354
emptyTypeEnv = emptyNameEnv
355

356
357
mkTypeEnv :: [TyThing] -> TypeEnv
mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
358
		
359
360
extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
extendTypeEnvList env things
361
362
363
364
365
  = extendNameEnvList env [(getName thing, thing) | thing <- things]

extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
extendTypeEnvWithIds env ids
  = extendNameEnvList env [(getName id, AnId id) | id <- ids]
366
367
\end{code}

368
369
370
\begin{code}
lookupType :: HomeSymbolTable -> PackageTypeEnv -> Name -> Maybe TyThing
lookupType hst pte name
371
  = case lookupModuleEnv hst (nameModule name) of
372
373
374
	Just details -> lookupNameEnv (md_types details) name
	Nothing	     -> lookupNameEnv pte name
\end{code}
375
376
377
378
379
380
381
382
383

%************************************************************************
%*									*
\subsection{Auxiliary types}
%*									*
%************************************************************************

These types are defined here because they are mentioned in ModDetails,
but they are mostly elaborated elsewhere
384
385

\begin{code}
386
387
data VersionInfo 
  = VersionInfo {
388
389
390
391
392
393
394
395
	vers_module  :: Version,	-- Changes when anything changes
	vers_exports :: Version,	-- Changes when export list changes
	vers_rules   :: Version,	-- Changes when any rule changes
	vers_decls   :: NameEnv Version
		-- Versions for "big" names only (not data constructors, class ops)
		-- The version of an Id changes if its fixity changes
		-- Ditto data constructors, class operations, except that the version of
		-- the parent class/tycon changes
396
397
		--
		-- If a name isn't in the map, it means 'initialVersion'
398
    }
399

400
401
402
403
initialVersionInfo :: VersionInfo
initialVersionInfo = VersionInfo { vers_module  = initialVersion,
				   vers_exports = initialVersion,
				   vers_rules   = initialVersion,
404
405
406
407
408
				   vers_decls   = emptyNameEnv
			}

lookupVersion :: NameEnv Version -> Name -> Version
lookupVersion env name = lookupNameEnv env name `orElse` initialVersion
409

410
data Deprecations = NoDeprecs
411
412
413
414
	 	  | DeprecAll DeprecTxt				-- Whole module deprecated
		  | DeprecSome (NameEnv (Name,DeprecTxt))	-- Some things deprecated
								-- Just "big" names
		-- We keep the Name in the range, so we can print them out
415

416
417
418
419
420
421
lookupDeprec :: Deprecations -> Name -> Maybe DeprecTxt
lookupDeprec NoDeprecs        name = Nothing
lookupDeprec (DeprecAll  txt) name = Just txt
lookupDeprec (DeprecSome env) name = case lookupNameEnv env name of
					    Just (_, txt) -> Just txt
					    Nothing	  -> Nothing
422
423
424
425
426
427
428

instance Eq Deprecations where
  -- Used when checking whether we need write a new interface
  NoDeprecs       == NoDeprecs	     = True
  (DeprecAll t1)  == (DeprecAll t2)  = t1 == t2
  (DeprecSome e1) == (DeprecSome e2) = nameEnvElts e1 == nameEnvElts e2
  d1		  == d2		     = False
429
430
431
432
433
434
435
436
\end{code}


\begin{code}
type Avails	  = [AvailInfo]
type AvailInfo    = GenAvailInfo Name
type RdrAvailInfo = GenAvailInfo OccName

437
438
439
440
441
442
443
444
445
446
data GenAvailInfo name	= Avail name	 -- An ordinary identifier
			| AvailTC name 	 -- The name of the type or class
				  [name] -- The available pieces of type/class.
					 -- NB: If the type or class is itself
					 -- to be in scope, it must be in this list.
					 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
			deriving( Eq )
			-- Equality used when deciding if the interface has changed

type AvailEnv	  = NameEnv AvailInfo	-- Maps a Name to the AvailInfo that contains it
447
448
449
450
451
452
453
454
455
456
				
instance Outputable n => Outputable (GenAvailInfo n) where
   ppr = pprAvail

pprAvail :: Outputable n => GenAvailInfo n -> SDoc
pprAvail (AvailTC n ns) = ppr n <> case {- filter (/= n) -} ns of
					[]  -> empty
					ns' -> braces (hsep (punctuate comma (map ppr ns')))

pprAvail (Avail n) = ppr n
457
458
459
460
461
462
463
464
465
466
\end{code}


%************************************************************************
%*									*
\subsection{ModIface}
%*									*
%************************************************************************

\begin{code}
467
468
469
470
471
472
473
474
475
type WhetherHasOrphans   = Bool
	-- An "orphan" is 
	-- 	* an instance decl in a module other than the defn module for 
	--		one of the tycons or classes in the instance head
	--	* a transformation rule in a module other than the one defining
	--		the function in the head of the rule.

type IsBootInterface     = Bool

476
477
type ImportVersion name  = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)

478
479
480
data WhatsImported name  = NothingAtAll				-- The module is below us in the
								-- hierarchy, but we import nothing

481
482
483
484
485
486
487
488
			 | Everything Version		-- Used for modules from other packages;
							-- we record only the module's version number

			 | Specifically 
				Version			-- Module version
				(Maybe Version)		-- Export-list version, if we depend on it
				[(name,Version)]	-- List guaranteed non-empty
				Version			-- Rules version
489
490

			 deriving( Eq )
491
492
493
	-- 'Specifically' doesn't let you say "I imported f but none of the rules in
	-- the module". If you use anything in the module you get its rule version
	-- So if the rules change, you'll recompile, even if you don't use them.
494
495
496
	-- This is easy to implement, and it's safer: you might not have used the rules last
	-- time round, but if someone has added a new rule you might need it this time

497
498
499
500
	-- The export list field is (Just v) if we depend on the export list:
	--	we imported the module without saying exactly what we imported
	-- We need to recompile if the module exports changes, because we might
	-- now have a name clash in the importing module.
501
502

type IsExported = Name -> Bool		-- True for names that are exported from this module
503
504
\end{code}

505

506
507
508
509
510
511
512
513
514
%************************************************************************
%*									*
\subsection{The persistent compiler state}
%*									*
%************************************************************************

\begin{code}
data PersistentCompilerState 
   = PCS {
515
        pcs_PIT :: !PackageIfaceTable,	-- Domain = non-home-package modules
516
					--   the mi_decls component is empty
517

518
        pcs_PTE :: !PackageTypeEnv,	-- Domain = non-home-package modules
519
					--   except that the InstEnv components is empty
520

521
	pcs_insts :: !PackageInstEnv,	-- The total InstEnv accumulated from all
522
					--   the non-home-package modules
523

524
	pcs_rules :: !PackageRuleBase,	-- Ditto RuleEnv
525

526
        pcs_PRS :: !PersistentRenamerState
527
     }
528
529
530
531
\end{code}

The @PersistentRenamerState@ persists across successive calls to the
compiler.
532

533
It contains:
534
  * A name supply, which deals with allocating unique names to
535
536
    (Module,OccName) original names, 
 
537
538
539
  * An accumulated TypeEnv from all the modules in imported packages

  * An accumulated InstEnv from all the modules in imported packages
540
541
542
543
544
545
546
547
548
    The point is that we don't want to keep recreating it whenever
    we compile a new module.  The InstEnv component of pcPST is empty.
    (This means we might "see" instances that we shouldn't "really" see;
    but the Haskell Report is vague on what is meant to be visible, 
    so we just take the easy road here.)

  * Ditto for rules

  * A "holding pen" for declarations that have been read out of
549
550
551
    interface files but not yet sucked in, renamed, and typechecked

\begin{code}
552
type PackageTypeEnv  = TypeEnv
553
554
555
type PackageRuleBase = RuleBase
type PackageInstEnv  = InstEnv

556
data PersistentRenamerState
557
558
559
560
561
  = PRS { prsOrig    :: !NameSupply,
	  prsImpMods :: !ImportedModuleInfo,
	  prsDecls   :: !DeclsMap,
	  prsInsts   :: !IfaceInsts,
	  prsRules   :: !IfaceRules
562
    }
563
564
\end{code}

565
The NameSupply makes sure that there is just one Unique assigned for
566
567
568
569
570
571
572
573
574
575
each original name; i.e. (module-name, occ-name) pair.  The Name is
always stored as a Global, and has the SrcLoc of its binding location.
Actually that's not quite right.  When we first encounter the original
name, we might not be at its binding site (e.g. we are reading an
interface file); so we give it 'noSrcLoc' then.  Later, when we find
its binding site, we fix it up.

Exactly the same is true of the Module stored in the Name.  When we first
encounter the occurrence, we may not know the details of the module, so
we just store junk.  Then when we find the binding site, we fix it up.
576

577
\begin{code}
578
579
data NameSupply
 = NameSupply { nsUniqs :: UniqSupply,
580
		-- Supply of uniques
581
		nsNames :: OrigNameCache,
582
		-- Ensures that one original name gets one unique
583
		nsIPs   :: OrigIParamCache
584
		-- Ensures that one implicit parameter name gets one unique
585
   }
586

587
588
type OrigNameCache   = FiniteMap (ModuleName,OccName) Name
type OrigIParamCache = FiniteMap OccName Name
589
\end{code}
590

591
592
593
594
595
596
597
598
599
600
@ImportedModuleInfo@ contains info ONLY about modules that have not yet 
been loaded into the iPIT.  These modules are mentioned in interfaces we've
already read, so we know a tiny bit about them, but we havn't yet looked
at the interface file for the module itself.  It needs to persist across 
invocations of the renamer, at least from Rename.checkOldIface to Rename.renameSource.
And there's no harm in it persisting across multiple compilations.

\begin{code}
type ImportedModuleInfo = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface)
\end{code}
601
602
603
604
605
606

A DeclsMap contains a binding for each Name in the declaration
including the constructors of a type decl etc.  The Bool is True just
for the 'main' Name.

\begin{code}
607
608
type DeclsMap = (NameEnv (AvailInfo, Bool, (Module, RdrNameTyClDecl)), Int)
						-- The Int says how many have been sucked in
609

610
611
type IfaceInsts = GatedDecls RdrNameInstDecl
type IfaceRules = GatedDecls RdrNameRuleDecl
612

613
type GatedDecls d = (Bag (GatedDecl d), Int)	-- The Int says how many have been sucked in
614
615
616
617
618
619
620
type GatedDecl  d = (GateFn, (Module, d))
type GateFn       = (Name -> Bool) -> Bool	-- Returns True <=> gate is open
						-- The (Name -> Bool) fn returns True for visible Names
	-- For example, suppose this is in an interface file
	--	instance C T where ...
	-- We want to slurp this decl if both C and T are "visible" in 
	-- the importing module.  See "The gating story" in RnIfaces for details.
621
622
\end{code}

623

624
625
626
627
628
629
%************************************************************************
%*									*
\subsection{Provenance and export info}
%*									*
%************************************************************************

630
631
632
633
634
635
636
637
638
639
A LocalRdrEnv is used for local bindings (let, where, lambda, case)

\begin{code}
type LocalRdrEnv = RdrNameEnv Name

extendLocalRdrEnv :: LocalRdrEnv -> [Name] -> LocalRdrEnv
extendLocalRdrEnv env names
  = addListToRdrEnv env [(mkRdrUnqual (nameOccName n), n) | n <- names]
\end{code}

640
641
642
643
The GlobalRdrEnv gives maps RdrNames to Names.  There is a separate
one for each module, corresponding to that module's top-level scope.

\begin{code}
644
645
646
647
648
649
type GlobalRdrEnv = RdrNameEnv [GlobalRdrElt]
	-- The list is because there may be name clashes
	-- These only get reported on lookup, not on construction

data GlobalRdrElt = GRE Name Provenance (Maybe DeprecTxt)
	-- The Maybe DeprecTxt tells whether this name is deprecated
650
651
652
653
654

pprGlobalRdrEnv env
  = vcat (map pp (rdrEnvToList env))
  where
    pp (rn, nps) = ppr rn <> colon <+> 
655
		   vcat [ppr n <+> pprNameProvenance n p | (GRE n p _) <- nps]
656
657
658
659
660
661
662
663
664
665
666
\end{code}

The "provenance" of something says how it came to be in scope.

\begin{code}
data Provenance
  = LocalDef			-- Defined locally

  | NonLocalDef  		-- Defined non-locally
	ImportReason

667
668
669
670
671
672
673
674
675
-- Just used for grouping error messages (in RnEnv.warnUnusedBinds)
instance Eq Provenance where
  p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False

instance Eq ImportReason where
  p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False

instance Ord Provenance where
   compare LocalDef LocalDef = EQ
676
677
   compare LocalDef (NonLocalDef _) = LT
   compare (NonLocalDef _) LocalDef = GT
678

679
   compare (NonLocalDef reason1) (NonLocalDef reason2) 
680
681
682
683
684
685
686
687
688
689
      = compare reason1 reason2

instance Ord ImportReason where
   compare ImplicitImport ImplicitImport = EQ
   compare ImplicitImport (UserImport _ _ _) = LT
   compare (UserImport _ _ _) ImplicitImport = GT
   compare (UserImport m1 loc1 _) (UserImport m2 loc2 _) 
      = (m1 `compare` m2) `thenCmp` (loc1 `compare` loc2)


690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
data ImportReason
  = UserImport Module SrcLoc Bool	-- Imported from module M on line L
					-- Note the M may well not be the defining module
					-- for this thing!
	-- The Bool is true iff the thing was named *explicitly* in the import spec,
	-- rather than being imported as part of a group; e.g.
	--	import B
	--	import C( T(..) )
	-- Here, everything imported by B, and the constructors of T
	-- are not named explicitly; only T is named explicitly.
	-- This info is used when warning of unused names.

  | ImplicitImport			-- Imported implicitly for some other reason
\end{code}

\begin{code}
hasBetterProv :: Provenance -> Provenance -> Bool
-- Choose 
--	a local thing		      over an	imported thing
--	a user-imported thing	      over a	non-user-imported thing
-- 	an explicitly-imported thing  over an	implicitly imported thing
711
712
713
hasBetterProv LocalDef 				  _			       = True
hasBetterProv (NonLocalDef (UserImport _ _ _   )) (NonLocalDef ImplicitImport) = True
hasBetterProv _					  _			       = False
714

715
pprNameProvenance :: Name -> Provenance -> SDoc
716
717
pprNameProvenance name LocalDef   	 = ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
pprNameProvenance name (NonLocalDef why) = sep [ppr_reason why, 
718
					        nest 2 (ppr_defn (nameSrcLoc name))]
719
720
721
722

ppr_reason ImplicitImport	  = ptext SLIT("implicitly imported")
ppr_reason (UserImport mod loc _) = ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc

723
ppr_defn loc | isGoodSrcLoc loc = parens (ptext SLIT("at") <+> ppr loc)
724
725
	     | otherwise	= empty
\end{code}