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