[project @ 2000-10-16 13:51:28 by sewardj]
[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         ModDetails(..), GlobalSymbolTable, 
9         HomeSymbolTable, PackageSymbolTable,
10
11         TyThing(..), lookupTypeEnv,
12
13         WhetherHasOrphans, ImportVersion, ExportItem,
14         PersistentRenamerState(..), IsBootInterface, Avails, DeclsMap,
15         IfaceInsts, IfaceRules, DeprecationEnv, OrigNameEnv, 
16         AvailEnv, AvailInfo, GenAvailInfo(..),
17         PersistentCompilerState(..),
18
19         InstEnv, 
20
21         GlobalRdrEnv, RdrAvailInfo,
22
23         -- Provenance
24         Provenance(..), ImportReason(..), PrintUnqualified,
25         pprNameProvenance, hasBetterProv
26
27     ) where
28
29 #include "HsVersions.h"
30
31 import Name             ( Name, NameEnv, NamedThing,
32                           unitNameEnv, extendNameEnv, plusNameEnv, 
33                           lookupNameEnv, emptyNameEnv, getName, nameModule,
34                           nameSrcLoc )
35 import Module           ( Module, ModuleName,
36                           extendModuleEnv, lookupModuleEnv )
37 import Class            ( Class )
38 import OccName          ( OccName )
39 import RdrName          ( RdrNameEnv, emptyRdrEnv )
40 import Outputable       ( SDoc )
41 import UniqFM           ( UniqFM )
42 import FiniteMap        ( FiniteMap, emptyFM, addToFM, lookupFM, foldFM )
43 import Bag              ( Bag )
44 import Id               ( Id )
45 import VarEnv           ( IdEnv, emptyVarEnv )
46 import BasicTypes       ( Version, Fixity, defaultFixity )
47 import TyCon            ( TyCon )
48 import ErrUtils         ( ErrMsg, WarnMsg )
49 import CmLink           ( Linkable )
50 import RdrHsSyn         ( RdrNameInstDecl, RdrNameRuleDecl, RdrNameHsDecl,
51                           RdrNameDeprecation, RdrNameFixitySig )
52 import UniqSupply       ( UniqSupply )
53 import HsDecls          ( DeprecTxt )
54 import CoreSyn          ( CoreRule )
55 import NameSet          ( NameSet )
56 import Type             ( Type )
57 import VarSet           ( TyVarSet )
58 import Panic            ( panic )
59 import Outputable
60 import SrcLoc           ( SrcLoc, isGoodSrcLoc )
61 \end{code}
62
63 %************************************************************************
64 %*                                                                      *
65 \subsection{Symbol tables and Module details}
66 %*                                                                      *
67 %************************************************************************
68
69 A @ModDetails@ summarises everything we know about a compiled module.
70
71 \begin{code}
72 data ModDetails
73    = ModDetails {
74         md_id       :: Module,
75         md_exports  :: Avails,          -- What it exports
76         md_version  :: VersionInfo,
77         md_globals  :: GlobalRdrEnv,    -- Its top level environment
78
79         md_fixities :: NameEnv Fixity,
80         md_deprecs  :: NameEnv DeprecTxt,
81         md_types    :: TypeEnv,
82
83         md_insts    :: [DFunId],        -- Dfun-ids for the instances in this module
84         md_rules    :: RuleEnv          -- Domain may include Id from other modules
85      }
86
87 emptyModDetails :: Module -> ModDetails
88 emptyModDetails mod
89   = ModDetails { md_id       = mod,
90                  md_exports  = [],
91                  md_globals  = emptyRdrEnv,
92                  md_fixities = emptyNameEnv,
93                  md_deprecs  = emptyNameEnv,
94                  md_types    = emptyNameEnv,
95                  md_insts    = [],
96                  md_rules    = emptyRuleEnv
97     }           
98 \end{code}
99
100 Symbol tables map modules to ModDetails:
101
102 \begin{code}
103 type SymbolTable        = ModuleEnv ModDetails
104 type HomeSymbolTable    = SymbolTable   -- Domain = modules in the home package
105 type PackageSymbolTable = SymbolTable   -- Domain = modules in the some other package
106 type GlobalSymbolTable  = SymbolTable   -- Domain = all modules
107 \end{code}
108
109 Simple lookups in the symbol table.
110
111 \begin{code}
112 lookupFixityEnv :: SymbolTable -> Name -> Maybe Fixity
113         -- Returns defaultFixity if there isn't an explicit fixity
114 lookupFixityEnv tbl name
115   = case lookupModuleEnv tbl (nameModule name) of
116         Nothing      -> Nothing
117         Just details -> lookupNameEnv (md_fixities details) name
118 \end{code}
119
120
121 %************************************************************************
122 %*                                                                      *
123 \subsection{Type environment stuff}
124 %*                                                                      *
125 %************************************************************************
126
127 \begin{code}
128 type TypeEnv = NameEnv TyThing
129
130 data TyThing = AnId   Id
131              | ATyCon TyCon
132              | AClass Class
133
134 instance NamedThing TyThing where
135   getName (AnId id)   = getName id
136   getName (ATyCon tc) = getName tc
137   getName (AClass cl) = getName cl
138 \end{code}
139
140
141 \begin{code}
142 lookupTypeEnv :: SymbolTable -> Name -> Maybe TyThing
143 lookupTypeEnv tbl name
144   = case lookupModuleEnv tbl (nameModule name) of
145         Just details -> lookupNameEnv (md_types details) name
146         Nothing      -> Nothing
147
148
149 groupTyThings :: [TyThing] -> FiniteMap Module TypeEnv
150   -- Finite map because we want the range too
151 groupTyThings things
152   = foldl add emptyFM things
153   where
154     add :: FiniteMap Module TypeEnv -> TyThing -> FiniteMap Module TypeEnv
155     add tbl thing = addToFM tbl mod new_env
156                   where
157                     name    = getName thing
158                     mod     = nameModule name
159                     new_env = case lookupFM tbl mod of
160                                 Nothing  -> unitNameEnv name thing
161                                 Just env -> extendNameEnv env name thing
162                 
163 extendTypeEnv :: SymbolTable -> FiniteMap Module TypeEnv -> SymbolTable
164 extendTypeEnv tbl things
165   = foldFM add tbl things
166   where
167     add mod type_env tbl
168         = panic "extendTypeEnv" --extendModuleEnv mod new_details
169         where
170           new_details 
171              = case lookupModuleEnv tbl mod of
172                   Nothing      -> (emptyModDetails mod) {md_types = type_env}
173                   Just details -> details {md_types = md_types details 
174                                                      `plusNameEnv` type_env}
175 \end{code}
176
177
178 %************************************************************************
179 %*                                                                      *
180 \subsection{Auxiliary types}
181 %*                                                                      *
182 %************************************************************************
183
184 These types are defined here because they are mentioned in ModDetails,
185 but they are mostly elaborated elsewhere
186
187 \begin{code}
188 data VersionInfo 
189   = VersionInfo {
190         modVers :: Version,
191         fixVers :: Version,
192         ruleVers :: Version,
193         declVers :: NameEnv Version
194     }
195
196 type DeprecationEnv = NameEnv DeprecTxt         -- Give reason for deprecation
197
198 type InstEnv    = UniqFM ClsInstEnv             -- Maps Class to instances for that class
199 type ClsInstEnv = [(TyVarSet, [Type], DFunId)]  -- The instances for a particular class
200 type DFunId     = Id
201
202 type RuleEnv    = IdEnv [CoreRule]
203
204 emptyRuleEnv    = emptyVarEnv
205 \end{code}
206
207
208 \begin{code}
209 type Avails       = [AvailInfo]
210 type AvailInfo    = GenAvailInfo Name
211 type RdrAvailInfo = GenAvailInfo OccName
212
213 data GenAvailInfo name  = Avail name     -- An ordinary identifier
214                         | AvailTC name   -- The name of the type or class
215                                   [name] -- The available pieces of type/class.
216                                          -- NB: If the type or class is itself
217                                          -- to be in scope, it must be in this list.
218                                          -- Thus, typically: AvailTC Eq [Eq, ==, /=]
219                         deriving( Eq )
220                         -- Equality used when deciding if the interface has changed
221
222 type AvailEnv     = NameEnv AvailInfo   -- Maps a Name to the AvailInfo that contains it
223 \end{code}
224
225
226 %************************************************************************
227 %*                                                                      *
228 \subsection{ModIface}
229 %*                                                                      *
230 %************************************************************************
231
232 \begin{code}
233 -- ModIFace is nearly the same as RnMonad.ParsedIface.
234 -- Right now it's identical :)
235 data ModIFace 
236    = ModIFace {
237         mi_mod       :: Module,                   -- Complete with package info
238         mi_vers      :: Version,                  -- Module version number
239         mi_orphan    :: WhetherHasOrphans,        -- Whether this module has orphans
240         mi_usages    :: [ImportVersion OccName],  -- Usages
241         mi_exports   :: [ExportItem],             -- Exports
242         mi_insts     :: [RdrNameInstDecl],        -- Local instance declarations
243         mi_decls     :: [(Version, RdrNameHsDecl)],    -- Local definitions
244         mi_fixity    :: (Version, [RdrNameFixitySig]), -- Local fixity declarations, 
245                                                        -- with their version
246         mi_rules     :: (Version, [RdrNameRuleDecl]),  -- Rules, with their version
247         mi_deprecs   :: [RdrNameDeprecation]           -- Deprecations
248      }
249
250 type ExportItem          = (ModuleName, [RdrAvailInfo])
251
252 type ImportVersion name  = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)
253
254 type ModVersionInfo     = (Version,             -- Version of the whole module
255                            Version,             -- Version number for all fixity decls together
256                            Version)             -- ...ditto all rules together
257
258 type WhetherHasOrphans   = Bool
259         -- An "orphan" is 
260         --      * an instance decl in a module other than the defn module for 
261         --              one of the tycons or classes in the instance head
262         --      * a transformation rule in a module other than the one defining
263         --              the function in the head of the rule.
264
265 type IsBootInterface     = Bool
266
267 data WhatsImported name  = NothingAtAll                         -- The module is below us in the
268                                                                 -- hierarchy, but we import nothing
269
270                          | Everything Version                   -- The module version
271
272                          | Specifically Version                 -- Module version
273                                         Version                 -- Fixity version
274                                         Version                 -- Rules version
275                                         [(name,Version)]        -- List guaranteed non-empty
276                          deriving( Eq )
277         -- 'Specifically' doesn't let you say "I imported f but none of the fixities in
278         -- the module". If you use anything in the module you get its fixity and rule version
279         -- So if the fixities or rules change, you'll recompile, even if you don't use either.
280         -- This is easy to implement, and it's safer: you might not have used the rules last
281         -- time round, but if someone has added a new rule you might need it this time
282
283         -- 'Everything' means there was a "module M" in 
284         -- this module's export list, so we just have to go by M's version,
285         -- not the list of (name,version) pairs
286 \end{code}
287
288
289 %************************************************************************
290 %*                                                                      *
291 \subsection{The persistent compiler state}
292 %*                                                                      *
293 %************************************************************************
294
295 \begin{code}
296 data PersistentCompilerState 
297    = PCS {
298         pcs_PST :: PackageSymbolTable,  -- Domain = non-home-package modules
299                                         --   except that the InstEnv components is empty
300         pcs_insts :: InstEnv,           -- The total InstEnv accumulated from all
301                                         --   the non-home-package modules
302         pcs_rules :: RuleEnv,           -- Ditto RuleEnv
303
304         pcs_PRS :: PersistentRenamerState
305      }
306 \end{code}
307
308 The @PersistentRenamerState@ persists across successive calls to the
309 compiler.
310
311 It contains:
312   * A name supply, which deals with allocating unique names to
313     (Module,OccName) original names, 
314  
315   * An accumulated InstEnv from all the modules in pcs_PST
316     The point is that we don't want to keep recreating it whenever
317     we compile a new module.  The InstEnv component of pcPST is empty.
318     (This means we might "see" instances that we shouldn't "really" see;
319     but the Haskell Report is vague on what is meant to be visible, 
320     so we just take the easy road here.)
321
322   * Ditto for rules
323
324   * A "holding pen" for declarations that have been read out of
325     interface files but not yet sucked in, renamed, and typechecked
326
327 \begin{code}
328 data PersistentRenamerState
329   = PRS { prsOrig  :: OrigNameEnv,
330           prsDecls :: DeclsMap,
331           prsInsts :: IfaceInsts,
332           prsRules :: IfaceRules
333     }
334 \end{code}
335
336 The OrigNameEnv makes sure that there is just one Unique assigned for
337 each original name; i.e. (module-name, occ-name) pair.  The Name is
338 always stored as a Global, and has the SrcLoc of its binding location.
339 Actually that's not quite right.  When we first encounter the original
340 name, we might not be at its binding site (e.g. we are reading an
341 interface file); so we give it 'noSrcLoc' then.  Later, when we find
342 its binding site, we fix it up.
343
344 Exactly the same is true of the Module stored in the Name.  When we first
345 encounter the occurrence, we may not know the details of the module, so
346 we just store junk.  Then when we find the binding site, we fix it up.
347
348 \begin{code}
349 data OrigNameEnv
350  = Orig { origNames  :: FiniteMap (ModuleName,OccName) Name,    -- Ensures that one original name gets one unique
351           origIParam :: FiniteMap OccName Name                  -- Ensures that one implicit parameter name gets one unique
352    }
353 \end{code}
354
355
356 A DeclsMap contains a binding for each Name in the declaration
357 including the constructors of a type decl etc.  The Bool is True just
358 for the 'main' Name.
359
360 \begin{code}
361 type DeclsMap = NameEnv (AvailInfo, Bool, (Module, RdrNameHsDecl))
362
363 type IfaceInsts = Bag GatedDecl
364 type IfaceRules = Bag GatedDecl
365
366 type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
367 \end{code}
368
369
370 %************************************************************************
371 %*                                                                      *
372 \subsection{The result of compiling one module}
373 %*                                                                      *
374 %************************************************************************
375
376 \begin{code}
377 data CompResult
378    = CompOK   ModDetails  -- new details (HST additions)
379               (Maybe (ModIFace, Linkable))
380                        -- summary and code; Nothing => compilation not reqd
381                        -- (old summary and code are still valid)
382               PersistentCompilerState   -- updated PCS
383               (Bag WarnMsg)             -- warnings
384
385    | CompErrs PersistentCompilerState   -- updated PCS
386               (Bag ErrMsg)              -- errors
387               (Bag WarnMsg)             -- warnings
388
389
390 -- The driver sits between 'compile' and 'hscMain', translating calls
391 -- to the former into calls to the latter, and results from the latter
392 -- into results from the former.  It does things like preprocessing
393 -- the .hs file if necessary, and compiling up the .stub_c files to
394 -- generate Linkables.
395
396 data HscResult
397    = HscOK   ModDetails                 -- new details (HomeSymbolTable additions)
398              (Maybe ModIFace)           -- new iface (if any compilation was done)
399              (Maybe String)             -- generated stub_h
400              (Maybe String)             -- generated stub_c
401              PersistentCompilerState    -- updated PCS
402              [SDoc]                     -- warnings
403
404    | HscErrs PersistentCompilerState    -- updated PCS
405              [SDoc]                     -- errors
406              [SDoc]                     -- warnings
407
408         
409 -- These two are only here to avoid recursion between CmCompile and
410 -- CompManager.  They really ought to be in the latter.
411 type ModuleEnv a = UniqFM a   -- Domain is Module
412
413 type HomeModMap         = FiniteMap ModuleName Module -- domain: home mods only
414 type HomeInterfaceTable = ModuleEnv ModIFace
415 \end{code}
416
417
418 %************************************************************************
419 %*                                                                      *
420 \subsection{Provenance and export info}
421 %*                                                                      *
422 %************************************************************************
423
424 The GlobalRdrEnv gives maps RdrNames to Names.  There is a separate
425 one for each module, corresponding to that module's top-level scope.
426
427 \begin{code}
428 type GlobalRdrEnv = RdrNameEnv [(Name,Provenance)]      -- The list is because there may be name clashes
429                                                         -- These only get reported on lookup,
430                                                         -- not on construction
431 \end{code}
432
433 The "provenance" of something says how it came to be in scope.
434
435 \begin{code}
436 data Provenance
437   = LocalDef                    -- Defined locally
438
439   | NonLocalDef                 -- Defined non-locally
440         ImportReason
441         PrintUnqualified
442
443 {-
444 Moved here from Name.
445 pp_prov (LocalDef _ Exported)          = char 'x'
446 pp_prov (LocalDef _ NotExported)       = char 'l'
447 pp_prov (NonLocalDef ImplicitImport _) = char 'j'
448 pp_prov (NonLocalDef (UserImport _ _ True ) _) = char 'I'       -- Imported by name
449 pp_prov (NonLocalDef (UserImport _ _ False) _) = char 'i'       -- Imported by ..
450 pp_prov SystemProv                     = char 's'
451 -}
452
453 data ImportReason
454   = UserImport Module SrcLoc Bool       -- Imported from module M on line L
455                                         -- Note the M may well not be the defining module
456                                         -- for this thing!
457         -- The Bool is true iff the thing was named *explicitly* in the import spec,
458         -- rather than being imported as part of a group; e.g.
459         --      import B
460         --      import C( T(..) )
461         -- Here, everything imported by B, and the constructors of T
462         -- are not named explicitly; only T is named explicitly.
463         -- This info is used when warning of unused names.
464
465   | ImplicitImport                      -- Imported implicitly for some other reason
466                         
467
468 type PrintUnqualified = Bool    -- True <=> the unqualified name of this thing is
469                                 -- in scope in this module, so print it 
470                                 -- unqualified in error messages
471 \end{code}
472
473 \begin{code}
474 hasBetterProv :: Provenance -> Provenance -> Bool
475 -- Choose 
476 --      a local thing                 over an   imported thing
477 --      a user-imported thing         over a    non-user-imported thing
478 --      an explicitly-imported thing  over an   implicitly imported thing
479 hasBetterProv LocalDef                              _                              = True
480 hasBetterProv (NonLocalDef (UserImport _ _ True) _) _                              = True
481 hasBetterProv (NonLocalDef (UserImport _ _ _   ) _) (NonLocalDef ImplicitImport _) = True
482 hasBetterProv _                                     _                              = False
483
484 pprNameProvenance :: Name -> Provenance -> SDoc
485 pprNameProvenance name LocalDef                = ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
486 pprNameProvenance name (NonLocalDef why _) = sep [ppr_reason why, 
487                                               nest 2 (parens (ppr_defn (nameSrcLoc name)))]
488
489 ppr_reason ImplicitImport         = ptext SLIT("implicitly imported")
490 ppr_reason (UserImport mod loc _) = ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc
491
492 ppr_defn loc | isGoodSrcLoc loc = ptext SLIT("at") <+> ppr loc
493              | otherwise        = empty
494 \end{code}