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