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