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