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