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