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 ForeignDecl(..), ForKind(..), isDynamicExtName,
26 FixitySig(..), RuleDecl(..),
27 isClassOpSig, Deprecation(..)
29 import BasicTypes ( Version, NewOrData(..), defaultFixity )
30 import RdrHsSyn ( RdrNameHsDecl, RdrNameInstDecl, RdrNameTyClDecl, RdrNameRuleDecl,
31 extractHsTyRdrNames, RdrNameDeprecation
33 import RnEnv ( mkImportedGlobalName, newImportedBinder, mkImportedGlobalFromRdrName,
34 lookupOccRn, lookupImplicitOccRn,
36 availName, availNames, addAvailToNameSet, addSysAvails,
40 import RnHsSyn ( RenamedHsDecl, RenamedDeprecation )
41 import ParseIface ( parseIface, IfaceStuff(..) )
43 import FiniteMap ( FiniteMap, sizeFM, emptyFM, delFromFM, listToFM,
44 lookupFM, addToFM, addToFM_C, addListToFM,
45 fmToList, elemFM, foldFM
47 import Name ( Name {-instance NamedThing-},
48 nameModule, isLocallyDefined,
49 isWiredInName, nameUnique, NamedThing(..)
51 import Module ( Module, moduleString, pprModule,
52 mkVanillaModule, pprModuleName,
53 moduleUserString, moduleName, isLocalModule,
54 ModuleName, WhereFrom(..),
56 import RdrName ( RdrName, rdrNameOcc )
59 import SrcLoc ( mkSrcLoc, SrcLoc )
60 import PrelMods ( pREL_GHC )
61 import PrelInfo ( cCallishTyKeys )
63 import Maybes ( MaybeErr(..), maybeToBool, orElse )
64 import ListSetOps ( unionLists )
66 import Unique ( Unique )
67 import StringBuffer ( StringBuffer, hGetStringBuffer )
68 import FastString ( mkFastString )
69 import ErrUtils ( Message )
73 import IO ( isDoesNotExistError )
78 %*********************************************************
80 \subsection{Loading a new interface file}
82 %*********************************************************
85 loadHomeInterface :: SDoc -> Name -> RnM d Ifaces
86 loadHomeInterface doc_str name
87 = loadInterface doc_str (moduleName (nameModule name)) ImportBySystem
89 loadOrphanModules :: [ModuleName] -> RnM d ()
90 loadOrphanModules mods
91 | null mods = returnRn ()
92 | otherwise = traceRn (text "Loading orphan modules:" <+>
93 fsep (map pprModuleName mods)) `thenRn_`
94 mapRn_ load mods `thenRn_`
97 load mod = loadInterface (mk_doc mod) mod ImportBySystem
98 mk_doc mod = pprModuleName mod <+> ptext SLIT("is a orphan-instance module")
101 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d Ifaces
102 loadInterface doc mod from
103 = tryLoadInterface doc mod from `thenRn` \ (ifaces, maybe_err) ->
105 Nothing -> returnRn ifaces
106 Just err -> failWithRn ifaces err
108 tryLoadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (Ifaces, Maybe Message)
109 -- Returns (Just err) if an error happened
110 -- Guarantees to return with iImpModInfo m --> (... Just cts)
111 -- (If the load fails, we plug in a vanilla placeholder
112 tryLoadInterface doc_str mod_name from
113 = getIfacesRn `thenRn` \ ifaces ->
115 mod_map = iImpModInfo ifaces
116 mod_info = lookupFM mod_map mod_name
118 hi_boot_file = case from of {
119 ImportByUser -> False ; -- Not hi-boot
120 ImportByUserSource -> True ; -- hi-boot
123 Just (_, _, is_boot, _) -> is_boot
126 -- We're importing a module we know absolutely
127 -- nothing about, so we assume it's from
128 -- another package, where we aren't doing
129 -- dependency tracking. So it won't be a hi-boot file.
131 redundant_source_import
132 = case (from, mod_info) of
133 (ImportByUserSource, Just (_,_,False,_)) -> True
136 -- CHECK WHETHER WE HAVE IT ALREADY
138 Just (_, _, _, Just _)
139 -> -- We're read it already so don't re-read it
140 returnRn (ifaces, Nothing) ;
144 -- Issue a warning for a redundant {- SOURCE -} import
145 -- NB that we arrange to read all the ordinary imports before
146 -- any of the {- SOURCE -} imports
147 warnCheckRn (not redundant_source_import)
148 (warnRedundantSourceImport mod_name) `thenRn_`
150 -- READ THE MODULE IN
151 findAndReadIface doc_str mod_name hi_boot_file `thenRn` \ read_result ->
152 case read_result of {
153 Left err -> -- Not found, so add an empty export env to the Ifaces map
154 -- so that we don't look again
156 mod = mkVanillaModule mod_name
157 new_mod_map = addToFM mod_map mod_name (0, False, False, Just (mod, from, []))
158 new_ifaces = ifaces { iImpModInfo = new_mod_map }
160 setIfacesRn new_ifaces `thenRn_`
161 returnRn (new_ifaces, Just err) ;
166 -- LOAD IT INTO Ifaces
168 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
169 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
170 -- If we do loadExport first the wrong info gets into the cache (unless we
171 -- explicitly tag each export which seems a bit of a bore)
173 getModuleRn `thenRn` \ this_mod_nm ->
175 rd_decls = pi_decls iface
178 -- Sanity check. If we're system-importing a module we know nothing at all
179 -- about, it should be from a different package to this one
180 WARN( not (maybeToBool mod_info) &&
181 case from of { ImportBySystem -> True; other -> False } &&
184 foldlRn (loadDecl mod) (iDecls ifaces) rd_decls `thenRn` \ new_decls ->
185 foldlRn (loadInstDecl mod) (iInsts ifaces) (pi_insts iface) `thenRn` \ new_insts ->
186 (if opt_IgnoreIfacePragmas
187 then returnRn emptyBag
188 else foldlRn (loadRule mod) (iRules ifaces) (pi_rules iface)) `thenRn` \ new_rules ->
189 (if opt_IgnoreIfacePragmas
190 then returnRn emptyNameEnv
191 else foldlRn (loadDeprec mod) (iDeprecs ifaces) (pi_deprecs iface)) `thenRn` \ new_deprecs ->
192 foldlRn (loadFixDecl mod_name) (iFixes ifaces) rd_decls `thenRn` \ new_fixities ->
193 mapRn (loadExport this_mod_nm) (pi_exports iface) `thenRn` \ avails_s ->
195 -- For an explicit user import, add to mod_map info about
196 -- the things the imported module depends on, extracted
197 -- from its usage info.
198 mod_map1 = case from of
199 ImportByUser -> addModDeps mod (pi_usages iface) mod_map
202 -- Now add info about this module
203 mod_map2 = addToFM mod_map1 mod_name mod_details
204 cts = (pi_mod iface, from, concat avails_s)
205 mod_details = (pi_vers iface, pi_orphan iface, hi_boot_file, Just cts)
207 new_ifaces = ifaces { iImpModInfo = mod_map2,
209 iFixes = new_fixities,
212 iDeprecs = new_deprecs }
214 setIfacesRn new_ifaces `thenRn_`
215 returnRn (new_ifaces, Nothing)
218 addModDeps :: Module -> [ImportVersion a]
219 -> ImportedModuleInfo -> ImportedModuleInfo
220 -- (addModDeps M ivs deps)
221 -- We are importing module M, and M.hi contains 'import' decls given by ivs
222 addModDeps mod new_deps mod_deps
223 = foldr add mod_deps filtered_new_deps
225 -- Don't record dependencies when importing a module from another package
226 -- Except for its descendents which contain orphans,
227 -- and in that case, forget about the boot indicator
229 | isLocalModule mod = [ (imp_mod, (version, has_orphans, is_boot, Nothing))
230 | (imp_mod, version, has_orphans, is_boot, _) <- new_deps
232 | otherwise = [ (imp_mod, (version, True, False, Nothing))
233 | (imp_mod, version, has_orphans, _, _) <- new_deps,
236 add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
238 combine old@(_, _, old_is_boot, cts) new
239 | maybeToBool cts || not old_is_boot = old -- Keep the old info if it's already loaded
240 -- or if it's a non-boot pending load
241 | otherwise = new -- Otherwise pick new info
243 loadExport :: ModuleName -> ExportItem -> RnM d [AvailInfo]
244 loadExport this_mod (mod, entities)
245 | mod == this_mod = returnRn []
246 -- If the module exports anything defined in this module, just ignore it.
247 -- Reason: otherwise it looks as if there are two local definition sites
248 -- for the thing, and an error gets reported. Easiest thing is just to
249 -- filter them out up front. This situation only arises if a module
250 -- imports itself, or another module that imported it. (Necessarily,
251 -- this invoves a loop.) Consequence: if you say
256 -- module B( AType ) where
257 -- import {-# SOURCE #-} A( AType )
259 -- then you'll get a 'B does not export AType' message. A bit bogus
260 -- but it's a bogus thing to do!
263 = mapRn (load_entity mod) entities
265 new_name mod occ = mkImportedGlobalName mod occ
267 load_entity mod (Avail occ)
268 = new_name mod occ `thenRn` \ name ->
269 returnRn (Avail name)
270 load_entity mod (AvailTC occ occs)
271 = new_name mod occ `thenRn` \ name ->
272 mapRn (new_name mod) occs `thenRn` \ names ->
273 returnRn (AvailTC name names)
276 loadFixDecl :: ModuleName -> FixityEnv
277 -> (Version, RdrNameHsDecl)
279 loadFixDecl mod_name fixity_env (version, FixD sig@(FixitySig rdr_name fixity loc))
280 = -- Ignore the version; when the fixity changes the version of
281 -- its 'host' entity changes, so we don't need a separate version
282 -- number for fixities
283 mkImportedGlobalName mod_name (rdrNameOcc rdr_name) `thenRn` \ name ->
285 new_fixity_env = addToNameEnv fixity_env name (FixitySig name fixity loc)
287 returnRn new_fixity_env
289 -- Ignore the other sorts of decl
290 loadFixDecl mod_name fixity_env other_decl = returnRn fixity_env
294 -> (Version, RdrNameHsDecl)
297 loadDecl mod decls_map (version, decl)
298 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
299 case maybe_avail of {
300 Nothing -> returnRn decls_map; -- No bindings
303 getDeclSysBinders new_name decl `thenRn` \ sys_bndrs ->
305 full_avail = addSysAvails avail sys_bndrs
306 -- Add the sys-binders to avail. When we import the decl,
307 -- it's full_avail that will get added to the 'already-slurped' set (iSlurp)
308 -- If we miss out sys-binders, we'll read the decl multiple times!
310 main_name = availName avail
311 new_decls_map = foldl add_decl decls_map
312 [ (name, (version, full_avail, name==main_name, (mod, decl')))
313 | name <- availNames full_avail]
314 add_decl decls_map (name, stuff)
315 = WARN( name `elemNameEnv` decls_map, ppr name )
316 addToNameEnv decls_map name stuff
318 returnRn new_decls_map
321 -- newImportedBinder puts into the cache the binder with the
322 -- module information set correctly. When the decl is later renamed,
323 -- the binding site will thereby get the correct module.
324 new_name rdr_name loc = newImportedBinder mod rdr_name
327 If a signature decl is being loaded, and optIgnoreIfacePragmas is on,
328 we toss away unfolding information.
330 Also, if the signature is loaded from a module we're importing from source,
331 we do the same. This is to avoid situations when compiling a pair of mutually
332 recursive modules, peering at unfolding info in the interface file of the other,
333 e.g., you compile A, it looks at B's interface file and may as a result change
334 its interface file. Hence, B is recompiled, maybe changing its interface file,
335 which will the unfolding info used in A to become invalid. Simple way out is to
336 just ignore unfolding info.
338 [Jan 99: I junked the second test above. If we're importing from an hi-boot
339 file there isn't going to *be* any pragma info. Maybe the above comment
340 dates from a time where we picked up a .hi file first if it existed?]
343 SigD (IfaceSig name tp ls loc) | opt_IgnoreIfacePragmas
344 -> SigD (IfaceSig name tp [] loc)
347 loadInstDecl :: Module
350 -> RnM d (Bag GatedDecl)
351 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
353 -- Find out what type constructors and classes are "gates" for the
354 -- instance declaration. If all these "gates" are slurped in then
355 -- we should slurp the instance decl too.
357 -- We *don't* want to count names in the context part as gates, though.
359 -- instance Foo a => Baz (T a) where ...
361 -- Here the gates are Baz and T, but *not* Foo.
363 munged_inst_ty = removeContext inst_ty
364 free_names = extractHsTyRdrNames munged_inst_ty
366 setModuleRn (moduleName mod) $
367 mapRn mkImportedGlobalFromRdrName free_names `thenRn` \ gate_names ->
368 returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
371 -- In interface files, the instance decls now look like
372 -- forall a. Foo a -> Baz (T a)
373 -- so we have to strip off function argument types as well
374 -- as the bit before the '=>' (which is always empty in interface files)
375 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
376 removeContext ty = removeFuns ty
378 removeFuns (MonoFunTy _ ty) = removeFuns ty
382 loadRule :: Module -> Bag GatedDecl
383 -> RdrNameRuleDecl -> RnM d (Bag GatedDecl)
384 -- "Gate" the rule simply by whether the rule variable is
385 -- needed. We can refine this later.
386 loadRule mod rules decl@(IfaceRuleDecl var body src_loc)
387 = setModuleRn (moduleName mod) $
388 mkImportedGlobalFromRdrName var `thenRn` \ var_name ->
389 returnRn ((unitNameSet var_name, (mod, RuleD decl)) `consBag` rules)
391 -- SUP: TEMPORARY HACK, ignoring module deprecations for now
392 loadDeprec :: Module -> DeprecationEnv -> RdrNameDeprecation -> RnM d DeprecationEnv
393 loadDeprec mod deprec_env (Deprecation (IEModuleContents _) txt)
394 = traceRn (text "module deprecation not yet implemented:" <+> ppr mod <> colon <+> ppr txt) `thenRn_`
396 loadDeprec mod deprec_env (Deprecation ie txt)
397 = setModuleRn (moduleName mod) $
398 mapRn mkImportedGlobalFromRdrName (namesFromIE ie) `thenRn` \ names ->
399 traceRn (text "loaded deprecation(s) for" <+> hcat (punctuate comma (map ppr names)) <> colon <+> ppr txt) `thenRn_`
400 returnRn (extendNameEnv deprec_env (zip names (repeat txt)))
402 namesFromIE :: IE a -> [a]
403 namesFromIE (IEVar n ) = [n]
404 namesFromIE (IEThingAbs n ) = [n]
405 namesFromIE (IEThingAll n ) = [n]
406 namesFromIE (IEThingWith n ns) = n:ns
407 namesFromIE (IEModuleContents _ ) = []
411 %********************************************************
413 \subsection{Loading usage information}
415 %********************************************************
421 checkUpToDate :: ModuleName -> RnMG Bool -- True <=> no need to recompile
422 -- When this guy is called, we already know that the
423 -- source code is unchanged from last time
424 checkUpToDate mod_name
425 = getIfacesRn `thenRn` \ ifaces ->
426 findAndReadIface doc_str mod_name
427 False {- Not hi-boot -} `thenRn` \ read_result ->
429 -- CHECK WHETHER WE HAVE IT ALREADY
431 Left err -> -- Old interface file not found, or garbled, so we'd better bail out
432 traceRn (vcat [ptext SLIT("No old iface") <+> pprModuleName mod_name,
437 -> -- Found it, so now check it
438 checkModUsage (pi_usages iface)
440 -- Only look in current directory, with suffix .hi
441 doc_str = sep [ptext SLIT("need usage info from"), pprModuleName mod_name]
443 checkModUsage [] = returnRn upToDate -- Yes! Everything is up to date!
445 checkModUsage ((mod_name, old_mod_vers, _, _, Specifically []) : rest)
446 -- If CurrentModule.hi contains
448 -- then that simply records that Foo lies below CurrentModule in the
449 -- hierarchy, but CurrentModule doesn't depend in any way on Foo.
450 -- In this case we don't even want to open Foo's interface.
451 = traceRn (ptext SLIT("Nothing used from:") <+> ppr mod_name) `thenRn_`
452 checkModUsage rest -- This one's ok, so check the rest
454 checkModUsage ((mod_name, old_mod_vers, _, _, whats_imported) : rest)
455 = tryLoadInterface doc_str mod_name ImportBySystem `thenRn` \ (ifaces, maybe_err) ->
457 Just err -> traceRn (sep [ptext SLIT("Can't find version number for module"),
458 pprModuleName mod_name]) `thenRn_`
460 -- Couldn't find or parse a module mentioned in the
461 -- old interface file. Don't complain -- it might just be that
462 -- the current module doesn't need that import and it's been deleted
465 new_mod_vers = case lookupFM (iImpModInfo ifaces) mod_name of
466 Just (version, _, _, _) -> version
468 -- If the module version hasn't changed, just move on
469 if new_mod_vers == old_mod_vers then
470 traceRn (sep [ptext SLIT("Module version unchanged:"), pprModuleName mod_name])
471 `thenRn_` checkModUsage rest
473 traceRn (sep [ptext SLIT("Module version has changed:"), pprModuleName mod_name])
475 -- Module version changed, so check entities inside
477 -- If the usage info wants to say "I imported everything from this module"
478 -- it does so by making whats_imported equal to Everything
479 -- In that case, we must recompile
480 case whats_imported of {
481 Everything -> traceRn (ptext SLIT("...and I needed the whole module")) `thenRn_`
482 returnRn outOfDate; -- Bale out
484 Specifically old_local_vers ->
486 -- Non-empty usage list, so check item by item
487 checkEntityUsage mod_name (iDecls ifaces) old_local_vers `thenRn` \ up_to_date ->
489 traceRn (ptext SLIT("...but the bits I use haven't.")) `thenRn_`
490 checkModUsage rest -- This one's ok, so check the rest
492 returnRn outOfDate -- This one failed, so just bail out now
495 doc_str = sep [ptext SLIT("need version info for"), pprModuleName mod_name]
498 checkEntityUsage mod decls []
499 = returnRn upToDate -- Yes! All up to date!
501 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
502 = mkImportedGlobalName mod occ_name `thenRn` \ name ->
503 case lookupNameEnv decls name of
505 Nothing -> -- We used it before, but it ain't there now
506 traceRn (sep [ptext SLIT("No longer exported:"), ppr name])
507 `thenRn_` returnRn outOfDate
509 Just (new_vers,_,_,_) -- It's there, but is it up to date?
510 | new_vers == old_vers
511 -- Up to date, so check the rest
512 -> checkEntityUsage mod decls rest
515 -- Out of date, so bale out
516 -> traceRn (sep [ptext SLIT("Out of date:"), ppr name]) `thenRn_`
521 %*********************************************************
523 \subsection{Getting in a declaration}
525 %*********************************************************
528 importDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
529 -- Returns Nothing for
532 -- (c) already slurped
538 = getSlurped `thenRn` \ already_slurped ->
539 if name `elemNameSet` already_slurped then
540 returnRn Nothing -- Already dealt with
542 if isLocallyDefined name then -- Don't bring in decls from
543 -- the renamed module's own interface file
544 addWarnRn (importDeclWarn name) `thenRn_`
547 getNonWiredInDecl name
551 getNonWiredInDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
552 getNonWiredInDecl needed_name
553 = traceRn doc_str `thenRn_`
554 loadHomeInterface doc_str needed_name `thenRn` \ ifaces ->
555 case lookupNameEnv (iDecls ifaces) needed_name of
557 Just (version,avail,_,decl)
558 -> recordSlurp (Just version) avail `thenRn_`
561 Nothing -- Can happen legitimately for "Optional" occurrences
562 -> addErrRn (getDeclErr needed_name) `thenRn_`
565 doc_str = ptext SLIT("need decl for") <+> ppr needed_name
568 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
569 It behaves exactly as if the wired in decl were actually in an interface file.
572 \item if the wired-in name is a data type constructor or a data constructor,
573 it brings in the type constructor and all the data constructors; and
574 marks as ``occurrences'' any free vars of the data con.
576 \item similarly for synonum type constructor
578 \item if the wired-in name is another wired-in Id, it marks as ``occurrences''
579 the free vars of the Id's type.
581 \item it loads the interface file for the wired-in thing for the
582 sole purpose of making sure that its instance declarations are available
584 All this is necessary so that we know all types that are ``in play'', so
585 that we know just what instances to bring into scope.
590 %*********************************************************
592 \subsection{Getting what a module exports}
594 %*********************************************************
596 @getInterfaceExports@ is called only for directly-imported modules.
599 getInterfaceExports :: ModuleName -> WhereFrom -> RnMG (Module, Avails)
600 getInterfaceExports mod_name from
601 = loadInterface doc_str mod_name from `thenRn` \ ifaces ->
602 case lookupFM (iImpModInfo ifaces) mod_name of
603 Just (_, _, _, Just (mod, _, avails)) -> returnRn (mod, avails)
604 -- loadInterface always puts something in the map
605 -- even if it's a fake
607 doc_str = sep [pprModuleName mod_name, ptext SLIT("is directly imported")]
611 %*********************************************************
613 \subsection{Instance declarations are handled specially}
615 %*********************************************************
618 getImportedInstDecls :: NameSet -> RnMG [(Module,RdrNameHsDecl)]
619 getImportedInstDecls gates
620 = -- First, load any orphan-instance modules that aren't aready loaded
621 -- Orphan-instance modules are recorded in the module dependecnies
622 getIfacesRn `thenRn` \ ifaces ->
625 [mod | (mod, (_, True, _, Nothing)) <- fmToList (iImpModInfo ifaces)]
627 loadOrphanModules orphan_mods `thenRn_`
629 -- Now we're ready to grab the instance declarations
630 -- Find the un-gated ones and return them,
631 -- removing them from the bag kept in Ifaces
632 getIfacesRn `thenRn` \ ifaces ->
634 (decls, new_insts) = selectGated gates (iInsts ifaces)
636 setIfacesRn (ifaces { iInsts = new_insts }) `thenRn_`
638 traceRn (sep [text "getImportedInstDecls:",
639 nest 4 (fsep (map ppr gate_list)),
640 text "Slurped" <+> int (length decls) <+> text "instance declarations",
641 nest 4 (vcat (map ppr_brief_inst_decl decls))]) `thenRn_`
644 gate_list = nameSetToList gates
646 ppr_brief_inst_decl (mod, InstD (InstDecl inst_ty _ _ _ _))
648 HsForAllTy _ _ tau -> ppr tau
651 getImportedRules :: RnMG [(Module,RdrNameHsDecl)]
653 | opt_IgnoreIfacePragmas = returnRn []
655 = getIfacesRn `thenRn` \ ifaces ->
657 gates = iSlurp ifaces -- Anything at all that's been slurped
658 (decls, new_rules) = selectGated gates (iRules ifaces)
660 setIfacesRn (ifaces { iRules = new_rules }) `thenRn_`
661 traceRn (sep [text "getImportedRules:",
662 text "Slurped" <+> int (length decls) <+> text "rules"]) `thenRn_`
665 selectGated gates decl_bag
666 -- Select only those decls whose gates are *all* in 'gates'
668 | opt_NoPruneDecls -- Just to try the effect of not gating at all
669 = (foldrBag (\ (_,d) ds -> d:ds) [] decl_bag, emptyBag) -- Grab them all
673 = foldrBag select ([], emptyBag) decl_bag
675 select (reqd, decl) (yes, no)
676 | isEmptyNameSet (reqd `minusNameSet` gates) = (decl:yes, no)
677 | otherwise = (yes, (reqd,decl) `consBag` no)
679 lookupFixity :: Name -> RnMS Fixity
681 | isLocallyDefined name
682 = getFixityEnv `thenRn` \ local_fix_env ->
683 case lookupNameEnv local_fix_env name of
684 Just (FixitySig _ fix _) -> returnRn fix
685 Nothing -> returnRn defaultFixity
687 | otherwise -- Imported
688 -- For imported names, we have to get their fixities by doing a loadHomeInterface,
689 -- and consulting the Ifaces that comes back from that, because the interface
690 -- file for the Name might not have been loaded yet. Why not? Suppose you import module A,
691 -- which exports a function 'f', which is defined in module B. Then B isn't loaded
692 -- right away (after all, it's possible that nothing from B will be used).
693 -- When we come across a use of 'f', we need to know its fixity, and it's then,
694 -- and only then, that we load B.hi. That is what's happening here.
695 = loadHomeInterface doc name `thenRn` \ ifaces ->
696 case lookupNameEnv (iFixes ifaces) name of
697 Just (FixitySig _ fix _) -> returnRn fix
698 Nothing -> returnRn defaultFixity
700 doc = ptext SLIT("Checking fixity for") <+> ppr name
704 %*********************************************************
706 \subsection{Keeping track of what we've slurped, and version numbers}
708 %*********************************************************
710 getImportVersions figures out what the ``usage information'' for this
711 moudule is; that is, what it must record in its interface file as the
712 things it uses. It records:
715 \item (a) anything reachable from its body code
716 \item (b) any module exported with a @module Foo@
717 \item (c) anything reachable from an exported item
720 Why (b)? Because if @Foo@ changes then this module's export list
721 will change, so we must recompile this module at least as far as
722 making a new interface file --- but in practice that means complete
725 Why (c)? Consider this:
727 module A( f, g ) where | module B( f ) where
728 import B( f ) | f = h 3
732 Here, @B.f@ isn't used in A. Should we nevertheless record @B.f@ in
733 @A@'s usages? Our idea is that we aren't going to touch A.hi if it is
734 *identical* to what it was before. If anything about @B.f@ changes
735 than anyone who imports @A@ should be recompiled in case they use
736 @B.f@ (they'll get an early exit if they don't). So, if anything
737 about @B.f@ changes we'd better make sure that something in A.hi
738 changes, and the convenient way to do that is to record the version
739 number @B.f@ in A.hi in the usage list. If B.f changes that'll force a
740 complete recompiation of A, which is overkill but it's the only way to
741 write a new, slightly different, A.hi.
743 But the example is tricker. Even if @B.f@ doesn't change at all,
744 @B.h@ may do so, and this change may not be reflected in @f@'s version
745 number. But with -O, a module that imports A must be recompiled if
746 @B.h@ changes! So A must record a dependency on @B.h@. So we treat
747 the occurrence of @B.f@ in the export list *just as if* it were in the
748 code of A, and thereby haul in all the stuff reachable from it.
750 [NB: If B was compiled with -O, but A isn't, we should really *still*
751 haul in all the unfoldings for B, in case the module that imports A *is*
752 compiled with -O. I think this is the case.]
754 Even if B is used at all we get a usage line for B
755 import B <n> :: ... ;
756 in A.hi, to record the fact that A does import B. This is used to decide
757 to look to look for B.hi rather than B.hi-boot when compiling a module that
758 imports A. This line says that A imports B, but uses nothing in it.
759 So we'll get an early bale-out when compiling A if B's version changes.
762 getImportVersions :: ModuleName -- Name of this module
763 -> ExportEnv -- Info about exports
764 -> RnMG (VersionInfo Name) -- Version info for these names
766 getImportVersions this_mod (ExportEnv _ _ export_all_mods)
767 = getIfacesRn `thenRn` \ ifaces ->
769 mod_map = iImpModInfo ifaces
770 imp_names = iVSlurp ifaces
772 -- mv_map groups together all the things imported from a particular module.
773 mv_map :: FiniteMap ModuleName [(Name,Version)]
774 mv_map = foldr add_mv emptyFM imp_names
776 -- Build the result list by adding info for each module.
777 -- For (a) a library module, we don't record it at all unless it contains orphans
778 -- (We must never lose track of orphans.)
780 -- (b) a source-imported module, don't record the dependency at all
782 -- (b) may seem a bit strange. The idea is that the usages in a .hi file records
783 -- *all* the module's dependencies other than the loop-breakers. We use
784 -- this info in findAndReadInterface to decide whether to look for a .hi file or
787 -- This means we won't track version changes, or orphans, from .hi-boot files.
788 -- The former is potentially rather bad news. It could be fixed by recording
789 -- whether something is a boot file along with the usage info for it, but
790 -- I can't be bothered just now.
792 mk_version_info mod_name (version, has_orphans, is_boot, contents) so_far
793 | mod_name == this_mod -- Check if M appears in the set of modules 'below' M
794 -- This seems like a convenient place to check
795 = WARN( not is_boot, ptext SLIT("Wierd:") <+> ppr this_mod <+>
796 ptext SLIT("imports itself (perhaps indirectly)") )
801 go_for_it exports = (mod_name, version, has_orphans, is_boot, exports)
805 Nothing -> -- We didn't even open the interface
806 -- This happens when a module, Foo, that we explicitly imported has
807 -- 'import Baz' in its interface file, recording that Baz is below
808 -- Foo in the module dependency hierarchy. We want to propagate this
809 -- information. The Nothing says that we didn't even open the interface
810 -- file but we must still propagate the dependeny info.
811 -- The module in question must be a local module (in the same package)
812 go_for_it (Specifically [])
814 Just (mod, how_imported, _)
815 | is_sys_import && is_lib_module && not has_orphans
818 | is_lib_module -- Record the module but not detailed
819 || mod_name `elem` export_all_mods -- version information for the imports
820 -> go_for_it Everything
823 -> case lookupFM mv_map mod_name of
824 Just whats_imported -> go_for_it (Specifically whats_imported)
825 Nothing -> go_for_it (Specifically [])
826 -- This happens if you have
828 -- but don't actually *use* anything from Foo
829 -- In which case record an empty dependency list
831 is_lib_module = not (isLocalModule mod)
832 is_sys_import = case how_imported of
833 ImportBySystem -> True
838 returnRn (foldFM mk_version_info [] mod_map)
840 add_mv v@(name, version) mv_map
841 = addToFM_C add_item mv_map mod [v]
843 mod = moduleName (nameModule name)
844 add_item vs _ = (v:vs)
849 = getIfacesRn `thenRn` \ ifaces ->
850 returnRn (iSlurp ifaces)
852 recordSlurp maybe_version avail
853 -- Nothing for locally defined names
854 -- Just version for imported names
855 = getIfacesRn `thenRn` \ ifaces@(Ifaces { iSlurp = slurped_names,
856 iVSlurp = imp_names }) ->
858 new_slurped_names = addAvailToNameSet slurped_names avail
860 new_imp_names = case maybe_version of
861 Just version -> (availName avail, version) : imp_names
864 setIfacesRn (ifaces { iSlurp = new_slurped_names,
865 iVSlurp = new_imp_names })
869 %*********************************************************
871 \subsection{Getting binders out of a declaration}
873 %*********************************************************
875 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
876 It's used for both source code (from @availsFromDecl@) and interface files
879 It doesn't deal with source-code specific things: @ValD@, @DefD@. They
880 are handled by the sourc-code specific stuff in @RnNames@.
883 getDeclBinders :: (RdrName -> SrcLoc -> RnM d Name) -- New-name function
885 -> RnM d (Maybe AvailInfo)
887 getDeclBinders new_name (TyClD (TyData _ _ tycon _ condecls _ _ src_loc))
888 = new_name tycon src_loc `thenRn` \ tycon_name ->
889 getConFieldNames new_name condecls `thenRn` \ sub_names ->
890 returnRn (Just (AvailTC tycon_name (tycon_name : nub sub_names)))
891 -- The "nub" is because getConFieldNames can legitimately return duplicates,
892 -- when a record declaration has the same field in multiple constructors
894 getDeclBinders new_name (TyClD (TySynonym tycon _ _ src_loc))
895 = new_name tycon src_loc `thenRn` \ tycon_name ->
896 returnRn (Just (AvailTC tycon_name [tycon_name]))
898 getDeclBinders new_name (TyClD (ClassDecl _ cname _ _ sigs _ _ _ _ _ _ src_loc))
899 = new_name cname src_loc `thenRn` \ class_name ->
901 -- Record the names for the class ops
903 -- just want class-op sigs
904 op_sigs = filter isClassOpSig sigs
906 mapRn (getClassOpNames new_name) op_sigs `thenRn` \ sub_names ->
908 returnRn (Just (AvailTC class_name (class_name : sub_names)))
910 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
911 = new_name var src_loc `thenRn` \ var_name ->
912 returnRn (Just (Avail var_name))
914 getDeclBinders new_name (FixD _) = returnRn Nothing
916 -- foreign declarations
917 getDeclBinders new_name (ForD (ForeignDecl nm kind _ dyn _ loc))
918 | binds_haskell_name kind dyn
919 = new_name nm loc `thenRn` \ name ->
920 returnRn (Just (Avail name))
922 | otherwise -- a foreign export
923 = lookupImplicitOccRn nm `thenRn_`
926 getDeclBinders new_name (DefD _) = returnRn Nothing
927 getDeclBinders new_name (InstD _) = returnRn Nothing
928 getDeclBinders new_name (RuleD _) = returnRn Nothing
930 binds_haskell_name (FoImport _) _ = True
931 binds_haskell_name FoLabel _ = True
932 binds_haskell_name FoExport ext_nm = isDynamicExtName ext_nm
935 getConFieldNames new_name (ConDecl con _ _ _ (RecCon fielddecls) src_loc : rest)
936 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
937 getConFieldNames new_name rest `thenRn` \ ns ->
940 fields = concat (map fst fielddecls)
942 getConFieldNames new_name (ConDecl con _ _ _ condecl src_loc : rest)
943 = new_name con src_loc `thenRn` \ n ->
946 new_name f src_loc `thenRn` \ new_f ->
948 _ -> returnRn [n]) `thenRn` \ nn ->
949 getConFieldNames new_name rest `thenRn` \ ns ->
952 getConFieldNames new_name [] = returnRn []
954 getClassOpNames new_name (ClassOpSig op _ _ _ src_loc) = new_name op src_loc
957 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
958 A the moment that's just the tycon and datacon that come with a class decl.
959 They aren't returned by @getDeclBinders@ because they aren't in scope;
960 but they {\em should} be put into the @DeclsMap@ of this module.
962 Note that this excludes the default-method names of a class decl,
963 and the dict fun of an instance decl, because both of these have
964 bindings of their own elsewhere.
967 getDeclSysBinders new_name (TyClD (ClassDecl _ cname _ _ sigs _ _ tname dname dwname snames src_loc))
968 = sequenceRn [new_name n src_loc | n <- (tname : dname : dwname : snames)]
970 getDeclSysBinders new_name (TyClD (TyData _ _ _ _ cons _ _ _))
971 = sequenceRn [new_name wkr_name src_loc | ConDecl _ wkr_name _ _ _ src_loc <- cons]
973 getDeclSysBinders new_name other_decl
977 %*********************************************************
979 \subsection{Reading an interface file}
981 %*********************************************************
984 findAndReadIface :: SDoc -> ModuleName
985 -> IsBootInterface -- True <=> Look for a .hi-boot file
986 -- False <=> Look for .hi file
987 -> RnM d (Either Message ParsedIface)
988 -- Nothing <=> file not found, or unreadable, or illegible
989 -- Just x <=> successfully found and parsed
991 findAndReadIface doc_str mod_name hi_boot_file
992 = traceRn trace_msg `thenRn_`
993 -- we keep two maps for interface files,
994 -- one for 'normal' ones, the other for .hi-boot files,
995 -- hence the need to signal which kind we're interested.
997 getHiMaps `thenRn` \ (search_path, hi_map, hiboot_map) ->
999 relevant_map | hi_boot_file = hiboot_map
1000 | otherwise = hi_map
1002 case lookupFM relevant_map mod_name of
1004 Just fpath -> traceRn (ptext SLIT("...reading from") <+> text fpath) `thenRn_`
1005 readIface mod_name fpath
1008 Nothing -> traceRn (ptext SLIT("...not found")) `thenRn_`
1009 returnRn (Left (noIfaceErr mod_name hi_boot_file search_path))
1012 trace_msg = sep [hsep [ptext SLIT("Reading"),
1013 if hi_boot_file then ptext SLIT("[boot]") else empty,
1014 ptext SLIT("interface for"),
1015 pprModuleName mod_name <> semi],
1016 nest 4 (ptext SLIT("reason:") <+> doc_str)]
1019 @readIface@ tries just the one file.
1022 readIface :: ModuleName -> String -> RnM d (Either Message ParsedIface)
1023 -- Nothing <=> file not found, or unreadable, or illegible
1024 -- Just x <=> successfully found and parsed
1025 readIface wanted_mod file_path
1026 = ioToRnM (hGetStringBuffer False file_path) `thenRn` \ read_result ->
1029 case parseIface contents
1030 PState{ bol = 0#, atbol = 1#,
1033 loc = mkSrcLoc (mkFastString file_path) 1 } of
1034 POk _ (PIface iface) ->
1035 warnCheckRn (read_mod == wanted_mod)
1036 (hiModuleNameMismatchWarn wanted_mod read_mod) `thenRn_`
1037 returnRn (Right iface)
1039 read_mod = moduleName (pi_mod iface)
1041 PFailed err -> bale_out err
1042 parse_result -> bale_out empty
1043 -- This last case can happen if the interface file is (say) empty
1044 -- in which case the parser thinks it looks like an IdInfo or
1045 -- something like that. Just an artefact of the fact that the
1046 -- parser is used for several purposes at once.
1048 Left io_err -> bale_out (text (show io_err))
1050 bale_out err = returnRn (Left (badIfaceFile file_path err))
1053 %*********************************************************
1057 %*********************************************************
1060 noIfaceErr mod_name boot_file search_path
1061 = vcat [ptext SLIT("Could not find interface file for") <+> quotes (pprModuleName mod_name),
1062 ptext SLIT("in the directories") <+>
1063 -- \& to avoid cpp interpreting this string as a
1064 -- comment starter with a pre-4.06 mkdependHS --SDM
1065 vcat [ text dir <> text "/\&*" <> pp_suffix suffix
1066 | (dir,suffix) <- search_path]
1069 pp_suffix suffix | boot_file = ptext SLIT(".hi-boot")
1070 | otherwise = text suffix
1072 badIfaceFile file err
1073 = vcat [ptext SLIT("Bad interface file:") <+> text file,
1077 = vcat [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
1078 ptext SLIT("from module") <+> quotes (ppr (nameModule name))
1081 getDeclWarn name loc
1082 = sep [ptext SLIT("Failed to find (optional) interface decl for") <+> quotes (ppr name),
1083 ptext SLIT("desired at") <+> ppr loc]
1087 "Compiler tried to import decl from interface file with same name as module."),
1089 "(possible cause: module name clashes with interface file already in scope.)")
1091 hsep [ptext SLIT("name:"), quotes (ppr name)]
1093 warnRedundantSourceImport mod_name
1094 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
1095 <+> quotes (pprModuleName mod_name)
1097 hiModuleNameMismatchWarn :: ModuleName -> ModuleName -> Message
1098 hiModuleNameMismatchWarn requested_mod read_mod =
1099 hsep [ ptext SLIT("Something is amiss; requested module name")
1100 , pprModuleName requested_mod
1101 , ptext SLIT("differs from name found in the interface file")
1102 , pprModuleName read_mod