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