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