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