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