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