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