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