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