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