[project @ 2002-10-25 15:23:03 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         HscEnv(..), 
9         GhciMode(..),
10
11         ModDetails(..), ModIface(..), 
12         ModGuts(..), ModImports(..), ForeignStubs(..),
13         ParsedIface(..), IfaceDeprecs,
14
15         HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
16
17         ExternalPackageState(..), 
18         PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
19         lookupIface, lookupIfaceByModName, moduleNameToModule,
20         emptyModIface,
21
22         InteractiveContext(..), emptyInteractiveContext, icPrintUnqual,
23
24         IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
25
26         VersionInfo(..), initialVersionInfo, lookupVersion,
27         FixityEnv, lookupFixity, collectFixities, emptyFixityEnv,
28
29         TyThing(..), isTyClThing, implicitTyThingIds,
30
31         TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
32         extendTypeEnvList, extendTypeEnvWithIds,
33         typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
34
35         WhetherHasOrphans, IsBootInterface, DeclsMap, Usage(..), 
36         Dependencies(..), noDependencies,
37         IfaceInsts, IfaceRules, GatedDecl, GatedDecls, GateFn, 
38         NameCache(..), OrigNameCache, OrigIParamCache,
39         Avails, availsToNameSet, availName, availNames,
40         GenAvailInfo(..), AvailInfo, RdrAvailInfo, 
41         ExportItem, RdrExportItem,
42
43         PersistentCompilerState(..),
44
45         Deprecations(..), lookupDeprec, plusDeprecs,
46
47         InstEnv, ClsInstEnv, DFunId,
48         PackageInstEnv, PackageRuleBase,
49
50         GlobalRdrEnv, GlobalRdrElt(..), emptyGlobalRdrEnv, pprGlobalRdrEnv,
51         LocalRdrEnv, extendLocalRdrEnv, isLocalGRE, unQualInScope,
52         
53         -- Linker stuff
54         Linkable(..), isObjectLinkable,
55         Unlinked(..), CompiledByteCode,
56         isObject, nameOfObject, isInterpretable, byteCodeOfObject,
57
58         -- Provenance
59         Provenance(..), ImportReason(..), 
60         pprNameProvenance, hasBetterProv
61
62     ) where
63
64 #include "HsVersions.h"
65
66 #ifdef GHCI
67 import ByteCodeAsm      ( CompiledByteCode )
68 #endif
69
70 import RdrName          ( RdrName, mkRdrUnqual, 
71                           RdrNameEnv, addListToRdrEnv, foldRdrEnv, isUnqual,
72                           rdrEnvToList, emptyRdrEnv )
73 import Name             ( Name, NamedThing, getName, nameOccName, nameModule, nameSrcLoc )
74 import NameEnv
75 import NameSet  
76 import OccName          ( OccName )
77 import Module
78 import InstEnv          ( InstEnv, ClsInstEnv, DFunId )
79 import Rules            ( RuleBase )
80 import CoreSyn          ( CoreBind )
81 import Id               ( Id )
82 import Class            ( Class, classSelIds )
83 import TyCon            ( TyCon, isNewTyCon, tyConGenIds, tyConSelIds, tyConDataCons_maybe )
84 import Type             ( TyThing(..), isTyClThing )
85 import DataCon          ( dataConWorkId, dataConWrapId )
86 import Packages         ( PackageName, basePackage )
87 import CmdLineOpts      ( DynFlags )
88
89 import BasicTypes       ( Version, initialVersion, IPName,
90                           Fixity, FixitySig(..), defaultFixity )
91
92 import HsSyn            ( DeprecTxt, TyClDecl, InstDecl, RuleDecl,
93                           tyClDeclName, ifaceRuleDeclName, tyClDeclNames,
94                           instDeclDFun )
95 import RnHsSyn          ( RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl )
96
97 import CoreSyn          ( IdCoreRule )
98 import PrelNames        ( isBuiltInSyntaxName )
99
100 import FiniteMap
101 import Bag              ( Bag )
102 import Maybes           ( orElse )
103 import Outputable
104 import SrcLoc           ( SrcLoc, isGoodSrcLoc )
105 import Util             ( thenCmp, sortLt )
106 import UniqSupply       ( UniqSupply )
107 import Maybe            ( fromJust )
108 import FastString       ( FastString )
109
110 import Time             ( ClockTime )
111 \end{code}
112
113
114 %************************************************************************
115 %*                                                                      *
116 \subsection{Compilation environment}
117 %*                                                                      *
118 %************************************************************************
119
120 The HscEnv gives the environment in which to compile a chunk of code.
121
122 \begin{code}
123 data HscEnv = HscEnv { hsc_mode   :: GhciMode,
124                        hsc_dflags :: DynFlags,
125                        hsc_HPT    :: HomePackageTable }
126 \end{code}
127
128 The GhciMode is self-explanatory:
129
130 \begin{code}
131 data GhciMode = Batch | Interactive | OneShot 
132               deriving Eq
133 \end{code}
134
135 \begin{code}
136 type HomePackageTable  = ModuleEnv HomeModInfo  -- Domain = modules in the home package
137 type PackageIfaceTable = ModuleEnv ModIface     -- Domain = modules in the imported packages
138
139 emptyHomePackageTable  = emptyModuleEnv
140 emptyPackageIfaceTable = emptyModuleEnv
141
142 data HomeModInfo = HomeModInfo { hm_iface    :: ModIface,
143                                  hm_details  :: ModDetails,
144                                  hm_linkable :: Linkable }
145 \end{code}
146
147 Simple lookups in the symbol table.
148
149 \begin{code}
150 lookupIface :: HomePackageTable -> PackageIfaceTable -> Module -> Maybe ModIface
151 -- We often have two IfaceTables, and want to do a lookup
152 lookupIface hpt pit mod
153   = case lookupModuleEnv hpt mod of
154         Just mod_info -> Just (hm_iface mod_info)
155         Nothing       -> lookupModuleEnv pit mod
156
157 lookupIfaceByModName :: HomePackageTable -> PackageIfaceTable -> ModuleName -> Maybe ModIface
158 -- We often have two IfaceTables, and want to do a lookup
159 lookupIfaceByModName hpt pit mod
160   = case lookupModuleEnvByName hpt mod of
161         Just mod_info -> Just (hm_iface mod_info)
162         Nothing       -> lookupModuleEnvByName pit mod
163 \end{code}
164
165 \begin{code}
166 -- Use instead of Finder.findModule if possible: this way doesn't
167 -- require filesystem operations, and it is guaranteed not to fail
168 -- when the IfaceTables are properly populated (i.e. after the renamer).
169 moduleNameToModule :: HomePackageTable -> PackageIfaceTable -> ModuleName -> Module
170 moduleNameToModule hpt pit mod 
171    = mi_module (fromJust (lookupIfaceByModName hpt pit mod))
172 \end{code}
173
174
175 %************************************************************************
176 %*                                                                      *
177 \subsection{Symbol tables and Module details}
178 %*                                                                      *
179 %************************************************************************
180
181 A @ModIface@ plus a @ModDetails@ summarises everything we know 
182 about a compiled module.  The @ModIface@ is the stuff *before* linking,
183 and can be written out to an interface file.  (The @ModDetails@ is after 
184 linking; it is the "linked" form of the mi_decls field.)
185
186 When we *read* an interface file, we also construct a @ModIface@ from it,
187 except that the mi_decls part is empty; when reading we consolidate
188 the declarations into a single indexed map in the @PersistentRenamerState@.
189
190 \begin{code}
191 data ModIface 
192    = ModIface {
193         mi_module   :: !Module,
194         mi_package  :: !PackageName,        -- Which package the module comes from
195         mi_version  :: !VersionInfo,        -- Version info for everything in this module
196         mi_orphan   :: !WhetherHasOrphans,  -- Whether this module has orphans
197         mi_boot     :: !IsBootInterface,    -- Read from an hi-boot file?
198
199         mi_deps     :: Dependencies,
200                 -- This is consulted for directly-imported modules, but
201                 -- not for anything else
202
203         mi_usages   :: [Usage Name],
204                 -- Usages; kept sorted so that it's easy to decide
205                 -- whether to write a new iface file (changing usages
206                 -- doesn't affect the version of this module)
207                 -- NOT STRICT!  we read this field lazily from the interface file
208                 -- It is *only* consulted by the recompilation checker
209
210         mi_exports  :: ![ExportItem],
211                 -- What it exports Kept sorted by (mod,occ), to make
212                 -- version comparisons easier
213
214         mi_globals  :: !(Maybe GlobalRdrEnv),
215                 -- Its top level environment or Nothing if we read this
216                 -- interface from an interface file.  (We need the source
217                 -- file to figure out the top-level environment.)
218
219         mi_fixities :: !FixityEnv,          -- Fixities
220         mi_deprecs  :: Deprecations,        -- Deprecations
221                 -- NOT STRICT!  we read this field lazilly from the interface file
222
223         mi_decls    :: IfaceDecls           -- The RnDecls form of ModDetails
224                 -- NOT STRICT!  we fill this field with _|_ sometimes
225      }
226
227 -- Should be able to construct ModDetails from mi_decls in ModIface
228 data ModDetails
229    = ModDetails {
230         -- The next three fields are created by the typechecker
231         md_types    :: !TypeEnv,
232         md_insts    :: ![DFunId],       -- Dfun-ids for the instances in this module
233         md_rules    :: ![IdCoreRule]    -- Domain may include Ids from other modules
234      }
235
236 -- A ModGuts is carried through the compiler, accumulating stuff as it goes
237 -- There is only one ModGuts at any time, the one for the module
238 -- being compiled right now.  Once it is compiled, a ModIface and 
239 -- ModDetails are extracted and the ModGuts is dicarded.
240
241 data ModGuts
242   = ModGuts {
243         mg_module   :: !Module,
244         mg_exports  :: !Avails,         -- What it exports
245         mg_deps     :: !Dependencies,   -- What is below it, directly or otherwise
246         mg_dir_imps :: ![Module],       -- Directly-imported modules; used to
247                                         --      generate initialisation code
248         mg_usages   :: ![Usage Name],   -- Version info for what it needed
249
250         mg_rdr_env  :: !GlobalRdrEnv,   -- Top-level lexical environment
251         mg_fix_env  :: !FixityEnv,      -- Fixity env, for things declared in this module
252         mg_deprecs  :: !Deprecations,   -- Deprecations declared in the module
253
254         mg_types    :: !TypeEnv,
255         mg_insts    :: ![DFunId],       -- Instances 
256         mg_rules    :: ![IdCoreRule],   -- Rules from this module
257         mg_binds    :: ![CoreBind],     -- Bindings for this module
258         mg_foreign  :: !ForeignStubs
259     }
260
261 -- The ModGuts takes on several slightly different forms:
262 --
263 -- After simplification, the following fields change slightly:
264 --      mg_rules        Orphan rules only (local ones now attached to binds)
265 --      mg_binds        With rules attached
266 --
267 -- After CoreTidy, the following fields change slightly:
268 --      mg_types        Now contains Ids as well, replete with final IdInfo
269 --                         The Ids are only the ones that are visible from
270 --                         importing modules.  Without -O that means only
271 --                         exported Ids, but with -O importing modules may
272 --                         see ids mentioned in unfoldings of exported Ids
273 --
274 --      mg_insts        Same DFunIds as before, but with final IdInfo,
275 --                         and the unique might have changed; remember that
276 --                         CoreTidy links up the uniques of old and new versions
277 --
278 --      mg_rules        All rules for exported things, substituted with final Ids
279 --
280 --      mg_binds        Tidied
281
282
283
284 data ModImports
285   = ModImports {
286         imp_direct     :: ![(Module,Bool)],     -- Explicitly-imported modules
287                                                 -- Boolean is true if we imported the whole
288                                                 --      module (apart, perhaps, from hiding some)
289         imp_pkg_mods   :: !ModuleSet,           -- Non-home-package modules on which we depend,
290                                                 --      directly or indirectly
291         imp_home_names :: !NameSet              -- Home package things on which we depend,
292                                                 --      directly or indirectly
293     }
294
295 data ForeignStubs = NoStubs
296                   | ForeignStubs
297                         SDoc            -- Header file prototypes for
298                                         --      "foreign exported" functions
299                         SDoc            -- C stubs to use when calling
300                                         --      "foreign exported" functions
301                         [FastString]    -- Headers that need to be included
302                                         --      into C code generated for this module
303                         [Id]            -- Foreign-exported binders
304                                         --      we have to generate code to register these
305
306
307 data IfaceDecls = IfaceDecls { dcl_tycl  :: [RenamedTyClDecl],  -- Sorted
308                                dcl_rules :: [RenamedRuleDecl],  -- Sorted
309                                dcl_insts :: [RenamedInstDecl] } -- Unsorted
310
311 mkIfaceDecls :: [RenamedTyClDecl] -> [RenamedRuleDecl] -> [RenamedInstDecl] -> IfaceDecls
312 -- Sort to put them in canonical order for version comparison
313 mkIfaceDecls tycls rules insts
314   = IfaceDecls { dcl_tycl  = sortLt lt_tycl tycls,
315                  dcl_rules = sortLt lt_rule rules,
316                  dcl_insts = sortLt lt_inst insts }
317   where
318     d1 `lt_tycl` d2 = tyClDeclName      d1 < tyClDeclName      d2
319     r1 `lt_rule` r2 = ifaceRuleDeclName r1 < ifaceRuleDeclName r2
320     i1 `lt_inst` i2 = instDeclDFun      i1 < instDeclDFun      i2
321 \end{code}
322
323 \begin{code}
324 emptyModIface :: Module -> ModIface
325 emptyModIface mod
326   = ModIface { mi_module   = mod,
327                mi_package  = basePackage, -- XXX fully bogus
328                mi_version  = initialVersionInfo,
329                mi_usages   = [],
330                mi_deps     = noDependencies,
331                mi_orphan   = False,
332                mi_boot     = False,
333                mi_exports  = [],
334                mi_fixities = emptyNameEnv,
335                mi_globals  = Nothing,
336                mi_deprecs  = NoDeprecs,
337                mi_decls    = panic "emptyModIface: decls"
338     }           
339 \end{code}
340
341
342 %************************************************************************
343 %*                                                                      *
344                 Parsed interface files
345 %*                                                                      *
346 %************************************************************************
347
348 A ParsedIface is exactly as read from an interface file.
349
350 \begin{code}
351 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
352         -- Nothing        => NoDeprecs
353         -- Just (Left t)  => DeprecAll
354         -- Just (Right p) => DeprecSome
355
356 data ParsedIface
357   = ParsedIface {
358       pi_mod       :: ModuleName,
359       pi_pkg       :: PackageName,
360       pi_vers      :: Version,                          -- Module version number
361       pi_orphan    :: WhetherHasOrphans,                -- Whether this module has orphans
362       pi_deps      :: Dependencies,                     -- What it depends on
363       pi_usages    :: [Usage OccName],                  -- Usages
364       pi_exports   :: (Version, [RdrExportItem]),       -- Exports
365       pi_decls     :: [(Version, TyClDecl RdrName)],    -- Local definitions
366       pi_fixity    :: [FixitySig RdrName],              -- Local fixity declarations,
367       pi_insts     :: [InstDecl RdrName],               -- Local instance declarations
368       pi_rules     :: (Version, [RuleDecl RdrName]),    -- Rules, with their version
369       pi_deprecs   :: IfaceDeprecs                      -- Deprecations
370     }
371 \end{code}
372
373
374 %************************************************************************
375 %*                                                                      *
376 \subsection{The interactive context}
377 %*                                                                      *
378 %************************************************************************
379
380 \begin{code}
381 data InteractiveContext 
382   = InteractiveContext { 
383         ic_toplev_scope :: [Module],    -- Include the "top-level" scope of
384                                         -- these modules
385
386         ic_exports :: [Module],         -- Include just the exports of these
387                                         -- modules
388
389         ic_rn_gbl_env :: GlobalRdrEnv,  -- The cached GlobalRdrEnv, built from
390                                         -- ic_toplev_scope and ic_exports
391
392         ic_rn_local_env :: LocalRdrEnv, -- Lexical context for variables bound
393                                         -- during interaction
394
395         ic_type_env :: TypeEnv          -- Ditto for types
396     }
397
398 emptyInteractiveContext
399   = InteractiveContext { ic_toplev_scope = [],
400                          ic_exports = [],
401                          ic_rn_gbl_env = emptyRdrEnv,
402                          ic_rn_local_env = emptyRdrEnv,
403                          ic_type_env = emptyTypeEnv }
404
405 icPrintUnqual :: InteractiveContext -> PrintUnqualified
406 icPrintUnqual ictxt = unQualInScope (ic_rn_gbl_env ictxt)
407 \end{code}
408
409
410 %************************************************************************
411 %*                                                                      *
412 \subsection{Type environment stuff}
413 %*                                                                      *
414 %************************************************************************
415
416 \begin{code}
417 typeEnvElts    :: TypeEnv -> [TyThing]
418 typeEnvClasses :: TypeEnv -> [Class]
419 typeEnvTyCons  :: TypeEnv -> [TyCon]
420 typeEnvIds     :: TypeEnv -> [Id]
421
422 typeEnvElts    env = nameEnvElts env
423 typeEnvClasses env = [cl | AClass cl <- typeEnvElts env]
424 typeEnvTyCons  env = [tc | ATyCon tc <- typeEnvElts env] 
425 typeEnvIds     env = [id | AnId id   <- typeEnvElts env] 
426
427 implicitTyThingIds :: [TyThing] -> [Id]
428 -- Add the implicit data cons and selectors etc 
429 implicitTyThingIds things
430   = concat (map go things)
431   where
432     go (AnId f)    = []
433     go (AClass cl) = classSelIds cl
434     go (ATyCon tc) = tyConGenIds tc ++
435                      tyConSelIds tc ++
436                      [ n | dc <- tyConDataCons_maybe tc `orElse` [],
437                            n  <- implicitConIds tc dc]
438                 -- Synonyms return empty list of constructors and selectors
439
440     implicitConIds tc dc        -- Newtypes have a constructor wrapper,
441                                 -- but no worker
442         | isNewTyCon tc = [dataConWrapId dc]
443         | otherwise     = [dataConWorkId dc, dataConWrapId dc]
444 \end{code}
445
446
447 \begin{code}
448 type TypeEnv = NameEnv TyThing
449
450 emptyTypeEnv = emptyNameEnv
451
452 mkTypeEnv :: [TyThing] -> TypeEnv
453 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
454                 
455 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
456 extendTypeEnvList env things
457   = extendNameEnvList env [(getName thing, thing) | thing <- things]
458
459 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
460 extendTypeEnvWithIds env ids
461   = extendNameEnvList env [(getName id, AnId id) | id <- ids]
462 \end{code}
463
464 \begin{code}
465 lookupType :: HomePackageTable -> PackageTypeEnv -> Name -> Maybe TyThing
466 lookupType hpt pte name
467   = case lookupModuleEnv hpt (nameModule name) of
468         Just details -> lookupNameEnv (md_types (hm_details details)) name
469         Nothing      -> lookupNameEnv pte name
470 \end{code}
471
472 %************************************************************************
473 %*                                                                      *
474 \subsection{Auxiliary types}
475 %*                                                                      *
476 %************************************************************************
477
478 These types are defined here because they are mentioned in ModDetails,
479 but they are mostly elaborated elsewhere
480
481 \begin{code}
482 data VersionInfo 
483   = VersionInfo {
484         vers_module  :: Version,        -- Changes when anything changes
485         vers_exports :: Version,        -- Changes when export list changes
486         vers_rules   :: Version,        -- Changes when any rule changes
487         vers_decls   :: NameEnv Version
488                 -- Versions for "big" names only (not data constructors, class ops)
489                 -- The version of an Id changes if its fixity changes
490                 -- Ditto data constructors, class operations, except that the version of
491                 -- the parent class/tycon changes
492                 --
493                 -- If a name isn't in the map, it means 'initialVersion'
494     }
495
496 initialVersionInfo :: VersionInfo
497 initialVersionInfo = VersionInfo { vers_module  = initialVersion,
498                                    vers_exports = initialVersion,
499                                    vers_rules   = initialVersion,
500                                    vers_decls   = emptyNameEnv
501                         }
502
503 lookupVersion :: NameEnv Version -> Name -> Version
504 lookupVersion env name = lookupNameEnv env name `orElse` initialVersion
505
506 data Deprecations = NoDeprecs
507                   | DeprecAll DeprecTxt                         -- Whole module deprecated
508                   | DeprecSome (NameEnv (Name,DeprecTxt))       -- Some things deprecated
509                                                                 -- Just "big" names
510                 -- We keep the Name in the range, so we can print them out
511
512 lookupDeprec :: Deprecations -> Name -> Maybe DeprecTxt
513 lookupDeprec NoDeprecs        name = Nothing
514 lookupDeprec (DeprecAll  txt) name = Just txt
515 lookupDeprec (DeprecSome env) name = case lookupNameEnv env name of
516                                             Just (_, txt) -> Just txt
517                                             Nothing       -> Nothing
518
519 plusDeprecs :: Deprecations -> Deprecations -> Deprecations
520 plusDeprecs d NoDeprecs = d
521 plusDeprecs NoDeprecs d = d
522 plusDeprecs d (DeprecAll t) = DeprecAll t
523 plusDeprecs (DeprecAll t) d = DeprecAll t
524 plusDeprecs (DeprecSome v1) (DeprecSome v2) = DeprecSome (v1 `plusNameEnv` v2)
525
526 instance Eq Deprecations where
527   -- Used when checking whether we need write a new interface
528   NoDeprecs       == NoDeprecs       = True
529   (DeprecAll t1)  == (DeprecAll t2)  = t1 == t2
530   (DeprecSome e1) == (DeprecSome e2) = nameEnvElts e1 == nameEnvElts e2
531   d1              == d2              = False
532 \end{code}
533
534
535 \begin{code}
536 type Avails       = [AvailInfo]
537 type AvailInfo    = GenAvailInfo Name
538 type RdrAvailInfo = GenAvailInfo OccName
539
540 data GenAvailInfo name  = Avail name     -- An ordinary identifier
541                         | AvailTC name   -- The name of the type or class
542                                   [name] -- The available pieces of type/class.
543                                          -- NB: If the type or class is itself
544                                          -- to be in scope, it must be in this list.
545                                          -- Thus, typically: AvailTC Eq [Eq, ==, /=]
546                         deriving( Eq )
547                         -- Equality used when deciding if the interface has changed
548
549 type RdrExportItem = (ModuleName, [RdrAvailInfo])
550 type ExportItem    = (ModuleName, [AvailInfo])
551
552 availsToNameSet :: [AvailInfo] -> NameSet
553 availsToNameSet avails = foldl add emptyNameSet avails
554                        where
555                          add set avail = addListToNameSet set (availNames avail)
556
557 availName :: GenAvailInfo name -> name
558 availName (Avail n)     = n
559 availName (AvailTC n _) = n
560
561 availNames :: GenAvailInfo name -> [name]
562 availNames (Avail n)      = [n]
563 availNames (AvailTC n ns) = ns
564
565 instance Outputable n => Outputable (GenAvailInfo n) where
566    ppr = pprAvail
567
568 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
569 pprAvail (AvailTC n ns) = ppr n <> case {- filter (/= n) -} ns of
570                                         []  -> empty
571                                         ns' -> braces (hsep (punctuate comma (map ppr ns')))
572
573 pprAvail (Avail n) = ppr n
574 \end{code}
575
576 \begin{code}
577 type FixityEnv = NameEnv (FixitySig Name)
578         -- We keep the whole fixity sig so that we
579         -- can report line-number info when there is a duplicate
580         -- fixity declaration
581
582 emptyFixityEnv :: FixityEnv
583 emptyFixityEnv = emptyNameEnv
584
585 lookupFixity :: FixityEnv -> Name -> Fixity
586 lookupFixity env n = case lookupNameEnv env n of
587                         Just (FixitySig _ fix _) -> fix
588                         Nothing                  -> defaultFixity
589
590 collectFixities :: FixityEnv -> [TyClDecl Name] -> [FixitySig Name]
591 -- Collect fixities for the specified declarations
592 collectFixities env decls
593   = [ fix
594     | d <- decls, (n,_) <- tyClDeclNames d,
595       Just fix <- [lookupNameEnv env n]
596     ]
597 \end{code}
598
599
600 %************************************************************************
601 %*                                                                      *
602 \subsection{WhatsImported}
603 %*                                                                      *
604 %************************************************************************
605
606 \begin{code}
607 type WhetherHasOrphans   = Bool
608         -- An "orphan" is 
609         --      * an instance decl in a module other than the defn module for 
610         --              one of the tycons or classes in the instance head
611         --      * a transformation rule in a module other than the one defining
612         --              the function in the head of the rule.
613
614 type IsBootInterface = Bool
615
616 -- Dependency info about modules and packages below this one
617 -- in the import hierarchy.  See TcRnTypes.ImportAvails for details.
618 --
619 -- Invariant: the dependencies of a module M never includes M
620 data Dependencies
621   = Deps { dep_mods  :: [(ModuleName,IsBootInterface)], -- Home-package module dependencies
622            dep_pkgs  :: [PackageName],                  -- External package dependencies
623            dep_orphs :: [ModuleName] }                  -- Orphan modules (whether home or external pkg)
624
625 noDependencies :: Dependencies
626 noDependencies = Deps [] [] []
627           
628 data Usage name 
629   = Usage { usg_name     :: ModuleName,         -- Name of the module
630             usg_mod      :: Version,            -- Module version
631             usg_exports  :: Maybe Version,      -- Export-list version, if we depend on it
632             usg_entities :: [(name,Version)],   -- Sorted by occurrence name
633             usg_rules    :: Version             -- Rules version
634     }       deriving( Eq )
635         -- This type doesn't let you say "I imported f but none of the rules in
636         -- the module". If you use anything in the module you get its rule version
637         -- So if the rules change, you'll recompile, even if you don't use them.
638         -- This is easy to implement, and it's safer: you might not have used the rules last
639         -- time round, but if someone has added a new rule you might need it this time
640
641         -- The export list field is (Just v) if we depend on the export list:
642         --      i.e. we imported the module without saying exactly what we imported
643         -- We need to recompile if the module exports changes, because we might
644         -- now have a name clash in the importing module.
645 \end{code}
646
647
648 %************************************************************************
649 %*                                                                      *
650 \subsection{The persistent compiler state}
651 %*                                                                      *
652 %************************************************************************
653
654 The @PersistentCompilerState@ persists across successive calls to the
655 compiler.
656
657 \begin{code}
658 data PersistentCompilerState 
659    = PCS {
660         pcs_nc  :: !NameCache,
661         pcs_EPS :: !ExternalPackageState
662      }
663 \end{code}
664
665
666 \begin{code}
667 type PackageTypeEnv  = TypeEnv
668 type PackageRuleBase = RuleBase
669 type PackageInstEnv  = InstEnv
670
671 data ExternalPackageState
672   = EPS {
673         eps_PIT :: !PackageIfaceTable,
674                 -- The ModuleIFaces for modules in external packages
675                 -- whose interfaces we have opened
676                 -- The declarations in these interface files are held in
677                 -- eps_decls, eps_insts, eps_rules (below), not in the 
678                 -- mi_decls fields of the iPIT.  
679                 -- What _is_ in the iPIT is:
680                 --      * The Module 
681                 --      * Version info
682                 --      * Its exports
683                 --      * Fixities
684                 --      * Deprecations
685
686         eps_PTE :: !PackageTypeEnv,             -- Domain = external-package modules
687
688         eps_inst_env :: !PackageInstEnv,        -- The total InstEnv accumulated from
689                                                 --   all the external-package modules
690         eps_rule_base :: !PackageRuleBase,      -- Ditto RuleEnv
691
692
693         -- Holding pens for stuff that has been read in from file,
694         -- but not yet slurped into the renamer
695         eps_decls      :: !DeclsMap,
696                 -- A single, global map of Names to unslurped decls
697         eps_insts      :: !IfaceInsts,
698                 -- The as-yet un-slurped instance decls; this bag is depleted when we
699                 -- slurp an instance decl so that we don't slurp the same one twice.
700                 -- Each is 'gated' by the names that must be available before
701                 -- this instance decl is needed.
702         eps_rules      :: !IfaceRules,
703                 -- Similar to instance decls, only for rules
704
705         eps_inst_gates :: !NameSet      -- Gates for instance decls
706                 -- The instance gates must accumulate across
707                 -- all invocations of the renamer; 
708                 -- see "the gating story" in RnIfaces.lhs
709                 -- These names should all be from other packages;
710                 -- for the home package we have all the instance
711                 -- declarations anyhow
712   }
713 \end{code}
714
715 The NameCache makes sure that there is just one Unique assigned for
716 each original name; i.e. (module-name, occ-name) pair.  The Name is
717 always stored as a Global, and has the SrcLoc of its binding location.
718 Actually that's not quite right.  When we first encounter the original
719 name, we might not be at its binding site (e.g. we are reading an
720 interface file); so we give it 'noSrcLoc' then.  Later, when we find
721 its binding site, we fix it up.
722
723 Exactly the same is true of the Module stored in the Name.  When we first
724 encounter the occurrence, we may not know the details of the module, so
725 we just store junk.  Then when we find the binding site, we fix it up.
726
727 \begin{code}
728 data NameCache
729  = NameCache {  nsUniqs :: UniqSupply,
730                 -- Supply of uniques
731                 nsNames :: OrigNameCache,
732                 -- Ensures that one original name gets one unique
733                 nsIPs   :: OrigIParamCache
734                 -- Ensures that one implicit parameter name gets one unique
735    }
736
737 type OrigNameCache = ModuleEnv (Module, OccNameCache)
738         -- Maps a module *name* to a Module, 
739         -- plus the OccNameEnv fot that module
740 type OccNameCache = FiniteMap OccName Name
741         -- Maps the OccName to a Name
742         -- A FiniteMap because OccNames have a Namespace/Faststring pair
743
744 type OrigIParamCache = FiniteMap (IPName RdrName) (IPName Name)
745 \end{code}
746
747 A DeclsMap contains a binding for each Name in the declaration
748 including the constructors of a type decl etc.  The Bool is True just
749 for the 'main' Name.
750
751 \begin{code}
752 type DeclsMap = (NameEnv (AvailInfo, Bool, (Module, TyClDecl RdrName)), Int)
753                                                 -- The Int says how many have been sucked in
754
755 type IfaceInsts = GatedDecls (InstDecl RdrName)
756 type IfaceRules = GatedDecls (RuleDecl RdrName)
757
758 type GatedDecls d = (Bag (GatedDecl d), Int)    -- The Int says how many have been sucked in
759 type GatedDecl  d = (GateFn, (Module, d))
760 type GateFn       = (Name -> Bool) -> Bool      -- Returns True <=> gate is open
761                                                 -- The (Name -> Bool) fn returns True for visible Names
762         -- For example, suppose this is in an interface file
763         --      instance C T where ...
764         -- We want to slurp this decl if both C and T are "visible" in 
765         -- the importing module.  See "The gating story" in RnIfaces for details.
766 \end{code}
767
768
769 %************************************************************************
770 %*                                                                      *
771 \subsection{Linkable stuff}
772 %*                                                                      *
773 %************************************************************************
774
775 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
776 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
777
778 \begin{code}
779 data Linkable = LM {
780   linkableTime     :: ClockTime,        -- Time at which this linkable was built
781                                         -- (i.e. when the bytecodes were produced,
782                                         --       or the mod date on the files)
783   linkableModName  :: ModuleName,       -- Should be Module, but see below
784   linkableUnlinked :: [Unlinked]
785  }
786
787 isObjectLinkable :: Linkable -> Bool
788 isObjectLinkable l = all isObject (linkableUnlinked l)
789
790 instance Outputable Linkable where
791    ppr (LM when_made mod unlinkeds)
792       = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
793         $$ nest 3 (ppr unlinkeds)
794
795 -------------------------------------------
796 data Unlinked
797    = DotO FilePath
798    | DotA FilePath
799    | DotDLL FilePath
800    | BCOs CompiledByteCode
801
802 #ifndef GHCI
803 data CompiledByteCode = NoByteCode
804 #endif
805
806 instance Outputable Unlinked where
807    ppr (DotO path)   = text "DotO" <+> text path
808    ppr (DotA path)   = text "DotA" <+> text path
809    ppr (DotDLL path) = text "DotDLL" <+> text path
810 #ifdef GHCI
811    ppr (BCOs bcos)   = text "BCOs" <+> ppr bcos
812 #else
813    ppr (BCOs bcos)   = text "No byte code"
814 #endif
815
816 isObject (DotO _)   = True
817 isObject (DotA _)   = True
818 isObject (DotDLL _) = True
819 isObject _          = False
820
821 isInterpretable = not . isObject
822
823 nameOfObject (DotO fn)   = fn
824 nameOfObject (DotA fn)   = fn
825 nameOfObject (DotDLL fn) = fn
826
827 byteCodeOfObject (BCOs bc) = bc
828 \end{code}
829
830
831 %************************************************************************
832 %*                                                                      *
833 \subsection{Provenance and export info}
834 %*                                                                      *
835 %************************************************************************
836
837 A LocalRdrEnv is used for local bindings (let, where, lambda, case)
838 Also used in 
839
840 \begin{code}
841 type LocalRdrEnv = RdrNameEnv Name
842
843 extendLocalRdrEnv :: LocalRdrEnv -> [Name] -> LocalRdrEnv
844 extendLocalRdrEnv env names
845   = addListToRdrEnv env [(mkRdrUnqual (nameOccName n), n) | n <- names]
846 \end{code}
847
848 The GlobalRdrEnv gives maps RdrNames to Names.  There is a separate
849 one for each module, corresponding to that module's top-level scope.
850
851 \begin{code}
852 type GlobalRdrEnv = RdrNameEnv [GlobalRdrElt]
853         -- The list is because there may be name clashes
854         -- These only get reported on lookup, not on construction
855
856 emptyGlobalRdrEnv = emptyRdrEnv
857
858 data GlobalRdrElt 
859   = GRE { gre_name   :: Name,
860           gre_parent :: Name,   -- Name of the "parent" structure
861                                 --      * the tycon of a data con
862                                 --      * the class of a class op
863                                 -- For others it's just the same as gre_name
864           gre_prov   :: Provenance,             -- Why it's in scope
865           gre_deprec :: Maybe DeprecTxt         -- Whether this name is deprecated
866     }
867
868 instance Outputable GlobalRdrElt where
869   ppr gre = ppr (gre_name gre) <+> 
870             parens (hsep [text "parent:" <+> ppr (gre_parent gre) <> comma,
871                           pprNameProvenance gre])
872 pprGlobalRdrEnv env
873   = vcat (map pp (rdrEnvToList env))
874   where
875     pp (rn, gres) = ppr rn <> colon <+> 
876                     vcat [ ppr (gre_name gre) <+> pprNameProvenance gre
877                          | gre <- gres]
878
879 isLocalGRE :: GlobalRdrElt -> Bool
880 isLocalGRE (GRE {gre_prov = LocalDef}) = True
881 isLocalGRE other                       = False
882 \end{code}
883
884 @unQualInScope@ returns a function that takes a @Name@ and tells whether
885 its unqualified name is in scope.  This is put as a boolean flag in
886 the @Name@'s provenance to guide whether or not to print the name qualified
887 in error messages.
888
889 \begin{code}
890 unQualInScope :: GlobalRdrEnv -> Name -> Bool
891 -- True if 'f' is in scope, and has only one binding,
892 -- and the thing it is bound to is the name we are looking for
893 -- (i.e. false if A.f and B.f are both in scope as unqualified 'f')
894 --
895 -- Also checks for built-in syntax, which is always 'in scope'
896 --
897 -- This fn is only efficient if the shared 
898 -- partial application is used a lot.
899 unQualInScope env
900   = \n -> n `elemNameSet` unqual_names || isBuiltInSyntaxName n
901   where
902     unqual_names :: NameSet
903     unqual_names = foldRdrEnv add emptyNameSet env
904     add rdr_name [gre] unquals | isUnqual rdr_name = addOneToNameSet unquals (gre_name gre)
905     add _        _     unquals                     = unquals
906 \end{code}
907
908 The "provenance" of something says how it came to be in scope.
909
910 \begin{code}
911 data Provenance
912   = LocalDef                    -- Defined locally
913
914   | NonLocalDef                 -- Defined non-locally
915         ImportReason
916
917 -- Just used for grouping error messages (in RnEnv.warnUnusedBinds)
918 instance Eq Provenance where
919   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
920
921 instance Eq ImportReason where
922   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
923
924 instance Ord Provenance where
925    compare LocalDef LocalDef = EQ
926    compare LocalDef (NonLocalDef _) = LT
927    compare (NonLocalDef _) LocalDef = GT
928
929    compare (NonLocalDef reason1) (NonLocalDef reason2) 
930       = compare reason1 reason2
931
932 instance Ord ImportReason where
933    compare ImplicitImport ImplicitImport = EQ
934    compare ImplicitImport (UserImport _ _ _) = LT
935    compare (UserImport _ _ _) ImplicitImport = GT
936    compare (UserImport m1 loc1 _) (UserImport m2 loc2 _) 
937       = (m1 `compare` m2) `thenCmp` (loc1 `compare` loc2)
938
939
940 data ImportReason
941   = UserImport Module SrcLoc Bool       -- Imported from module M on line L
942                                         -- Note the M may well not be the defining module
943                                         -- for this thing!
944         -- The Bool is true iff the thing was named *explicitly* in the import spec,
945         -- rather than being imported as part of a group; e.g.
946         --      import B
947         --      import C( T(..) )
948         -- Here, everything imported by B, and the constructors of T
949         -- are not named explicitly; only T is named explicitly.
950         -- This info is used when warning of unused names.
951
952   | ImplicitImport                      -- Imported implicitly for some other reason
953 \end{code}
954
955 \begin{code}
956 hasBetterProv :: Provenance -> Provenance -> Bool
957 -- Choose 
958 --      a local thing                 over an   imported thing
959 --      a user-imported thing         over a    non-user-imported thing
960 --      an explicitly-imported thing  over an   implicitly imported thing
961 hasBetterProv LocalDef                            _                            = True
962 hasBetterProv (NonLocalDef (UserImport _ _ _   )) (NonLocalDef ImplicitImport) = True
963 hasBetterProv _                                   _                            = False
964
965 pprNameProvenance :: GlobalRdrElt -> SDoc
966 pprNameProvenance (GRE {gre_name = name, gre_prov = prov})
967   = case prov of
968         LocalDef        -> ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
969         NonLocalDef why ->  sep [ppr_reason why, 
970                                  nest 2 (ppr_defn (nameSrcLoc name))]
971
972 ppr_reason ImplicitImport         = ptext SLIT("implicitly imported")
973 ppr_reason (UserImport mod loc _) = ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc
974
975 ppr_defn loc | isGoodSrcLoc loc = parens (ptext SLIT("at") <+> ppr loc)
976              | otherwise        = empty
977 \end{code}