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