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