2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
9 getImportedInstDecls, getImportedRules,
10 lookupFixity, loadHomeInterface,
11 importDecl, recordSlurp,
12 getImportVersions, getSlurped,
16 getDeclBinders, getDeclSysBinders,
17 removeContext -- removeContext probably belongs somewhere else
20 #include "HsVersions.h"
22 import CmdLineOpts ( opt_NoPruneDecls, opt_IgnoreIfacePragmas )
23 import HsSyn ( HsDecl(..), TyClDecl(..), InstDecl(..), IfaceSig(..),
24 HsType(..), ConDecl(..), IE(..), ConDetails(..), Sig(..),
25 FixitySig(..), RuleDecl(..),
28 import BasicTypes ( Version, NewOrData(..), defaultFixity )
29 import RdrHsSyn ( RdrNameHsDecl, RdrNameInstDecl, RdrNameTyClDecl, RdrNameRuleDecl,
32 import RnEnv ( mkImportedGlobalName, newImportedBinder, mkImportedGlobalFromRdrName,
35 availName, availNames, addAvailToNameSet,
39 import RnHsSyn ( RenamedHsDecl )
40 import ParseIface ( parseIface, IfaceStuff(..) )
42 import FiniteMap ( FiniteMap, sizeFM, emptyFM, delFromFM,
43 lookupFM, addToFM, addToFM_C, addListToFM,
44 fmToList, elemFM, foldFM
46 import Name ( Name {-instance NamedThing-},
47 nameModule, isLocallyDefined,
48 isWiredInName, nameUnique, NamedThing(..)
50 import Module ( Module, moduleString, pprModule,
51 mkVanillaModule, pprModuleName,
52 moduleUserString, moduleName, isLibModule,
53 ModuleName, WhereFrom(..),
55 import RdrName ( RdrName, rdrNameOcc )
58 import SrcLoc ( mkSrcLoc, SrcLoc )
59 import PrelMods ( pREL_GHC )
60 import PrelInfo ( cCallishTyKeys, thinAirModules )
62 import Maybes ( MaybeErr(..), maybeToBool, orElse )
63 import ListSetOps ( unionLists )
65 import Unique ( Unique )
66 import StringBuffer ( StringBuffer, hGetStringBuffer )
67 import FastString ( mkFastString )
71 import IO ( isDoesNotExistError )
76 %*********************************************************
78 \subsection{Loading a new interface file}
80 %*********************************************************
83 loadHomeInterface :: SDoc -> Name -> RnM d Ifaces
84 loadHomeInterface doc_str name
85 = loadInterface doc_str (moduleName (nameModule name)) ImportBySystem `thenRn` \ (_, ifaces) ->
88 loadOrphanModules :: [ModuleName] -> RnM d ()
89 loadOrphanModules mods
90 | null mods = returnRn ()
91 | otherwise = traceRn (text "Loading orphan modules:" <+> fsep (map pprModuleName mods)) `thenRn_`
92 mapRn_ load mods `thenRn_`
95 load mod = loadInterface (pprModuleName mod <+> ptext SLIT("is a orphan-instance module")) mod ImportBySystem
97 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (Module, Ifaces)
98 loadInterface doc_str mod_name from
99 = getIfacesRn `thenRn` \ ifaces ->
101 mod_map = iImpModInfo ifaces
102 mod_info = lookupFM mod_map mod_name
103 in_map = maybeToBool mod_info
106 -- Issue a warning for a redundant {- SOURCE -} import
107 -- It's redundant if the moduld is in the iImpModInfo at all,
108 -- because we arrange to read all the ordinary imports before
109 -- any of the {- SOURCE -} imports
110 warnCheckRn (not (in_map && case from of {ImportByUserSource -> True; other -> False}))
111 (warnRedundantSourceImport mod_name) `thenRn_`
113 -- CHECK WHETHER WE HAVE IT ALREADY
115 Just (_, _, Just (load_mod, _, _))
116 -> -- We're read it already so don't re-read it
117 returnRn (load_mod, ifaces) ;
121 -- READ THE MODULE IN
122 findAndReadIface doc_str mod_name from in_map
123 `thenRn` \ (hi_boot_read, read_result) ->
124 case read_result of {
125 Nothing -> -- Not found, so add an empty export env to the Ifaces map
126 -- so that we don't look again
128 mod = mkVanillaModule mod_name
129 new_mod_map = addToFM mod_map mod_name (0, False, Just (mod, False, []))
130 new_ifaces = ifaces { iImpModInfo = new_mod_map }
132 setIfacesRn new_ifaces `thenRn_`
133 failWithRn (mod, new_ifaces) (noIfaceErr mod hi_boot_read) ;
138 -- LOAD IT INTO Ifaces
140 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
141 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
142 -- If we do loadExport first the wrong info gets into the cache (unless we
143 -- explicitly tag each export which seems a bit of a bore)
145 getModuleRn `thenRn` \ this_mod_nm ->
147 rd_decls = pi_decls iface
149 foldlRn (loadDecl mod) (iDecls ifaces) rd_decls `thenRn` \ new_decls ->
150 foldlRn (loadInstDecl mod) (iInsts ifaces) (pi_insts iface) `thenRn` \ new_insts ->
151 foldlRn (loadRule mod) (iRules ifaces) (pi_rules iface) `thenRn` \ new_rules ->
152 foldlRn (loadFixDecl mod_name) (iFixes ifaces) rd_decls `thenRn` \ new_fixities ->
153 mapRn (loadExport this_mod_nm) (pi_exports iface) `thenRn` \ avails_s ->
155 -- For an explicit user import, add to mod_map info about
156 -- the things the imported module depends on, extracted
157 -- from its usage info.
158 mod_map1 = case from of
159 ImportByUser -> addModDeps mod mod_map (pi_usages iface)
162 -- Now add info about this module
163 mod_map2 = addToFM mod_map1 mod_name mod_details
164 mod_details = (pi_mod iface, pi_orphan iface, Just (mod, hi_boot_read, concat avails_s))
166 new_ifaces = ifaces { iImpModInfo = mod_map2,
168 iFixes = new_fixities,
172 setIfacesRn new_ifaces `thenRn_`
173 returnRn (mod, new_ifaces)
176 addModDeps :: Module -> ImportedModuleInfo
177 -> [ImportVersion a] -> ImportedModuleInfo
178 addModDeps mod mod_deps new_deps
179 = foldr add mod_deps new_deps
181 is_lib = isLibModule mod -- Don't record dependencies when importing a library module
182 add (imp_mod, version, has_orphans, _) deps
183 | is_lib && not has_orphans = deps
184 | otherwise = addToFM_C combine deps imp_mod (version, has_orphans, Nothing)
185 -- Record dependencies for modules that are
186 -- either are dependent via a non-library module
187 -- or contain orphan rules or instance decls
189 -- Don't ditch a module that's already loaded!!
190 combine old@(_, _, Just _) new = old
191 combine old@(_, _, Nothing) new = new
193 loadExport :: ModuleName -> ExportItem -> RnM d [AvailInfo]
194 loadExport this_mod (mod, entities)
195 | mod == this_mod = returnRn []
196 -- If the module exports anything defined in this module, just ignore it.
197 -- Reason: otherwise it looks as if there are two local definition sites
198 -- for the thing, and an error gets reported. Easiest thing is just to
199 -- filter them out up front. This situation only arises if a module
200 -- imports itself, or another module that imported it. (Necessarily,
201 -- this invoves a loop.) Consequence: if you say
206 -- module B( AType ) where
207 -- import {-# SOURCE #-} A( AType )
209 -- then you'll get a 'B does not export AType' message. A bit bogus
210 -- but it's a bogus thing to do!
213 = mapRn (load_entity mod) entities
215 new_name mod occ = mkImportedGlobalName mod occ
217 load_entity mod (Avail occ)
218 = new_name mod occ `thenRn` \ name ->
219 returnRn (Avail name)
220 load_entity mod (AvailTC occ occs)
221 = new_name mod occ `thenRn` \ name ->
222 mapRn (new_name mod) occs `thenRn` \ names ->
223 returnRn (AvailTC name names)
226 loadFixDecl :: ModuleName -> FixityEnv
227 -> (Version, RdrNameHsDecl)
229 loadFixDecl mod_name fixity_env (version, FixD sig@(FixitySig rdr_name fixity loc))
230 = -- Ignore the version; when the fixity changes the version of
231 -- its 'host' entity changes, so we don't need a separate version
232 -- number for fixities
233 mkImportedGlobalName mod_name (rdrNameOcc rdr_name) `thenRn` \ name ->
235 new_fixity_env = addToNameEnv fixity_env name (FixitySig name fixity loc)
237 returnRn new_fixity_env
239 -- Ignore the other sorts of decl
240 loadFixDecl mod_name fixity_env other_decl = returnRn fixity_env
244 -> (Version, RdrNameHsDecl)
247 loadDecl mod decls_map (version, decl)
248 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
249 case maybe_avail of {
250 Nothing -> returnRn decls_map; -- No bindings
253 getDeclSysBinders new_name decl `thenRn` \ sys_bndrs ->
255 main_name = availName avail
256 new_decls_map = foldl add_decl decls_map
257 [ (name, (version, avail, name==main_name, (mod, decl')))
258 | name <- sys_bndrs ++ availNames avail]
259 add_decl decls_map (name, stuff)
260 = WARN( name `elemNameEnv` decls_map, ppr name )
261 addToNameEnv decls_map name stuff
263 returnRn new_decls_map
266 -- newImportedBinder puts into the cache the binder with the
267 -- module information set correctly. When the decl is later renamed,
268 -- the binding site will thereby get the correct module.
269 new_name rdr_name loc = newImportedBinder mod rdr_name
272 If a signature decl is being loaded, and optIgnoreIfacePragmas is on,
273 we toss away unfolding information.
275 Also, if the signature is loaded from a module we're importing from source,
276 we do the same. This is to avoid situations when compiling a pair of mutually
277 recursive modules, peering at unfolding info in the interface file of the other,
278 e.g., you compile A, it looks at B's interface file and may as a result change
279 its interface file. Hence, B is recompiled, maybe changing its interface file,
280 which will the unfolding info used in A to become invalid. Simple way out is to
281 just ignore unfolding info.
283 [Jan 99: I junked the second test above. If we're importing from an hi-boot
284 file there isn't going to *be* any pragma info. Maybe the above comment
285 dates from a time where we picked up a .hi file first if it existed?]
288 SigD (IfaceSig name tp ls loc) | opt_IgnoreIfacePragmas
289 -> SigD (IfaceSig name tp [] loc)
292 loadInstDecl :: Module
295 -> RnM d (Bag GatedDecl)
296 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
298 -- Find out what type constructors and classes are "gates" for the
299 -- instance declaration. If all these "gates" are slurped in then
300 -- we should slurp the instance decl too.
302 -- We *don't* want to count names in the context part as gates, though.
304 -- instance Foo a => Baz (T a) where ...
306 -- Here the gates are Baz and T, but *not* Foo.
308 munged_inst_ty = removeContext inst_ty
309 free_names = extractHsTyRdrNames munged_inst_ty
311 setModuleRn (moduleName mod) $
312 mapRn mkImportedGlobalFromRdrName free_names `thenRn` \ gate_names ->
313 returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
316 -- In interface files, the instance decls now look like
317 -- forall a. Foo a -> Baz (T a)
318 -- so we have to strip off function argument types as well
319 -- as the bit before the '=>' (which is always empty in interface files)
320 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
321 removeContext ty = removeFuns ty
323 removeFuns (MonoFunTy _ ty) = removeFuns ty
327 loadRule :: Module -> Bag GatedDecl
328 -> RdrNameRuleDecl -> RnM d (Bag GatedDecl)
329 -- "Gate" the rule simply by whether the rule variable is
330 -- needed. We can refine this later.
331 loadRule mod rules decl@(IfaceRuleDecl var body src_loc)
332 = setModuleRn (moduleName mod) $
333 mkImportedGlobalFromRdrName var `thenRn` \ var_name ->
334 returnRn ((unitNameSet var_name, (mod, RuleD decl)) `consBag` rules)
338 %********************************************************
340 \subsection{Loading usage information}
342 %********************************************************
345 checkUpToDate :: ModuleName -> RnMG Bool -- True <=> no need to recompile
346 checkUpToDate mod_name
347 = getIfacesRn `thenRn` \ ifaces ->
348 findAndReadIface doc_str mod_name
350 (error "checkUpToDate") `thenRn` \ (_, read_result) ->
352 -- CHECK WHETHER WE HAVE IT ALREADY
354 Nothing -> -- Old interface file not found, so we'd better bail out
355 traceRn (sep [ptext SLIT("Didnt find old iface"),
356 pprModuleName mod_name]) `thenRn_`
360 -> -- Found it, so now check it
361 checkModUsage (pi_usages iface)
363 -- Only look in current directory, with suffix .hi
364 doc_str = sep [ptext SLIT("need usage info from"), pprModuleName mod_name]
366 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
368 checkModUsage ((mod_name, old_mod_vers, _, whats_imported) : rest)
369 = loadInterface doc_str mod_name ImportBySystem `thenRn` \ (mod, ifaces) ->
371 maybe_mod_vers = case lookupFM (iImpModInfo ifaces) mod_name of
372 Just (version, _, Just (_, _, _)) -> Just version
375 case maybe_mod_vers of {
376 Nothing -> -- If we can't find a version number for the old module then
377 -- bail out saying things aren't up to date
378 traceRn (sep [ptext SLIT("Can't find version number for module"),
379 pprModuleName mod_name])
380 `thenRn_` returnRn False ;
384 -- If the module version hasn't changed, just move on
385 if new_mod_vers == old_mod_vers then
386 traceRn (sep [ptext SLIT("Module version unchanged:"), pprModuleName mod_name])
387 `thenRn_` checkModUsage rest
389 traceRn (sep [ptext SLIT("Module version has changed:"), pprModuleName mod_name])
391 -- Module version changed, so check entities inside
393 -- If the usage info wants to say "I imported everything from this module"
394 -- it does so by making whats_imported equal to Everything
395 -- In that case, we must recompile
396 case whats_imported of {
397 Everything -> traceRn (ptext SLIT("...and I needed the whole module")) `thenRn_`
398 returnRn False; -- Bale out
400 Specifically old_local_vers ->
402 -- Non-empty usage list, so check item by item
403 checkEntityUsage mod_name (iDecls ifaces) old_local_vers `thenRn` \ up_to_date ->
405 traceRn (ptext SLIT("...but the bits I use haven't.")) `thenRn_`
406 checkModUsage rest -- This one's ok, so check the rest
408 returnRn False -- This one failed, so just bail out now
411 doc_str = sep [ptext SLIT("need version info for"), pprModuleName mod_name]
414 checkEntityUsage mod decls []
415 = returnRn True -- Yes! All up to date!
417 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
418 = mkImportedGlobalName mod occ_name `thenRn` \ name ->
419 case lookupNameEnv decls name of
421 Nothing -> -- We used it before, but it ain't there now
422 putDocRn (sep [ptext SLIT("No longer exported:"), ppr name])
423 `thenRn_` returnRn False
425 Just (new_vers,_,_,_) -- It's there, but is it up to date?
426 | new_vers == old_vers
427 -- Up to date, so check the rest
428 -> checkEntityUsage mod decls rest
431 -- Out of date, so bale out
432 -> putDocRn (sep [ptext SLIT("Out of date:"), ppr name]) `thenRn_`
437 %*********************************************************
439 \subsection{Getting in a declaration}
441 %*********************************************************
444 importDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
445 -- Returns Nothing for
448 -- (c) already slurped
454 = getSlurped `thenRn` \ already_slurped ->
455 if name `elemNameSet` already_slurped then
456 returnRn Nothing -- Already dealt with
458 if isLocallyDefined name then -- Don't bring in decls from
459 -- the renamed module's own interface file
460 addWarnRn (importDeclWarn name) `thenRn_`
463 getNonWiredInDecl name
467 getNonWiredInDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
468 getNonWiredInDecl needed_name
469 = traceRn doc_str `thenRn_`
470 loadHomeInterface doc_str needed_name `thenRn` \ ifaces ->
471 case lookupNameEnv (iDecls ifaces) needed_name of
473 Just (version,avail,_,decl)
474 -> recordSlurp (Just version) avail `thenRn_`
477 Nothing -- Can happen legitimately for "Optional" occurrences
478 -> addErrRn (getDeclErr needed_name) `thenRn_`
481 doc_str = ptext SLIT("need decl for") <+> ppr needed_name
484 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
485 It behaves exactly as if the wired in decl were actually in an interface file.
488 \item if the wired-in name is a data type constructor or a data constructor,
489 it brings in the type constructor and all the data constructors; and
490 marks as ``occurrences'' any free vars of the data con.
492 \item similarly for synonum type constructor
494 \item if the wired-in name is another wired-in Id, it marks as ``occurrences''
495 the free vars of the Id's type.
497 \item it loads the interface file for the wired-in thing for the
498 sole purpose of making sure that its instance declarations are available
500 All this is necessary so that we know all types that are ``in play'', so
501 that we know just what instances to bring into scope.
506 %*********************************************************
508 \subsection{Getting what a module exports}
510 %*********************************************************
512 @getInterfaceExports@ is called only for directly-imported modules.
515 getInterfaceExports :: ModuleName -> WhereFrom -> RnMG (Module, Avails)
516 getInterfaceExports mod_name from
517 = loadInterface doc_str mod_name from `thenRn` \ (mod, ifaces) ->
518 case lookupFM (iImpModInfo ifaces) mod_name of
519 Nothing -> -- Not there; it must be that the interface file wasn't found;
520 -- the error will have been reported already.
521 -- (Actually loadInterface should put the empty export env in there
522 -- anyway, but this does no harm.)
525 Just (_, _, Just (mod, _, avails)) -> returnRn (mod, avails)
527 doc_str = sep [pprModuleName mod_name, ptext SLIT("is directly imported")]
531 %*********************************************************
533 \subsection{Instance declarations are handled specially}
535 %*********************************************************
538 getImportedInstDecls :: NameSet -> RnMG [(Module,RdrNameHsDecl)]
539 getImportedInstDecls gates
540 = -- First, ensure that the home module of each gate is loaded
541 mapRn_ load_home gate_list `thenRn_`
543 -- Next, load any orphan-instance modules that aren't aready loaded
544 -- Orphan-instance modules are recorded in the module dependecnies
545 getIfacesRn `thenRn` \ ifaces ->
548 [mod | (mod, (_, True, Nothing)) <- fmToList (iImpModInfo ifaces)]
550 loadOrphanModules orphan_mods `thenRn_`
552 -- Now we're ready to grab the instance declarations
553 -- Find the un-gated ones and return them,
554 -- removing them from the bag kept in Ifaces
555 getIfacesRn `thenRn` \ ifaces ->
557 (decls, new_insts) = selectGated gates (iInsts ifaces)
559 setIfacesRn (ifaces { iInsts = new_insts }) `thenRn_`
561 traceRn (sep [text "getImportedInstDecls:",
562 nest 4 (fsep (map ppr gate_list)),
563 text "Slurped" <+> int (length decls)
564 <+> text "instance declarations"]) `thenRn_`
567 gate_list = nameSetToList gates
569 load_home gate | isLocallyDefined gate
572 = loadHomeInterface (ppr gate <+> text "is an instance gate") gate `thenRn_`
575 getImportedRules :: RnMG [(Module,RdrNameHsDecl)]
577 = getIfacesRn `thenRn` \ ifaces ->
579 gates = iSlurp ifaces -- Anything at all that's been slurped
580 (decls, new_rules) = selectGated gates (iRules ifaces)
582 setIfacesRn (ifaces { iRules = new_rules }) `thenRn_`
583 traceRn (sep [text "getImportedRules:",
584 text "Slurped" <+> int (length decls) <+> text "rules"]) `thenRn_`
587 selectGated gates decl_bag
588 -- Select only those decls whose gates are *all* in 'gates'
590 | opt_NoPruneDecls -- Just to try the effect of not gating at all
591 = (foldrBag (\ (_,d) ds -> d:ds) [] decl_bag, emptyBag) -- Grab them all
595 = foldrBag select ([], emptyBag) decl_bag
597 select (reqd, decl) (yes, no)
598 | isEmptyNameSet (reqd `minusNameSet` gates) = (decl:yes, no)
599 | otherwise = (yes, (reqd,decl) `consBag` no)
601 lookupFixity :: Name -> RnMS Fixity
603 | isLocallyDefined name
604 = getFixityEnv `thenRn` \ local_fix_env ->
605 case lookupNameEnv local_fix_env name of
606 Just (FixitySig _ fix _) -> returnRn fix
607 Nothing -> returnRn defaultFixity
609 | otherwise -- Imported
610 = loadHomeInterface doc name `thenRn` \ ifaces ->
611 case lookupNameEnv (iFixes ifaces) name of
612 Just (FixitySig _ fix _) -> returnRn fix
613 Nothing -> returnRn defaultFixity
615 doc = ptext SLIT("Checking fixity for") <+> ppr name
619 %*********************************************************
621 \subsection{Keeping track of what we've slurped, and version numbers}
623 %*********************************************************
625 getImportVersions figures out
626 what the ``usage information'' for this moudule is;
627 that is, what it must record in its interface file as the things it uses.
630 \item anything reachable from its body code
631 \item any module exported with a @module Foo@.
634 Why the latter? Because if @Foo@ changes then this module's export list
635 will change, so we must recompile this module at least as far as
636 making a new interface file --- but in practice that means complete
641 module A( f, g ) where | module B( f ) where
642 import B( f ) | f = h 3
645 Should we record @B.f@ in @A@'s usages? In fact we don't. Certainly, if
646 anything about @B.f@ changes than anyone who imports @A@ should be recompiled;
647 they'll get an early exit if they don't use @B.f@. However, even if @B.f@
648 doesn't change at all, @B.h@ may do so, and this change may not be reflected
649 in @f@'s version number. So there are two things going on when compiling module @A@:
651 \item Are @A.o@ and @A.hi@ correct? Then we can bale out early.
652 \item Should modules that import @A@ be recompiled?
654 For (1) it is slightly harmful to record @B.f@ in @A@'s usages,
655 because a change in @B.f@'s version will provoke full recompilation of @A@,
656 producing an identical @A.o@,
657 and @A.hi@ differing only in its usage-version of @B.f@
658 (which isn't used by any importer).
660 For (2), because of the tricky @B.h@ question above,
661 we ensure that @A.hi@ is touched
662 (even if identical to its previous version)
663 if A's recompilation was triggered by an imported @.hi@ file date change.
664 Given that, there's no need to record @B.f@ in @A@'s usages.
666 On the other hand, if @A@ exports @module B@,
667 then we {\em do} count @module B@ among @A@'s usages,
668 because we must recompile @A@ to ensure that @A.hi@ changes appropriately.
671 getImportVersions :: ModuleName -- Name of this module
672 -> Maybe [IE any] -- Export list for this module
673 -> RnMG (VersionInfo Name) -- Version info for these names
675 getImportVersions this_mod exports
676 = getIfacesRn `thenRn` \ ifaces ->
678 mod_map = iImpModInfo ifaces
679 imp_names = iVSlurp ifaces
681 -- mv_map groups together all the things imported from a particular module.
682 mv_map1, mv_map2 :: FiniteMap ModuleName (WhatsImported Name)
684 -- mv_map1 records all the modules that have a "module M"
685 -- in this module's export list with an "Everything"
686 mv_map1 = foldr add_mod emptyFM export_mods
688 -- mv_map2 adds the version numbers of things exported individually
689 mv_map2 = foldr add_mv mv_map1 imp_names
691 -- Build the result list by adding info for each module,
692 -- *omitting* (a) library modules
693 -- (b) source-imported modules
694 mk_version_info mod_name (version, has_orphans, cts) so_far
695 | omit cts = so_far -- Don't record usage info for this module
696 | otherwise = (mod_name, version, has_orphans, whats_imported) : so_far
698 whats_imported = case lookupFM mv_map2 mod_name of
700 Nothing -> Specifically []
702 omit (Just (mod, boot_import, _)) = isLibModule mod || boot_import
705 returnRn (foldFM mk_version_info [] mod_map)
707 export_mods = case exports of
709 Just es -> [mod | IEModuleContents mod <- es, mod /= this_mod]
711 add_mv v@(name, version) mv_map
712 = addToFM_C add_item mv_map mod (Specifically [v])
714 mod = moduleName (nameModule name)
716 add_item Everything _ = Everything
717 add_item (Specifically xs) _ = Specifically (v:xs)
719 add_mod mod mv_map = addToFM mv_map mod Everything
724 = getIfacesRn `thenRn` \ ifaces ->
725 returnRn (iSlurp ifaces)
727 recordSlurp maybe_version avail
728 = getIfacesRn `thenRn` \ ifaces@(Ifaces { iSlurp = slurped_names,
729 iVSlurp = imp_names }) ->
731 new_slurped_names = addAvailToNameSet slurped_names avail
733 new_imp_names = case maybe_version of
734 Just version -> (availName avail, version) : imp_names
737 setIfacesRn (ifaces { iSlurp = new_slurped_names,
738 iVSlurp = new_imp_names })
742 %*********************************************************
744 \subsection{Getting binders out of a declaration}
746 %*********************************************************
748 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
749 It's used for both source code (from @availsFromDecl@) and interface files
752 It doesn't deal with source-code specific things: @ValD@, @DefD@. They
753 are handled by the sourc-code specific stuff in @RnNames@.
756 getDeclBinders :: (RdrName -> SrcLoc -> RnM d Name) -- New-name function
758 -> RnM d (Maybe AvailInfo)
760 getDeclBinders new_name (TyClD (TyData _ _ tycon _ condecls _ _ src_loc))
761 = new_name tycon src_loc `thenRn` \ tycon_name ->
762 getConFieldNames new_name condecls `thenRn` \ sub_names ->
763 returnRn (Just (AvailTC tycon_name (tycon_name : nub sub_names)))
764 -- The "nub" is because getConFieldNames can legitimately return duplicates,
765 -- when a record declaration has the same field in multiple constructors
767 getDeclBinders new_name (TyClD (TySynonym tycon _ _ src_loc))
768 = new_name tycon src_loc `thenRn` \ tycon_name ->
769 returnRn (Just (AvailTC tycon_name [tycon_name]))
771 getDeclBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ _ _ _ src_loc))
772 = new_name cname src_loc `thenRn` \ class_name ->
774 -- Record the names for the class ops
776 -- just want class-op sigs
777 op_sigs = filter isClassOpSig sigs
779 mapRn (getClassOpNames new_name) op_sigs `thenRn` \ sub_names ->
781 returnRn (Just (AvailTC class_name (class_name : sub_names)))
783 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
784 = new_name var src_loc `thenRn` \ var_name ->
785 returnRn (Just (Avail var_name))
787 getDeclBinders new_name (FixD _) = returnRn Nothing
788 getDeclBinders new_name (ForD _) = returnRn Nothing
789 getDeclBinders new_name (DefD _) = returnRn Nothing
790 getDeclBinders new_name (InstD _) = returnRn Nothing
791 getDeclBinders new_name (RuleD _) = returnRn Nothing
794 getConFieldNames new_name (ConDecl con _ _ (RecCon fielddecls) src_loc : rest)
795 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
796 getConFieldNames new_name rest `thenRn` \ ns ->
799 fields = concat (map fst fielddecls)
801 getConFieldNames new_name (ConDecl con _ _ condecl src_loc : rest)
802 = new_name con src_loc `thenRn` \ n ->
805 new_name f src_loc `thenRn` \ new_f ->
807 _ -> returnRn [n]) `thenRn` \ nn ->
808 getConFieldNames new_name rest `thenRn` \ ns ->
811 getConFieldNames new_name [] = returnRn []
813 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
816 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
817 A the moment that's just the tycon and datacon that come with a class decl.
818 They aren't returned by @getDeclBinders@ because they aren't in scope;
819 but they {\em should} be put into the @DeclsMap@ of this module.
821 Note that this excludes the default-method names of a class decl,
822 and the dict fun of an instance decl, because both of these have
823 bindings of their own elsewhere.
826 getDeclSysBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ tname dname snames src_loc))
827 = new_name dname src_loc `thenRn` \ datacon_name ->
828 new_name tname src_loc `thenRn` \ tycon_name ->
829 sequenceRn [new_name n src_loc | n <- snames] `thenRn` \ scsel_names ->
830 returnRn (tycon_name : datacon_name : scsel_names)
832 getDeclSysBinders new_name other_decl
836 %*********************************************************
838 \subsection{Reading an interface file}
840 %*********************************************************
843 findAndReadIface :: SDoc -> ModuleName -> WhereFrom
844 -> Bool -- Only relevant for SystemImport
845 -- True <=> Look for a .hi file
846 -- False <=> Look for .hi-boot file unless there's
847 -- a library .hi file
848 -> RnM d (Bool, Maybe (Module, ParsedIface))
849 -- Bool is True if the interface actually read was a .hi-boot one
850 -- Nothing <=> file not found, or unreadable, or illegible
851 -- Just x <=> successfully found and parsed
853 findAndReadIface doc_str mod_name from hi_file
854 = traceRn trace_msg `thenRn_`
855 -- we keep two maps for interface files,
856 -- one for 'normal' ones, the other for .hi-boot files,
857 -- hence the need to signal which kind we're interested.
859 getHiMaps `thenRn` \ hi_maps ->
861 case find_path from hi_maps of
863 (hi_boot, Just (fpath, mod)) -> traceRn (ptext SLIT("...reading from") <+> text fpath)
865 readIface mod fpath `thenRn` \ result ->
866 returnRn (hi_boot, result)
867 (hi_boot, Nothing) -> traceRn (ptext SLIT("...not found")) `thenRn_`
868 returnRn (hi_boot, Nothing)
870 find_path ImportByUser (hi_map, _) = (False, lookupFM hi_map mod_name)
871 find_path ImportByUserSource (_, hiboot_map) = (True, lookupFM hiboot_map mod_name)
873 find_path ImportBySystem (hi_map, hiboot_map)
875 = -- If the module we seek is in our dependent set,
876 -- Look for a .hi file
877 (False, lookupFM hi_map mod_name)
880 -- Check if there's a library module of that name
881 -- If not, look for an hi-boot file
882 = case lookupFM hi_map mod_name of
883 stuff@(Just (_, mod)) | isLibModule mod -> (False, stuff)
884 other -> (True, lookupFM hiboot_map mod_name)
886 trace_msg = sep [hsep [ptext SLIT("Reading"),
888 ptext SLIT("interface for"),
889 pprModuleName mod_name <> semi],
890 nest 4 (ptext SLIT("reason:") <+> doc_str)]
893 @readIface@ tries just the one file.
896 readIface :: Module -> String -> RnM d (Maybe (Module, ParsedIface))
897 -- Nothing <=> file not found, or unreadable, or illegible
898 -- Just x <=> successfully found and parsed
899 readIface the_mod file_path
900 = ioToRnM (hGetStringBuffer False file_path) `thenRn` \ read_result ->
903 case parseIface contents
904 PState{ bol = 0#, atbol = 1#,
907 loc = mkSrcLoc (mkFastString file_path) 1 } of
908 PFailed err -> failWithRn Nothing err
909 POk _ (PIface mod_nm iface) ->
910 warnCheckRn (mod_nm == moduleName the_mod)
911 (hsep [ ptext SLIT("Something is amiss; requested module name")
913 , ptext SLIT("differs from name found in the interface file ")
914 , pprModuleName mod_nm
916 `thenRn_` returnRn (Just (the_mod, iface))
919 | isDoesNotExistError err -> returnRn Nothing
920 | otherwise -> failWithRn Nothing (cannaeReadFile file_path err)
923 %*********************************************************
927 %*********************************************************
930 noIfaceErr filename boot_file
931 = hsep [ptext SLIT("Could not find valid"), boot,
932 ptext SLIT("interface file"), quotes (pprModule filename)]
934 boot | boot_file = ptext SLIT("[boot]")
937 cannaeReadFile file err
938 = hcat [ptext SLIT("Failed in reading file: "),
940 ptext SLIT("; error="),
944 = ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name)
947 = sep [ptext SLIT("Failed to find (optional) interface decl for") <+> quotes (ppr name),
948 ptext SLIT("desired at") <+> ppr loc]
952 "Compiler tried to import decl from interface file with same name as module."),
954 "(possible cause: module name clashes with interface file already in scope.)")
956 hsep [ptext SLIT("name:"), quotes (ppr name)]
958 warnRedundantSourceImport mod_name
959 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
960 <+> quotes (pprModuleName mod_name)