[project @ 2000-10-24 17:09:44 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         Finder, ModuleLocation(..),
9
10         ModDetails(..), ModIface(..), GlobalSymbolTable, 
11         HomeSymbolTable, PackageSymbolTable,
12         HomeIfaceTable, PackageIfaceTable, 
13         lookupTable, lookupTableByModName,
14
15         IfaceDecls(..), 
16
17         VersionInfo(..), initialVersionInfo,
18
19         TyThing(..), groupTyThings,
20
21         TypeEnv, extendTypeEnv, lookupTypeEnv, 
22
23         WhetherHasOrphans, ImportVersion, WhatsImported(..),
24         PersistentRenamerState(..), IsBootInterface, Avails, DeclsMap,
25         IfaceInsts, IfaceRules, GatedDecl,
26         OrigNameEnv(..), OrigNameNameEnv, OrigNameIParamEnv,
27         AvailEnv, AvailInfo, GenAvailInfo(..),
28         PersistentCompilerState(..),
29
30         Deprecations(..), lookupDeprec,
31
32         InstEnv, ClsInstEnv, DFunId,
33         PackageInstEnv, PackageRuleBase,
34
35         GlobalRdrEnv, RdrAvailInfo,
36
37         -- Provenance
38         Provenance(..), ImportReason(..), PrintUnqualified,
39         pprNameProvenance, hasBetterProv
40
41     ) where
42
43 #include "HsVersions.h"
44
45 import RdrName          ( RdrNameEnv, emptyRdrEnv )
46 import Name             ( Name, NameEnv, NamedThing,
47                           emptyNameEnv, unitNameEnv, extendNameEnv, plusNameEnv, 
48                           lookupNameEnv, emptyNameEnv, getName, nameModule,
49                           nameSrcLoc )
50 import NameSet          ( NameSet )
51 import OccName          ( OccName )
52 import Module           ( Module, ModuleName, ModuleEnv,
53                           lookupModuleEnv, lookupModuleEnvByName
54                         )
55 import VarSet           ( TyVarSet )
56 import VarEnv           ( emptyVarEnv )
57 import Id               ( Id )
58 import Class            ( Class )
59 import TyCon            ( TyCon )
60
61 import BasicTypes       ( Version, initialVersion, Fixity )
62
63 import HsSyn            ( DeprecTxt )
64 import RdrHsSyn         ( RdrNameHsDecl, RdrNameTyClDecl )
65 import RnHsSyn          ( RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl )
66
67 import CoreSyn          ( CoreRule )
68 import Type             ( Type )
69
70 import FiniteMap        ( FiniteMap, emptyFM, addToFM, lookupFM, foldFM )
71 import Bag              ( Bag )
72 import Maybes           ( seqMaybe )
73 import UniqFM           ( UniqFM )
74 import Outputable
75 import SrcLoc           ( SrcLoc, isGoodSrcLoc )
76 import Util             ( thenCmp )
77 import UniqSupply       ( UniqSupply )
78 \end{code}
79
80 %************************************************************************
81 %*                                                                      *
82 \subsection{The Finder type}
83 %*                                                                      *
84 %************************************************************************
85
86 \begin{code}
87 type Finder = ModuleName -> IO (Maybe (Module, ModuleLocation))
88
89 data ModuleLocation
90    = ModuleLocation {
91         hs_file  :: FilePath,
92         hi_file  :: FilePath,
93         obj_file :: FilePath
94       }
95 \end{code}
96
97 For a module in another package, the hs_file and obj_file
98 components of ModuleLocation are undefined.  
99
100 The locations specified by a ModuleLocation may or may not
101 correspond to actual files yet: for example, even if the object
102 file doesn't exist, the ModuleLocation still contains the path to
103 where the object file will reside if/when it is created.
104
105
106 %************************************************************************
107 %*                                                                      *
108 \subsection{Symbol tables and Module details}
109 %*                                                                      *
110 %************************************************************************
111
112 A @ModIface@ plus a @ModDetails@ summarises everything we know 
113 about a compiled module.  The @ModIface@ is the stuff *before* linking,
114 and can be written out to an interface file.  The @ModDetails@ is after
115 linking; it is the "linked" form of the mi_decls field.
116
117 \begin{code}
118 data ModIface 
119    = ModIface {
120         mi_module   :: Module,                  -- Complete with package info
121         mi_version  :: VersionInfo,             -- Module version number
122         mi_orphan   :: WhetherHasOrphans,       -- Whether this module has orphans
123
124         mi_usages   :: [ImportVersion Name],    -- Usages; kept sorted so that it's easy
125                                                 -- to decide whether to write a new iface file
126                                                 -- (changing usages doesn't affect the version of
127                                                 --  this module)
128
129         mi_exports  :: Avails,                  -- What it exports
130                                                 -- Kept sorted by (mod,occ),
131                                                 -- to make version comparisons easier
132
133         mi_globals  :: GlobalRdrEnv,            -- Its top level environment
134
135         mi_fixities :: NameEnv Fixity,          -- Fixities
136         mi_deprecs  :: Deprecations,            -- Deprecations
137
138         mi_decls    :: IfaceDecls               -- The RnDecls form of ModDetails
139      }
140
141 data IfaceDecls = IfaceDecls { dcl_tycl  :: [RenamedTyClDecl],  -- Sorted
142                                dcl_rules :: [RenamedRuleDecl],  -- Sorted
143                                dcl_insts :: [RenamedInstDecl] } -- Unsorted
144
145 -- typechecker should only look at this, not ModIface
146 -- Should be able to construct ModDetails from mi_decls in ModIface
147 data ModDetails
148    = ModDetails {
149         -- The next three fields are created by the typechecker
150         md_types    :: TypeEnv,
151         md_insts    :: [DFunId],        -- Dfun-ids for the instances in this module
152         md_rules    :: RuleBase         -- Domain may include Ids from other modules
153      }
154 \end{code}
155
156 \begin{code}
157 emptyModDetails :: ModDetails
158 emptyModDetails
159   = ModDetails { md_types = emptyTypeEnv,
160                  md_insts = [],
161                  md_rules = emptyRuleBase
162     }
163
164 emptyModIface :: Module -> ModIface
165 emptyModIface mod
166   = ModIface { mi_module   = mod,
167                mi_exports  = [],
168                mi_globals  = emptyRdrEnv,
169                mi_deprecs  = NoDeprecs
170     }           
171 \end{code}
172
173 Symbol tables map modules to ModDetails:
174
175 \begin{code}
176 type SymbolTable        = ModuleEnv ModDetails
177 type IfaceTable         = ModuleEnv ModIface
178
179 type HomeIfaceTable     = IfaceTable
180 type PackageIfaceTable  = IfaceTable
181
182 type HomeSymbolTable    = SymbolTable   -- Domain = modules in the home package
183 type PackageSymbolTable = SymbolTable   -- Domain = modules in the some other package
184 type GlobalSymbolTable  = SymbolTable   -- Domain = all modules
185 \end{code}
186
187 Simple lookups in the symbol table.
188
189 \begin{code}
190 lookupTable :: ModuleEnv a -> ModuleEnv a -> Name -> Maybe a
191 -- We often have two Symbol- or IfaceTables, and want to do a lookup
192 lookupTable ht pt name
193   = lookupModuleEnv ht mod `seqMaybe` lookupModuleEnv pt mod
194   where
195     mod = nameModule name
196
197 lookupTableByModName :: ModuleEnv a -> ModuleEnv a -> ModuleName -> Maybe a
198 -- We often have two Symbol- or IfaceTables, and want to do a lookup
199 lookupTableByModName ht pt mod
200   = lookupModuleEnvByName ht mod `seqMaybe` lookupModuleEnvByName pt mod
201 \end{code}
202
203
204 %************************************************************************
205 %*                                                                      *
206 \subsection{Type environment stuff}
207 %*                                                                      *
208 %************************************************************************
209
210 \begin{code}
211 type TypeEnv = NameEnv TyThing
212 emptyTypeEnv = emptyNameEnv
213
214 data TyThing = AnId   Id
215              | ATyCon TyCon
216              | AClass Class
217
218 instance NamedThing TyThing where
219   getName (AnId id)   = getName id
220   getName (ATyCon tc) = getName tc
221   getName (AClass cl) = getName cl
222 \end{code}
223
224
225 \begin{code}
226 lookupTypeEnv :: SymbolTable -> Name -> Maybe TyThing
227 lookupTypeEnv tbl name
228   = case lookupModuleEnv tbl (nameModule name) of
229         Just details -> lookupNameEnv (md_types details) name
230         Nothing      -> Nothing
231
232
233 groupTyThings :: [TyThing] -> FiniteMap Module TypeEnv
234   -- Finite map because we want the range too
235 groupTyThings things
236   = foldl add emptyFM things
237   where
238     add :: FiniteMap Module TypeEnv -> TyThing -> FiniteMap Module TypeEnv
239     add tbl thing = addToFM tbl mod new_env
240                   where
241                     name    = getName thing
242                     mod     = nameModule name
243                     new_env = case lookupFM tbl mod of
244                                 Nothing  -> unitNameEnv name thing
245                                 Just env -> extendNameEnv env name thing
246                 
247 extendTypeEnv :: SymbolTable -> FiniteMap Module TypeEnv -> SymbolTable
248 extendTypeEnv tbl things
249   = foldFM add tbl things
250   where
251     add mod type_env tbl
252         = panic "extendTypeEnv" --extendModuleEnv mod new_details
253         where
254           new_details 
255              = case lookupModuleEnv tbl mod of
256                   Nothing      -> emptyModDetails {md_types = type_env}
257                   Just details -> details {md_types = md_types details 
258                                                      `plusNameEnv` type_env}
259 \end{code}
260
261
262 %************************************************************************
263 %*                                                                      *
264 \subsection{Auxiliary types}
265 %*                                                                      *
266 %************************************************************************
267
268 These types are defined here because they are mentioned in ModDetails,
269 but they are mostly elaborated elsewhere
270
271 \begin{code}
272 data VersionInfo 
273   = VersionInfo {
274         vers_module  :: Version,        -- Changes when anything changes
275         vers_exports :: Version,        -- Changes when export list changes
276         vers_rules   :: Version,        -- Changes when any rule changes
277         vers_decls   :: NameEnv Version
278                 -- Versions for "big" names only (not data constructors, class ops)
279                 -- The version of an Id changes if its fixity changes
280                 -- Ditto data constructors, class operations, except that the version of
281                 -- the parent class/tycon changes
282     }
283
284 initialVersionInfo :: VersionInfo
285 initialVersionInfo = VersionInfo { vers_module  = initialVersion,
286                                    vers_exports = initialVersion,
287                                    vers_rules   = initialVersion,
288                                    vers_decls   = emptyNameEnv }
289
290 data Deprecations = NoDeprecs
291                   | DeprecAll DeprecTxt                 -- Whole module deprecated
292                   | DeprecSome (NameEnv DeprecTxt)      -- Some things deprecated
293                                                         -- Just "big" names
294
295 lookupDeprec :: ModIface -> Name -> Maybe DeprecTxt
296 lookupDeprec iface name
297   = case mi_deprecs iface of
298         NoDeprecs      -> Nothing
299         DeprecAll txt  -> Just txt
300         DeprecSome env -> lookupNameEnv env name
301
302 type InstEnv    = UniqFM ClsInstEnv             -- Maps Class to instances for that class
303
304 type ClsInstEnv = [(TyVarSet, [Type], DFunId)]  -- The instances for a particular class
305 type DFunId     = Id
306 \end{code}
307
308
309 \begin{code}
310 type Avails       = [AvailInfo]
311 type AvailInfo    = GenAvailInfo Name
312 type RdrAvailInfo = GenAvailInfo OccName
313
314 data GenAvailInfo name  = Avail name     -- An ordinary identifier
315                         | AvailTC name   -- The name of the type or class
316                                   [name] -- The available pieces of type/class.
317                                          -- NB: If the type or class is itself
318                                          -- to be in scope, it must be in this list.
319                                          -- Thus, typically: AvailTC Eq [Eq, ==, /=]
320                         deriving( Eq )
321                         -- Equality used when deciding if the interface has changed
322
323 type AvailEnv     = NameEnv AvailInfo   -- Maps a Name to the AvailInfo that contains it
324 \end{code}
325
326
327 %************************************************************************
328 %*                                                                      *
329 \subsection{ModIface}
330 %*                                                                      *
331 %************************************************************************
332
333 \begin{code}
334 type WhetherHasOrphans   = Bool
335         -- An "orphan" is 
336         --      * an instance decl in a module other than the defn module for 
337         --              one of the tycons or classes in the instance head
338         --      * a transformation rule in a module other than the one defining
339         --              the function in the head of the rule.
340
341 type IsBootInterface     = Bool
342
343 type ImportVersion name  = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)
344
345 data WhatsImported name  = NothingAtAll                         -- The module is below us in the
346                                                                 -- hierarchy, but we import nothing
347
348                          | Everything Version           -- Used for modules from other packages;
349                                                         -- we record only the module's version number
350
351                          | Specifically 
352                                 Version                 -- Module version
353                                 (Maybe Version)         -- Export-list version, if we depend on it
354                                 [(name,Version)]        -- List guaranteed non-empty
355                                 Version                 -- Rules version
356
357                          deriving( Eq )
358         -- 'Specifically' doesn't let you say "I imported f but none of the rules in
359         -- the module". If you use anything in the module you get its rule version
360         -- So if the rules change, you'll recompile, even if you don't use them.
361         -- This is easy to implement, and it's safer: you might not have used the rules last
362         -- time round, but if someone has added a new rule you might need it this time
363
364         -- The export list field is (Just v) if we depend on the export list:
365         --      we imported the module without saying exactly what we imported
366         -- We need to recompile if the module exports changes, because we might
367         -- now have a name clash in the importing module.
368 \end{code}
369
370
371 %************************************************************************
372 %*                                                                      *
373 \subsection{The persistent compiler state}
374 %*                                                                      *
375 %************************************************************************
376
377 \begin{code}
378 data PersistentCompilerState 
379    = PCS {
380         pcs_PIT :: PackageIfaceTable,   -- Domain = non-home-package modules
381                                         --   the mi_decls component is empty
382
383         pcs_PST :: PackageSymbolTable,  -- Domain = non-home-package modules
384                                         --   except that the InstEnv components is empty
385
386         pcs_insts :: PackageInstEnv,    -- The total InstEnv accumulated from all
387                                         --   the non-home-package modules
388
389         pcs_rules :: PackageRuleEnv,    -- Ditto RuleEnv
390
391         pcs_PRS :: PersistentRenamerState
392      }
393
394 \end{code}
395
396 The @PersistentRenamerState@ persists across successive calls to the
397 compiler.
398
399 It contains:
400   * A name supply, which deals with allocating unique names to
401     (Module,OccName) original names, 
402  
403   * An accumulated InstEnv from all the modules in pcs_PST
404     The point is that we don't want to keep recreating it whenever
405     we compile a new module.  The InstEnv component of pcPST is empty.
406     (This means we might "see" instances that we shouldn't "really" see;
407     but the Haskell Report is vague on what is meant to be visible, 
408     so we just take the easy road here.)
409
410   * Ditto for rules
411
412   * A "holding pen" for declarations that have been read out of
413     interface files but not yet sucked in, renamed, and typechecked
414
415 \begin{code}
416 type PackageRuleBase = RuleBase
417 type PackageInstEnv  = InstEnv
418
419 data PersistentRenamerState
420   = PRS { prsOrig  :: OrigNameEnv,
421           prsDecls :: DeclsMap,
422           prsInsts :: IfaceInsts,
423           prsRules :: IfaceRules,
424           prsNS    :: UniqSupply
425     }
426 \end{code}
427
428 The OrigNameEnv makes sure that there is just one Unique assigned for
429 each original name; i.e. (module-name, occ-name) pair.  The Name is
430 always stored as a Global, and has the SrcLoc of its binding location.
431 Actually that's not quite right.  When we first encounter the original
432 name, we might not be at its binding site (e.g. we are reading an
433 interface file); so we give it 'noSrcLoc' then.  Later, when we find
434 its binding site, we fix it up.
435
436 Exactly the same is true of the Module stored in the Name.  When we first
437 encounter the occurrence, we may not know the details of the module, so
438 we just store junk.  Then when we find the binding site, we fix it up.
439
440 \begin{code}
441 data OrigNameEnv
442  = Orig { origNames  :: OrigNameNameEnv,
443                 -- Ensures that one original name gets one unique
444           origIParam :: OrigNameIParamEnv
445                 -- Ensures that one implicit parameter name gets one unique
446    }
447
448 type OrigNameNameEnv   = FiniteMap (ModuleName,OccName) Name
449 type OrigNameIParamEnv = FiniteMap OccName Name
450 \end{code}
451
452
453 A DeclsMap contains a binding for each Name in the declaration
454 including the constructors of a type decl etc.  The Bool is True just
455 for the 'main' Name.
456
457 \begin{code}
458 type DeclsMap = NameEnv (AvailInfo, Bool, (Module, RdrNameTyClDecl))
459
460 type IfaceInsts = Bag GatedDecl
461 type IfaceRules = Bag GatedDecl
462
463 type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
464 \end{code}
465
466
467 %************************************************************************
468 %*                                                                      *
469 \subsection{Provenance and export info}
470 %*                                                                      *
471 %************************************************************************
472
473 The GlobalRdrEnv gives maps RdrNames to Names.  There is a separate
474 one for each module, corresponding to that module's top-level scope.
475
476 \begin{code}
477 type GlobalRdrEnv = RdrNameEnv [(Name,Provenance)]      -- The list is because there may be name clashes
478                                                         -- These only get reported on lookup,
479                                                         -- not on construction
480 \end{code}
481
482 The "provenance" of something says how it came to be in scope.
483
484 \begin{code}
485 data Provenance
486   = LocalDef                    -- Defined locally
487
488   | NonLocalDef                 -- Defined non-locally
489         ImportReason
490         PrintUnqualified
491
492 -- Just used for grouping error messages (in RnEnv.warnUnusedBinds)
493 instance Eq Provenance where
494   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
495
496 instance Eq ImportReason where
497   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
498
499 instance Ord Provenance where
500    compare LocalDef LocalDef = EQ
501    compare LocalDef (NonLocalDef _ _) = LT
502    compare (NonLocalDef _ _) LocalDef = GT
503
504    compare (NonLocalDef reason1 _) (NonLocalDef reason2 _) 
505       = compare reason1 reason2
506
507 instance Ord ImportReason where
508    compare ImplicitImport ImplicitImport = EQ
509    compare ImplicitImport (UserImport _ _ _) = LT
510    compare (UserImport _ _ _) ImplicitImport = GT
511    compare (UserImport m1 loc1 _) (UserImport m2 loc2 _) 
512       = (m1 `compare` m2) `thenCmp` (loc1 `compare` loc2)
513
514
515 data ImportReason
516   = UserImport Module SrcLoc Bool       -- Imported from module M on line L
517                                         -- Note the M may well not be the defining module
518                                         -- for this thing!
519         -- The Bool is true iff the thing was named *explicitly* in the import spec,
520         -- rather than being imported as part of a group; e.g.
521         --      import B
522         --      import C( T(..) )
523         -- Here, everything imported by B, and the constructors of T
524         -- are not named explicitly; only T is named explicitly.
525         -- This info is used when warning of unused names.
526
527   | ImplicitImport                      -- Imported implicitly for some other reason
528                         
529
530 type PrintUnqualified = Bool    -- True <=> the unqualified name of this thing is
531                                 -- in scope in this module, so print it 
532                                 -- unqualified in error messages
533 \end{code}
534
535 \begin{code}
536 hasBetterProv :: Provenance -> Provenance -> Bool
537 -- Choose 
538 --      a local thing                 over an   imported thing
539 --      a user-imported thing         over a    non-user-imported thing
540 --      an explicitly-imported thing  over an   implicitly imported thing
541 hasBetterProv LocalDef                              _                              = True
542 hasBetterProv (NonLocalDef (UserImport _ _ True) _) _                              = True
543 hasBetterProv (NonLocalDef (UserImport _ _ _   ) _) (NonLocalDef ImplicitImport _) = True
544 hasBetterProv _                                     _                              = False
545
546 pprNameProvenance :: Name -> Provenance -> SDoc
547 pprNameProvenance name LocalDef            = ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
548 pprNameProvenance name (NonLocalDef why _) = sep [ppr_reason why, 
549                                               nest 2 (parens (ppr_defn (nameSrcLoc name)))]
550
551 ppr_reason ImplicitImport         = ptext SLIT("implicitly imported")
552 ppr_reason (UserImport mod loc _) = ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc
553
554 ppr_defn loc | isGoodSrcLoc loc = ptext SLIT("at") <+> ppr loc
555              | otherwise        = empty
556 \end{code}