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