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