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