[project @ 2000-02-22 15:47:56 by panne]
[ghc-hetmet.git] / ghc / compiler / rename / RnIfaces.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
5
6 \begin{code}
7 module RnIfaces (
8         getInterfaceExports, 
9         getImportedInstDecls, getImportedRules,
10         lookupFixity, loadHomeInterface,
11         importDecl, recordSlurp,
12         getImportVersions, getSlurped,
13
14         checkUpToDate,
15
16         getDeclBinders, getDeclSysBinders,
17         removeContext           -- removeContext probably belongs somewhere else
18     ) where
19
20 #include "HsVersions.h"
21
22 import CmdLineOpts      ( opt_NoPruneDecls, opt_IgnoreIfacePragmas )
23 import HsSyn            ( HsDecl(..), TyClDecl(..), InstDecl(..), IfaceSig(..), 
24                           HsType(..), ConDecl(..), IE(..), ConDetails(..), Sig(..),
25                           ForeignDecl(..), ForKind(..), isDynamic,
26                           FixitySig(..), RuleDecl(..),
27                           isClassOpSig, Deprecation(..)
28                         )
29 import BasicTypes       ( Version, NewOrData(..), defaultFixity )
30 import RdrHsSyn         ( RdrNameHsDecl, RdrNameInstDecl, RdrNameTyClDecl, RdrNameRuleDecl,
31                           extractHsTyRdrNames, RdrNameDeprecation
32                         )
33 import RnEnv            ( mkImportedGlobalName, newImportedBinder, mkImportedGlobalFromRdrName,
34                           lookupOccRn, lookupImplicitOccRn,
35                           pprAvail,
36                           availName, availNames, addAvailToNameSet,
37                           FreeVars, emptyFVs
38                         )
39 import RnMonad
40 import RnHsSyn          ( RenamedHsDecl, RenamedDeprecation )
41 import ParseIface       ( parseIface, IfaceStuff(..) )
42
43 import FiniteMap        ( FiniteMap, sizeFM, emptyFM, delFromFM, listToFM,
44                           lookupFM, addToFM, addToFM_C, addListToFM, 
45                           fmToList, elemFM, foldFM
46                         )
47 import Name             ( Name {-instance NamedThing-},
48                           nameModule, isLocallyDefined,
49                           isWiredInName, nameUnique, NamedThing(..)
50                          )
51 import Module           ( Module, moduleString, pprModule,
52                           mkVanillaModule, pprModuleName,
53                           moduleUserString, moduleName, isLibModule,
54                           ModuleName, WhereFrom(..),
55                         )
56 import RdrName          ( RdrName, rdrNameOcc )
57 import NameSet
58 import Var              ( Id )
59 import SrcLoc           ( mkSrcLoc, SrcLoc )
60 import PrelMods         ( pREL_GHC )
61 import PrelInfo         ( cCallishTyKeys )
62 import Bag
63 import Maybes           ( MaybeErr(..), maybeToBool, orElse )
64 import ListSetOps       ( unionLists )
65 import Outputable
66 import Unique           ( Unique )
67 import StringBuffer     ( StringBuffer, hGetStringBuffer )
68 import FastString       ( mkFastString )
69 import ErrUtils         ( Message )
70 import Lex
71 import Outputable
72
73 import IO       ( isDoesNotExistError )
74 import List     ( nub )
75 \end{code}
76
77
78 %*********************************************************
79 %*                                                      *
80 \subsection{Loading a new interface file}
81 %*                                                      *
82 %*********************************************************
83
84 \begin{code}
85 loadHomeInterface :: SDoc -> Name -> RnM d Ifaces
86 loadHomeInterface doc_str name
87   = loadInterface doc_str (moduleName (nameModule name)) ImportBySystem         `thenRn` \ (_, ifaces) ->
88     returnRn ifaces
89
90 loadOrphanModules :: [ModuleName] -> RnM d ()
91 loadOrphanModules mods
92   | null mods = returnRn ()
93   | otherwise = traceRn (text "Loading orphan modules:" <+> fsep (map pprModuleName mods))      `thenRn_` 
94                 mapRn_ load mods        `thenRn_`
95                 returnRn ()
96   where
97     load mod = loadInterface (pprModuleName mod <+> ptext SLIT("is a orphan-instance module")) mod ImportBySystem
98
99 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (Module, Ifaces)
100 loadInterface doc_str mod_name from
101  = getIfacesRn                  `thenRn` \ ifaces ->
102    let
103         mod_map  = iImpModInfo ifaces
104         mod_info = lookupFM mod_map mod_name
105         in_map   = maybeToBool mod_info
106    in
107
108         -- Issue a warning for a redundant {- SOURCE -} import
109         -- It's redundant if the moduld is in the iImpModInfo at all,
110         -- because we arrange to read all the ordinary imports before 
111         -- any of the {- SOURCE -} imports
112    warnCheckRn  (not (in_map && case from of {ImportByUserSource -> True; other -> False}))
113                 (warnRedundantSourceImport mod_name)    `thenRn_`
114
115         -- CHECK WHETHER WE HAVE IT ALREADY
116    case mod_info of {
117         Just (_, _, Just (load_mod, _, _))
118                 ->      -- We're read it already so don't re-read it
119                     returnRn (load_mod, ifaces) ;
120
121         mod_map_result ->
122
123         -- READ THE MODULE IN
124    findAndReadIface doc_str mod_name from in_map
125    `thenRn` \ (hi_boot_read, read_result) ->
126    case read_result of {
127         Nothing ->      -- Not found, so add an empty export env to the Ifaces map
128                         -- so that we don't look again
129            let
130                 mod         = mkVanillaModule mod_name
131                 new_mod_map = addToFM mod_map mod_name (0, False, Just (mod, False, []))
132                 new_ifaces  = ifaces { iImpModInfo = new_mod_map }
133            in
134            setIfacesRn new_ifaces               `thenRn_`
135            failWithRn (mod, new_ifaces) (noIfaceErr mod hi_boot_read) ;
136
137         -- Found and parsed!
138         Just (mod, iface) ->
139
140         -- LOAD IT INTO Ifaces
141
142         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
143         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
144         --     If we do loadExport first the wrong info gets into the cache (unless we
145         --      explicitly tag each export which seems a bit of a bore)
146
147     getModuleRn                 `thenRn` \ this_mod_nm ->
148     let
149         rd_decls = pi_decls iface
150     in
151     foldlRn (loadDecl mod)            (iDecls ifaces) rd_decls                  `thenRn` \ new_decls ->
152     foldlRn (loadInstDecl mod)        (iInsts ifaces) (pi_insts iface)          `thenRn` \ new_insts ->
153     (if opt_IgnoreIfacePragmas
154         then returnRn emptyBag
155         else foldlRn (loadRule mod)   (iRules ifaces) (pi_rules iface))         `thenRn` \ new_rules ->
156     (if opt_IgnoreIfacePragmas
157         then returnRn emptyNameEnv
158         else foldlRn (loadDeprec mod) (iDeprecs ifaces) (pi_deprecs iface))     `thenRn` \ new_deprecs ->
159     foldlRn (loadFixDecl mod_name)    (iFixes ifaces) rd_decls                  `thenRn` \ new_fixities ->
160     mapRn   (loadExport this_mod_nm)  (pi_exports iface)                        `thenRn` \ avails_s ->
161     let
162         -- For an explicit user import, add to mod_map info about
163         -- the things the imported module depends on, extracted
164         -- from its usage info.
165         mod_map1 = case from of
166                         ImportByUser -> addModDeps mod mod_map (pi_usages iface)
167                         other        -> mod_map
168
169         -- Now add info about this module
170         mod_map2    = addToFM mod_map1 mod_name mod_details
171         mod_details = (pi_mod iface, pi_orphan iface, Just (mod, hi_boot_read, concat avails_s))
172
173         new_ifaces = ifaces { iImpModInfo = mod_map2,
174                               iDecls      = new_decls,
175                               iFixes      = new_fixities,
176                               iInsts      = new_insts,
177                               iRules      = new_rules,
178                               iDeprecs    = new_deprecs }
179     in
180     setIfacesRn new_ifaces              `thenRn_`
181     returnRn (mod, new_ifaces)
182     }}
183
184 addModDeps :: Module -> ImportedModuleInfo
185            -> [ImportVersion a] -> ImportedModuleInfo
186 addModDeps mod mod_deps new_deps
187   = foldr add mod_deps new_deps
188   where
189     is_lib = isLibModule mod    -- Don't record dependencies when importing a library module
190     add (imp_mod, version, has_orphans, _) deps
191         | is_lib && not has_orphans = deps
192         | otherwise  =  addToFM_C combine deps imp_mod (version, has_orphans, Nothing)
193         -- Record dependencies for modules that are
194         --      either are dependent via a non-library module
195         --      or contain orphan rules or instance decls
196
197         -- Don't ditch a module that's already loaded!!
198     combine old@(_, _, Just _)  new = old
199     combine old@(_, _, Nothing) new = new
200
201 loadExport :: ModuleName -> ExportItem -> RnM d [AvailInfo]
202 loadExport this_mod (mod, entities)
203   | mod == this_mod = returnRn []
204         -- If the module exports anything defined in this module, just ignore it.
205         -- Reason: otherwise it looks as if there are two local definition sites
206         -- for the thing, and an error gets reported.  Easiest thing is just to
207         -- filter them out up front. This situation only arises if a module
208         -- imports itself, or another module that imported it.  (Necessarily,
209         -- this invoves a loop.)  Consequence: if you say
210         --      module A where
211         --         import B( AType )
212         --         type AType = ...
213         --
214         --      module B( AType ) where
215         --         import {-# SOURCE #-} A( AType )
216         --
217         -- then you'll get a 'B does not export AType' message.  A bit bogus
218         -- but it's a bogus thing to do!
219
220   | otherwise
221   = mapRn (load_entity mod) entities
222   where
223     new_name mod occ = mkImportedGlobalName mod occ
224
225     load_entity mod (Avail occ)
226       = new_name mod occ        `thenRn` \ name ->
227         returnRn (Avail name)
228     load_entity mod (AvailTC occ occs)
229       = new_name mod occ              `thenRn` \ name ->
230         mapRn (new_name mod) occs     `thenRn` \ names ->
231         returnRn (AvailTC name names)
232
233
234 loadFixDecl :: ModuleName -> FixityEnv
235             -> (Version, RdrNameHsDecl)
236             -> RnM d FixityEnv
237 loadFixDecl mod_name fixity_env (version, FixD sig@(FixitySig rdr_name fixity loc))
238   =     -- Ignore the version; when the fixity changes the version of
239         -- its 'host' entity changes, so we don't need a separate version
240         -- number for fixities
241     mkImportedGlobalName mod_name (rdrNameOcc rdr_name)         `thenRn` \ name ->
242     let
243         new_fixity_env = addToNameEnv fixity_env name (FixitySig name fixity loc)
244     in
245     returnRn new_fixity_env
246
247         -- Ignore the other sorts of decl
248 loadFixDecl mod_name fixity_env other_decl = returnRn fixity_env
249
250 loadDecl :: Module 
251          -> DeclsMap
252          -> (Version, RdrNameHsDecl)
253          -> RnM d DeclsMap
254
255 loadDecl mod decls_map (version, decl)
256   = getDeclBinders new_name decl        `thenRn` \ maybe_avail ->
257     case maybe_avail of {
258         Nothing -> returnRn decls_map;  -- No bindings
259         Just avail ->
260
261     getDeclSysBinders new_name decl     `thenRn` \ sys_bndrs ->
262     let
263         main_name     = availName avail
264         new_decls_map = foldl add_decl decls_map
265                                        [ (name, (version, avail, name==main_name, (mod, decl'))) 
266                                        | name <- sys_bndrs ++ availNames avail]
267         add_decl decls_map (name, stuff)
268           = WARN( name `elemNameEnv` decls_map, ppr name )
269             addToNameEnv decls_map name stuff
270     in
271     returnRn new_decls_map
272     }
273   where
274         -- newImportedBinder puts into the cache the binder with the
275         -- module information set correctly.  When the decl is later renamed,
276         -- the binding site will thereby get the correct module.
277     new_name rdr_name loc = newImportedBinder mod rdr_name
278
279     {-
280       If a signature decl is being loaded, and optIgnoreIfacePragmas is on,
281       we toss away unfolding information.
282
283       Also, if the signature is loaded from a module we're importing from source,
284       we do the same. This is to avoid situations when compiling a pair of mutually
285       recursive modules, peering at unfolding info in the interface file of the other, 
286       e.g., you compile A, it looks at B's interface file and may as a result change
287       its interface file. Hence, B is recompiled, maybe changing its interface file,
288       which will the unfolding info used in A to become invalid. Simple way out is to
289       just ignore unfolding info.
290
291       [Jan 99: I junked the second test above.  If we're importing from an hi-boot
292        file there isn't going to *be* any pragma info.  Maybe the above comment
293        dates from a time where we picked up a .hi file first if it existed?]
294     -}
295     decl' = case decl of
296                SigD (IfaceSig name tp ls loc) | opt_IgnoreIfacePragmas
297                          ->  SigD (IfaceSig name tp [] loc)
298                other     -> decl
299
300 loadInstDecl :: Module
301              -> Bag GatedDecl
302              -> RdrNameInstDecl
303              -> RnM d (Bag GatedDecl)
304 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
305   = 
306         -- Find out what type constructors and classes are "gates" for the
307         -- instance declaration.  If all these "gates" are slurped in then
308         -- we should slurp the instance decl too.
309         -- 
310         -- We *don't* want to count names in the context part as gates, though.
311         -- For example:
312         --              instance Foo a => Baz (T a) where ...
313         --
314         -- Here the gates are Baz and T, but *not* Foo.
315     let 
316         munged_inst_ty = removeContext inst_ty
317         free_names     = extractHsTyRdrNames munged_inst_ty
318     in
319     setModuleRn (moduleName mod) $
320     mapRn mkImportedGlobalFromRdrName free_names        `thenRn` \ gate_names ->
321     returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
322
323
324 -- In interface files, the instance decls now look like
325 --      forall a. Foo a -> Baz (T a)
326 -- so we have to strip off function argument types as well
327 -- as the bit before the '=>' (which is always empty in interface files)
328 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
329 removeContext ty                      = removeFuns ty
330
331 removeFuns (MonoFunTy _ ty) = removeFuns ty
332 removeFuns ty               = ty
333
334
335 loadRule :: Module -> Bag GatedDecl 
336          -> RdrNameRuleDecl -> RnM d (Bag GatedDecl)
337 -- "Gate" the rule simply by whether the rule variable is
338 -- needed.  We can refine this later.
339 loadRule mod rules decl@(IfaceRuleDecl var body src_loc)
340   = setModuleRn (moduleName mod) $
341     mkImportedGlobalFromRdrName var             `thenRn` \ var_name ->
342     returnRn ((unitNameSet var_name, (mod, RuleD decl)) `consBag` rules)
343
344 loadDeprec :: Module -> DeprecationEnv -> RdrNameDeprecation -> RnM d DeprecationEnv
345 loadDeprec mod deprec_env (DeprecMod txt)
346   = traceRn (text "module deprecation not yet implemented:" <+> ppr mod <> colon <+> ppr txt) `thenRn_`
347     returnRn deprec_env
348 loadDeprec mod deprec_env (DeprecName rdr_name txt)
349   = setModuleRn (moduleName mod) $
350     mkImportedGlobalFromRdrName rdr_name `thenRn` \ name ->
351     traceRn (text "loaded deprecation for" <+> ppr name <> colon <+> ppr txt) `thenRn_`
352     returnRn (addToNameEnv deprec_env name (DeprecName name txt))
353 \end{code}
354
355
356 %********************************************************
357 %*                                                      *
358 \subsection{Loading usage information}
359 %*                                                      *
360 %********************************************************
361
362 \begin{code}
363 checkUpToDate :: ModuleName -> RnMG Bool                -- True <=> no need to recompile
364 checkUpToDate mod_name
365   = getIfacesRn                                 `thenRn` \ ifaces ->
366     findAndReadIface doc_str mod_name 
367                      ImportByUser
368                      (error "checkUpToDate")    `thenRn` \ (_, read_result) ->
369
370         -- CHECK WHETHER WE HAVE IT ALREADY
371     case read_result of
372         Nothing ->      -- Old interface file not found, so we'd better bail out
373                     traceRn (sep [ptext SLIT("Didnt find old iface"), 
374                                   pprModuleName mod_name])      `thenRn_`
375                     returnRn False
376
377         Just (_, iface)
378                 ->      -- Found it, so now check it
379                     checkModUsage (pi_usages iface)
380   where
381         -- Only look in current directory, with suffix .hi
382     doc_str = sep [ptext SLIT("need usage info from"), pprModuleName mod_name]
383
384 checkModUsage [] = returnRn True                -- Yes!  Everything is up to date!
385
386 checkModUsage ((mod_name, old_mod_vers, _, Specifically []) : rest)
387         -- If CurrentModule.hi contains 
388         --      import Foo :: ;
389         -- then that simply records that Foo lies below CurrentModule in the
390         -- hierarchy, but CurrentModule doesn't depend in any way on Foo.
391         -- In this case we don't even want to open Foo's interface.
392   = traceRn (ptext SLIT("Nothing used from:") <+> ppr mod_name) `thenRn_`
393     checkModUsage rest  -- This one's ok, so check the rest
394
395 checkModUsage ((mod_name, old_mod_vers, _, whats_imported) : rest)
396   = loadInterface doc_str mod_name ImportBySystem       `thenRn` \ (mod, ifaces) ->
397     let
398         maybe_mod_vers = case lookupFM (iImpModInfo ifaces) mod_name of
399                            Just (version, _, Just (_, _, _)) -> Just version
400                            other                             -> Nothing
401     in
402     case maybe_mod_vers of {
403         Nothing ->      -- If we can't find a version number for the old module then
404                         -- bail out saying things aren't up to date
405                 traceRn (sep [ptext SLIT("Can't find version number for module"), 
406                               pprModuleName mod_name])
407                 `thenRn_` returnRn False ;
408
409         Just new_mod_vers ->
410
411         -- If the module version hasn't changed, just move on
412     if new_mod_vers == old_mod_vers then
413         traceRn (sep [ptext SLIT("Module version unchanged:"), pprModuleName mod_name])
414         `thenRn_` checkModUsage rest
415     else
416     traceRn (sep [ptext SLIT("Module version has changed:"), pprModuleName mod_name])
417     `thenRn_`
418         -- Module version changed, so check entities inside
419
420         -- If the usage info wants to say "I imported everything from this module"
421         --     it does so by making whats_imported equal to Everything
422         -- In that case, we must recompile
423     case whats_imported of {
424       Everything -> traceRn (ptext SLIT("...and I needed the whole module"))    `thenRn_`
425                     returnRn False;                -- Bale out
426
427       Specifically old_local_vers ->
428
429         -- Non-empty usage list, so check item by item
430     checkEntityUsage mod_name (iDecls ifaces) old_local_vers    `thenRn` \ up_to_date ->
431     if up_to_date then
432         traceRn (ptext SLIT("...but the bits I use haven't."))  `thenRn_`
433         checkModUsage rest      -- This one's ok, so check the rest
434     else
435         returnRn False          -- This one failed, so just bail out now
436     }}
437   where
438     doc_str = sep [ptext SLIT("need version info for"), pprModuleName mod_name]
439
440
441 checkEntityUsage mod decls [] 
442   = returnRn True       -- Yes!  All up to date!
443
444 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
445   = mkImportedGlobalName mod occ_name   `thenRn` \ name ->
446     case lookupNameEnv decls name of
447
448         Nothing       ->        -- We used it before, but it ain't there now
449                           traceRn (sep [ptext SLIT("No longer exported:"), ppr name])
450                           `thenRn_` returnRn False
451
452         Just (new_vers,_,_,_)   -- It's there, but is it up to date?
453                 | new_vers == old_vers
454                         -- Up to date, so check the rest
455                 -> checkEntityUsage mod decls rest
456
457                 | otherwise
458                         -- Out of date, so bale out
459                 -> traceRn (sep [ptext SLIT("Out of date:"), ppr name])  `thenRn_`
460                    returnRn False
461 \end{code}
462
463
464 %*********************************************************
465 %*                                                      *
466 \subsection{Getting in a declaration}
467 %*                                                      *
468 %*********************************************************
469
470 \begin{code}
471 importDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
472         -- Returns Nothing for 
473         --      (a) wired in name
474         --      (b) local decl
475         --      (c) already slurped
476
477 importDecl name
478   | isWiredInName name
479   = returnRn Nothing
480   | otherwise
481   = getSlurped                          `thenRn` \ already_slurped ->
482     if name `elemNameSet` already_slurped then
483         returnRn Nothing        -- Already dealt with
484     else
485         if isLocallyDefined name then   -- Don't bring in decls from
486                                         -- the renamed module's own interface file
487                   addWarnRn (importDeclWarn name) `thenRn_`
488                   returnRn Nothing
489         else
490         getNonWiredInDecl name
491 \end{code}
492
493 \begin{code}
494 getNonWiredInDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
495 getNonWiredInDecl needed_name 
496   = traceRn doc_str                             `thenRn_`
497     loadHomeInterface doc_str needed_name       `thenRn` \ ifaces ->
498     case lookupNameEnv (iDecls ifaces) needed_name of
499
500       Just (version,avail,_,decl)
501         -> recordSlurp (Just version) avail     `thenRn_`
502            returnRn (Just decl)
503
504       Nothing           -- Can happen legitimately for "Optional" occurrences
505         -> addErrRn (getDeclErr needed_name)    `thenRn_` 
506            returnRn Nothing
507   where
508      doc_str = ptext SLIT("need decl for") <+> ppr needed_name
509 \end{code}
510
511 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
512 It behaves exactly as if the wired in decl were actually in an interface file.
513 Specifically,
514 \begin{itemize}
515 \item   if the wired-in name is a data type constructor or a data constructor, 
516         it brings in the type constructor and all the data constructors; and
517         marks as ``occurrences'' any free vars of the data con.
518
519 \item   similarly for synonum type constructor
520
521 \item   if the wired-in name is another wired-in Id, it marks as ``occurrences''
522         the free vars of the Id's type.
523
524 \item   it loads the interface file for the wired-in thing for the
525         sole purpose of making sure that its instance declarations are available
526 \end{itemize}
527 All this is necessary so that we know all types that are ``in play'', so
528 that we know just what instances to bring into scope.
529         
530
531
532     
533 %*********************************************************
534 %*                                                      *
535 \subsection{Getting what a module exports}
536 %*                                                      *
537 %*********************************************************
538
539 @getInterfaceExports@ is called only for directly-imported modules.
540
541 \begin{code}
542 getInterfaceExports :: ModuleName -> WhereFrom -> RnMG (Module, Avails)
543 getInterfaceExports mod_name from
544   = loadInterface doc_str mod_name from `thenRn` \ (mod, ifaces) ->
545     case lookupFM (iImpModInfo ifaces) mod_name of
546         Nothing -> -- Not there; it must be that the interface file wasn't found;
547                    -- the error will have been reported already.
548                    -- (Actually loadInterface should put the empty export env in there
549                    --  anyway, but this does no harm.)
550                    returnRn (mod, [])
551
552         Just (_, _, Just (mod, _, avails)) -> returnRn (mod, avails)
553   where
554     doc_str = sep [pprModuleName mod_name, ptext SLIT("is directly imported")]
555 \end{code}
556
557
558 %*********************************************************
559 %*                                                      *
560 \subsection{Instance declarations are handled specially}
561 %*                                                      *
562 %*********************************************************
563
564 \begin{code}
565 getImportedInstDecls :: NameSet -> RnMG [(Module,RdrNameHsDecl)]
566 getImportedInstDecls gates
567   =     -- First, load any orphan-instance modules that aren't aready loaded
568         -- Orphan-instance modules are recorded in the module dependecnies
569     getIfacesRn                                         `thenRn` \ ifaces ->
570     let
571         orphan_mods =
572           [mod | (mod, (_, True, Nothing)) <- fmToList (iImpModInfo ifaces)]
573     in
574     loadOrphanModules orphan_mods                       `thenRn_` 
575
576         -- Now we're ready to grab the instance declarations
577         -- Find the un-gated ones and return them, 
578         -- removing them from the bag kept in Ifaces
579     getIfacesRn                                         `thenRn` \ ifaces ->
580     let
581         (decls, new_insts) = selectGated gates (iInsts ifaces)
582     in
583     setIfacesRn (ifaces { iInsts = new_insts })         `thenRn_`
584
585     traceRn (sep [text "getImportedInstDecls:", 
586                   nest 4 (fsep (map ppr gate_list)),
587                   text "Slurped" <+> int (length decls) <+> text "instance declarations",
588                   nest 4 (vcat (map ppr_brief_inst_decl decls))])       `thenRn_`
589     returnRn decls
590   where
591     gate_list      = nameSetToList gates
592
593     load_home gate | isLocallyDefined gate
594                    = returnRn ()
595                    | otherwise
596                    = loadHomeInterface (ppr gate <+> text "is an instance gate") gate   `thenRn_`
597                      returnRn ()
598
599 ppr_brief_inst_decl (mod, InstD (InstDecl inst_ty _ _ _ _))
600   = case inst_ty of
601         HsForAllTy _ _ tau -> ppr tau
602         other              -> ppr inst_ty
603
604 getImportedRules :: RnMG [(Module,RdrNameHsDecl)]
605 getImportedRules 
606   | opt_IgnoreIfacePragmas = returnRn []
607   | otherwise
608   = getIfacesRn         `thenRn` \ ifaces ->
609     let
610         gates              = iSlurp ifaces      -- Anything at all that's been slurped
611         (decls, new_rules) = selectGated gates (iRules ifaces)
612     in
613     setIfacesRn (ifaces { iRules = new_rules })         `thenRn_`
614     traceRn (sep [text "getImportedRules:", 
615                   text "Slurped" <+> int (length decls) <+> text "rules"])      `thenRn_`
616     returnRn decls
617
618 selectGated gates decl_bag
619         -- Select only those decls whose gates are *all* in 'gates'
620 #ifdef DEBUG
621   | opt_NoPruneDecls    -- Just to try the effect of not gating at all
622   = (foldrBag (\ (_,d) ds -> d:ds) [] decl_bag, emptyBag)       -- Grab them all
623
624   | otherwise
625 #endif
626   = foldrBag select ([], emptyBag) decl_bag
627   where
628     select (reqd, decl) (yes, no)
629         | isEmptyNameSet (reqd `minusNameSet` gates) = (decl:yes, no)
630         | otherwise                                  = (yes,      (reqd,decl) `consBag` no)
631
632 lookupFixity :: Name -> RnMS Fixity
633 lookupFixity name
634   | isLocallyDefined name
635   = getFixityEnv                        `thenRn` \ local_fix_env ->
636     case lookupNameEnv local_fix_env name of 
637         Just (FixitySig _ fix _) -> returnRn fix
638         Nothing                  -> returnRn defaultFixity
639
640   | otherwise   -- Imported
641       -- For imported names, we have to get their fixities by doing a loadHomeInterface,
642       -- and consulting the Ifaces that comes back from that, because the interface
643       -- file for the Name might not have been loaded yet.  Why not?  Suppose you import module A,
644       -- which exports a function 'f', which is defined in module B.  Then B isn't loaded
645       -- right away (after all, it's possible that nothing from B will be used).
646       -- When we come across a use of 'f', we need to know its fixity, and it's then,
647       -- and only then, that we load B.hi.  That is what's happening here.
648   = loadHomeInterface doc name          `thenRn` \ ifaces ->
649     case lookupNameEnv (iFixes ifaces) name of
650         Just (FixitySig _ fix _) -> returnRn fix 
651         Nothing                  -> returnRn defaultFixity
652   where
653     doc = ptext SLIT("Checking fixity for") <+> ppr name
654 \end{code}
655
656
657 %*********************************************************
658 %*                                                      *
659 \subsection{Keeping track of what we've slurped, and version numbers}
660 %*                                                      *
661 %*********************************************************
662
663 getImportVersions figures out what the ``usage information'' for this
664 moudule is; that is, what it must record in its interface file as the
665 things it uses.  It records:
666
667 \begin{itemize}
668 \item   anything reachable from its body code
669 \item   any module exported with a @module Foo@.
670 \end{itemize}
671 %
672 Why the latter?  Because if @Foo@ changes then this module's export list
673 will change, so we must recompile this module at least as far as
674 making a new interface file --- but in practice that means complete
675 recompilation.
676
677 What about this? 
678 \begin{verbatim}
679         module A( f, g ) where  |       module B( f ) where
680           import B( f )         |         f = h 3
681           g = ...               |         h = ...
682 \end{verbatim}
683
684 Should we record @B.f@ in @A@'s usages?  In fact we don't.  Certainly,
685 if anything about @B.f@ changes than anyone who imports @A@ should be
686 recompiled; they'll get an early exit if they don't use @B.f@.
687 However, even if @B.f@ doesn't change at all, @B.h@ may do so, and
688 this change may not be reflected in @f@'s version number.  So there
689 are two things going on when compiling module @A@:
690
691 \begin{enumerate}
692 \item   Are @A.o@ and @A.hi@ correct?  Then we can bale out early.
693 \item   Should modules that import @A@ be recompiled?
694 \end{enumerate}
695
696 For (1) it is slightly harmful to record @B.f@ in @A@'s usages,
697 because a change in @B.f@'s version will provoke full recompilation of
698 @A@, producing an identical @A.o@, and @A.hi@ differing only in its
699 usage-version of @B.f@ (and this usage-version info isn't used by any
700 importer).
701
702 For (2), because of the tricky @B.h@ question above, we ensure that
703 @A.hi@ is touched (even if identical to its previous version) if A's
704 recompilation was triggered by an imported @.hi@ file date change.
705 Given that, there's no need to record @B.f@ in @A@'s usages.
706
707 On the other hand, if @A@ exports @module B@, then we {\em do} count
708 @module B@ among @A@'s usages, because we must recompile @A@ to ensure
709 that @A.hi@ changes appropriately.
710
711 HOWEVER, we *do* record the usage
712         import B <n> :: ;
713 in A.hi, to record the fact that A does import B.  This is used to decide
714 to look to look for B.hi rather than B.hi-boot when compiling a module that
715 imports A.  This line says that A imports B, but uses nothing in it.
716 So we'll get an early bale-out when compiling A if B's version changes.
717
718 \begin{code}
719 getImportVersions :: ModuleName                 -- Name of this module
720                   -> ExportEnv                  -- Info about exports 
721                   -> RnMG (VersionInfo Name)    -- Version info for these names
722
723 getImportVersions this_mod (ExportEnv export_avails _ export_all_mods)
724   = getIfacesRn                                 `thenRn` \ ifaces ->
725     let
726         mod_map   = iImpModInfo ifaces
727         imp_names = iVSlurp     ifaces
728
729         -- mv_map groups together all the things imported from a particular module.
730         mv_map :: FiniteMap ModuleName [(Name,Version)]
731         mv_map = foldr add_mv emptyFM imp_names
732
733         -- Build the result list by adding info for each module.
734         -- For (a) a library module, we don't record it at all unless it contains orphans
735         --         (We must never lose track of orphans.)
736         -- 
737         --     (b) a source-imported module, don't record the dependency at all
738         --      
739         -- (b) may seem a bit strange.  The idea is that the usages in a .hi file records
740         -- *all* the module's dependencies other than the loop-breakers.  We use
741         -- this info in findAndReadInterface to decide whether to look for a .hi file or
742         -- a .hi-boot file.  
743         --
744         -- This means we won't track version changes, or orphans, from .hi-boot files.
745         -- The former is potentially rather bad news.  It could be fixed by recording
746         -- whether something is a boot file along with the usage info for it, but 
747         -- I can't be bothered just now.
748
749         mk_version_info mod_name (version, has_orphans, contents) so_far
750            = let
751                 go_for_it exports = (mod_name, version, has_orphans, exports) : so_far
752              in 
753              case contents of
754                 Nothing ->      -- We didn't even open the interface
755                         -- This happens when a module, Foo, that we explicitly imported has 
756                         -- 'import Baz' in its interface file, recording that Baz is below
757                         -- Foo in the module dependency hierarchy.  We want to propagate this
758                         -- information.  The Nothing says that we didn't even open the interface
759                         -- file but we must still propagate the dependeny info.
760                    go_for_it (Specifically [])
761
762                 Just (mod, boot_import, _)              -- We did open the interface
763                    |  boot_import                       -- Don't record any usage info for this module
764                    || (is_lib_module && not has_orphans)
765                    -> so_far            
766            
767                    |  is_lib_module                     -- Record the module but not detailed
768                    || mod_name `elem` export_all_mods   -- version information for the imports
769                    -> go_for_it Everything
770
771                    |  otherwise
772                    -> case lookupFM mv_map mod_name of
773                         Just whats_imported -> go_for_it (Specifically whats_imported)
774                         Nothing             -> go_for_it (Specifically [])
775                                                 -- This happens if you have
776                                                 --      import Foo
777                                                 -- but don't actually *use* anything from Foo
778                                                 -- In which case record an empty dependency list
779                    where
780                      is_lib_module     = isLibModule mod
781              
782     in
783         -- A module shouldn't load its own interface
784         -- This seems like a convenient place to check
785     WARN( maybeToBool (lookupFM mod_map this_mod), 
786           ptext SLIT("Wierd:") <+> ppr this_mod <+> ptext SLIT("loads its own interface") )
787
788     returnRn (foldFM mk_version_info [] mod_map)
789   where
790      add_mv v@(name, version) mv_map
791       = addToFM_C add_item mv_map mod [v] 
792       where
793          mod = moduleName (nameModule name)
794          add_item vs _ = (v:vs)
795 \end{code}
796
797 \begin{code}
798 getSlurped
799   = getIfacesRn         `thenRn` \ ifaces ->
800     returnRn (iSlurp ifaces)
801
802 recordSlurp maybe_version avail
803   = getIfacesRn         `thenRn` \ ifaces@(Ifaces { iSlurp  = slurped_names,
804                                                     iVSlurp = imp_names }) ->
805     let
806         new_slurped_names = addAvailToNameSet slurped_names avail
807
808         new_imp_names = case maybe_version of
809                            Just version -> (availName avail, version) : imp_names
810                            Nothing      -> imp_names
811     in
812     setIfacesRn (ifaces { iSlurp  = new_slurped_names,
813                           iVSlurp = new_imp_names })
814 \end{code}
815
816
817 %*********************************************************
818 %*                                                      *
819 \subsection{Getting binders out of a declaration}
820 %*                                                      *
821 %*********************************************************
822
823 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
824 It's used for both source code (from @availsFromDecl@) and interface files
825 (from @loadDecl@).
826
827 It doesn't deal with source-code specific things: @ValD@, @DefD@.  They
828 are handled by the sourc-code specific stuff in @RnNames@.
829
830 \begin{code}
831 getDeclBinders :: (RdrName -> SrcLoc -> RnM d Name)     -- New-name function
832                 -> RdrNameHsDecl
833                 -> RnM d (Maybe AvailInfo)
834
835 getDeclBinders new_name (TyClD (TyData _ _ tycon _ condecls _ _ src_loc))
836   = new_name tycon src_loc                      `thenRn` \ tycon_name ->
837     getConFieldNames new_name condecls          `thenRn` \ sub_names ->
838     returnRn (Just (AvailTC tycon_name (tycon_name : nub sub_names)))
839         -- The "nub" is because getConFieldNames can legitimately return duplicates,
840         -- when a record declaration has the same field in multiple constructors
841
842 getDeclBinders new_name (TyClD (TySynonym tycon _ _ src_loc))
843   = new_name tycon src_loc              `thenRn` \ tycon_name ->
844     returnRn (Just (AvailTC tycon_name [tycon_name]))
845
846 getDeclBinders new_name (TyClD (ClassDecl _ cname _ _ sigs _ _ _ _ _ src_loc))
847   = new_name cname src_loc                      `thenRn` \ class_name ->
848
849         -- Record the names for the class ops
850     let
851         -- just want class-op sigs
852         op_sigs = filter isClassOpSig sigs
853     in
854     mapRn (getClassOpNames new_name) op_sigs    `thenRn` \ sub_names ->
855
856     returnRn (Just (AvailTC class_name (class_name : sub_names)))
857
858 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
859   = new_name var src_loc                        `thenRn` \ var_name ->
860     returnRn (Just (Avail var_name))
861
862 getDeclBinders new_name (FixD _)  = returnRn Nothing
863
864     -- foreign declarations
865 getDeclBinders new_name (ForD (ForeignDecl nm kind _ dyn _ loc))
866   | binds_haskell_name kind dyn
867   = new_name nm loc                 `thenRn` \ name ->
868     returnRn (Just (Avail name))
869
870   | otherwise -- a foreign export
871   = lookupImplicitOccRn nm `thenRn_` 
872     returnRn Nothing
873
874 getDeclBinders new_name (DefD _)  = returnRn Nothing
875 getDeclBinders new_name (InstD _) = returnRn Nothing
876 getDeclBinders new_name (RuleD _) = returnRn Nothing
877
878 binds_haskell_name (FoImport _) _   = True
879 binds_haskell_name FoLabel      _   = True
880 binds_haskell_name FoExport  ext_nm = isDynamic ext_nm
881
882 ----------------
883 getConFieldNames new_name (ConDecl con _ _ (RecCon fielddecls) src_loc : rest)
884   = mapRn (\n -> new_name n src_loc) (con:fields)       `thenRn` \ cfs ->
885     getConFieldNames new_name rest                      `thenRn` \ ns  -> 
886     returnRn (cfs ++ ns)
887   where
888     fields = concat (map fst fielddecls)
889
890 getConFieldNames new_name (ConDecl con _ _ condecl src_loc : rest)
891   = new_name con src_loc                `thenRn` \ n ->
892     (case condecl of
893       NewCon _ (Just f) -> 
894         new_name f src_loc `thenRn` \ new_f ->
895         returnRn [n,new_f]
896       _ -> returnRn [n])                `thenRn` \ nn ->
897     getConFieldNames new_name rest      `thenRn` \ ns -> 
898     returnRn (nn ++ ns)
899
900 getConFieldNames new_name [] = returnRn []
901
902 getClassOpNames new_name (ClassOpSig op _ _ _ src_loc) = new_name op src_loc
903 \end{code}
904
905 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
906 A the moment that's just the tycon and datacon that come with a class decl.
907 They aren't returned by @getDeclBinders@ because they aren't in scope;
908 but they {\em should} be put into the @DeclsMap@ of this module.
909
910 Note that this excludes the default-method names of a class decl,
911 and the dict fun of an instance decl, because both of these have 
912 bindings of their own elsewhere.
913
914 \begin{code}
915 getDeclSysBinders new_name (TyClD (ClassDecl _ cname _ _ sigs _ _ tname dname snames src_loc))
916   = new_name dname src_loc                              `thenRn` \ datacon_name ->
917     new_name tname src_loc                              `thenRn` \ tycon_name ->
918     sequenceRn [new_name n src_loc | n <- snames]       `thenRn` \ scsel_names ->
919     returnRn (tycon_name : datacon_name : scsel_names)
920
921 getDeclSysBinders new_name other_decl
922   = returnRn []
923 \end{code}
924
925 %*********************************************************
926 %*                                                      *
927 \subsection{Reading an interface file}
928 %*                                                      *
929 %*********************************************************
930
931 \begin{code}
932 findAndReadIface :: SDoc -> ModuleName -> WhereFrom 
933                  -> Bool        -- Only relevant for SystemImport
934                                 -- True  <=> Look for a .hi file
935                                 -- False <=> Look for .hi-boot file unless there's
936                                 --           a library .hi file
937                  -> RnM d (Bool, Maybe (Module, ParsedIface))
938         -- Bool is True if the interface actually read was a .hi-boot one
939         -- Nothing <=> file not found, or unreadable, or illegible
940         -- Just x  <=> successfully found and parsed 
941
942 findAndReadIface doc_str mod_name from hi_file
943   = traceRn trace_msg                   `thenRn_`
944       -- we keep two maps for interface files,
945       -- one for 'normal' ones, the other for .hi-boot files,
946       -- hence the need to signal which kind we're interested.
947
948     getHiMaps                   `thenRn` \ hi_maps ->
949         
950     case find_path from hi_maps of
951          -- Found the file
952        (hi_boot, Just (fpath, mod)) -> traceRn (ptext SLIT("...reading from") <+> text fpath)
953                                        `thenRn_`
954                                        readIface mod fpath      `thenRn` \ result ->
955                                        returnRn (hi_boot, result)
956        (hi_boot, Nothing)           -> traceRn (ptext SLIT("...not found"))     `thenRn_`
957                                        returnRn (hi_boot, Nothing)
958   where
959     find_path ImportByUser       (hi_map, _)     = (False, lookupFM hi_map mod_name)
960     find_path ImportByUserSource (_, hiboot_map) = (True,  lookupFM hiboot_map mod_name)
961
962     find_path ImportBySystem     (hi_map, hiboot_map)
963       | hi_file
964       =         -- If the module we seek is in our dependent set, 
965                 -- Look for a .hi file
966          (False, lookupFM hi_map mod_name)
967
968       | otherwise
969                 -- Check if there's a library module of that name
970                 -- If not, look for an hi-boot file
971       = case lookupFM hi_map mod_name of
972            stuff@(Just (_, mod)) | isLibModule mod -> (False, stuff)
973            other                                   -> (True, lookupFM hiboot_map mod_name)
974
975     trace_msg = sep [hsep [ptext SLIT("Reading"), 
976                            ppr from,
977                            ptext SLIT("interface for"), 
978                            pprModuleName mod_name <> semi],
979                      nest 4 (ptext SLIT("reason:") <+> doc_str)]
980 \end{code}
981
982 @readIface@ tries just the one file.
983
984 \begin{code}
985 readIface :: Module -> String -> RnM d (Maybe (Module, ParsedIface))
986         -- Nothing <=> file not found, or unreadable, or illegible
987         -- Just x  <=> successfully found and parsed 
988 readIface the_mod file_path
989   = ioToRnM (hGetStringBuffer False file_path)       `thenRn` \ read_result ->
990     case read_result of
991         Right contents    -> 
992              case parseIface contents
993                         PState{ bol = 0#, atbol = 1#,
994                                 context = [],
995                                 glasgow_exts = 1#,
996                                 loc = mkSrcLoc (mkFastString file_path) 1 } of
997                   POk _  (PIface mod_nm iface) ->
998                     warnCheckRn (mod_nm == moduleName the_mod)
999                                 (hiModuleNameMismatchWarn the_mod mod_nm) `thenRn_`
1000                     returnRn (Just (the_mod, iface))
1001
1002                   PFailed err   -> failWithRn Nothing err 
1003                   other         -> failWithRn Nothing (ptext SLIT("Unrecognisable interface file"))
1004                                 -- This last case can happen if the interface file is (say) empty
1005                                 -- in which case the parser thinks it looks like an IdInfo or
1006                                 -- something like that.  Just an artefact of the fact that the
1007                                 -- parser is used for several purposes at once.
1008
1009         Left err
1010           | isDoesNotExistError err -> returnRn Nothing
1011           | otherwise               -> failWithRn Nothing (cannaeReadFile file_path err)
1012 \end{code}
1013
1014 %*********************************************************
1015 %*                                                       *
1016 \subsection{Errors}
1017 %*                                                       *
1018 %*********************************************************
1019
1020 \begin{code}
1021 noIfaceErr filename boot_file
1022   = hsep [ptext SLIT("Could not find valid"), boot, 
1023           ptext SLIT("interface file"), quotes (pprModule filename)]
1024   where
1025     boot | boot_file = ptext SLIT("[boot]")
1026          | otherwise = empty
1027
1028 cannaeReadFile file err
1029   = hcat [ptext SLIT("Failed in reading file: "), 
1030           text file, 
1031           ptext SLIT("; error="), 
1032           text (show err)]
1033
1034 getDeclErr name
1035   = ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name)
1036
1037 getDeclWarn name loc
1038   = sep [ptext SLIT("Failed to find (optional) interface decl for") <+> quotes (ppr name),
1039          ptext SLIT("desired at") <+> ppr loc]
1040
1041 importDeclWarn name
1042   = sep [ptext SLIT(
1043     "Compiler tried to import decl from interface file with same name as module."), 
1044          ptext SLIT(
1045     "(possible cause: module name clashes with interface file already in scope.)")
1046         ] $$
1047     hsep [ptext SLIT("name:"), quotes (ppr name)]
1048
1049 warnRedundantSourceImport mod_name
1050   = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
1051           <+> quotes (pprModuleName mod_name)
1052
1053 hiModuleNameMismatchWarn :: Module -> ModuleName -> Message
1054 hiModuleNameMismatchWarn requested_mod mod_nm = 
1055     hsep [ ptext SLIT("Something is amiss; requested module name")
1056          , pprModule requested_mod
1057          , ptext SLIT("differs from name found in the interface file ")
1058          , pprModuleName mod_nm
1059          ]
1060
1061 \end{code}