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