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