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