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