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