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