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