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(..), isDynamic,
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,
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, isLibModule,
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 `thenRn` \ (_, ifaces) ->
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_`
97 load mod = loadInterface (pprModuleName mod <+> ptext SLIT("is a orphan-instance module")) mod ImportBySystem
99 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (Module, Ifaces)
100 loadInterface doc_str mod_name from
101 = getIfacesRn `thenRn` \ ifaces ->
103 mod_map = iImpModInfo ifaces
104 mod_info = lookupFM mod_map mod_name
105 in_map = maybeToBool mod_info
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_`
115 -- CHECK WHETHER WE HAVE IT ALREADY
117 Just (_, _, Just (load_mod, _, _))
118 -> -- We're read it already so don't re-read it
119 returnRn (load_mod, ifaces) ;
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
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 }
134 setIfacesRn new_ifaces `thenRn_`
135 failWithRn (mod, new_ifaces) (noIfaceErr mod hi_boot_read) ;
140 -- LOAD IT INTO Ifaces
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)
147 getModuleRn `thenRn` \ this_mod_nm ->
149 rd_decls = pi_decls iface
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 (if opt_IgnoreIfacePragmas
157 then returnRn emptyNameEnv
158 else foldlRn (loadDeprec mod) (iDeprecs ifaces) (pi_deprecs iface)) `thenRn` \ new_deprecs ->
159 foldlRn (loadFixDecl mod_name) (iFixes ifaces) rd_decls `thenRn` \ new_fixities ->
160 mapRn (loadExport this_mod_nm) (pi_exports iface) `thenRn` \ avails_s ->
162 -- For an explicit user import, add to mod_map info about
163 -- the things the imported module depends on, extracted
164 -- from its usage info.
165 mod_map1 = case from of
166 ImportByUser -> addModDeps mod mod_map (pi_usages iface)
169 -- Now add info about this module
170 mod_map2 = addToFM mod_map1 mod_name mod_details
171 mod_details = (pi_mod iface, pi_orphan iface, Just (mod, hi_boot_read, concat avails_s))
173 new_ifaces = ifaces { iImpModInfo = mod_map2,
175 iFixes = new_fixities,
178 iDeprecs = new_deprecs }
180 setIfacesRn new_ifaces `thenRn_`
181 returnRn (mod, new_ifaces)
184 addModDeps :: Module -> ImportedModuleInfo
185 -> [ImportVersion a] -> ImportedModuleInfo
186 addModDeps mod mod_deps new_deps
187 = foldr add mod_deps new_deps
189 is_lib = isLibModule mod -- Don't record dependencies when importing a library module
190 add (imp_mod, version, has_orphans, _) deps
191 | is_lib && not has_orphans = deps
192 | otherwise = addToFM_C combine deps imp_mod (version, has_orphans, Nothing)
193 -- Record dependencies for modules that are
194 -- either are dependent via a non-library module
195 -- or contain orphan rules or instance decls
197 -- Don't ditch a module that's already loaded!!
198 combine old@(_, _, Just _) new = old
199 combine old@(_, _, Nothing) new = new
201 loadExport :: ModuleName -> ExportItem -> RnM d [AvailInfo]
202 loadExport this_mod (mod, entities)
203 | mod == this_mod = returnRn []
204 -- If the module exports anything defined in this module, just ignore it.
205 -- Reason: otherwise it looks as if there are two local definition sites
206 -- for the thing, and an error gets reported. Easiest thing is just to
207 -- filter them out up front. This situation only arises if a module
208 -- imports itself, or another module that imported it. (Necessarily,
209 -- this invoves a loop.) Consequence: if you say
214 -- module B( AType ) where
215 -- import {-# SOURCE #-} A( AType )
217 -- then you'll get a 'B does not export AType' message. A bit bogus
218 -- but it's a bogus thing to do!
221 = mapRn (load_entity mod) entities
223 new_name mod occ = mkImportedGlobalName mod occ
225 load_entity mod (Avail occ)
226 = new_name mod occ `thenRn` \ name ->
227 returnRn (Avail name)
228 load_entity mod (AvailTC occ occs)
229 = new_name mod occ `thenRn` \ name ->
230 mapRn (new_name mod) occs `thenRn` \ names ->
231 returnRn (AvailTC name names)
234 loadFixDecl :: ModuleName -> FixityEnv
235 -> (Version, RdrNameHsDecl)
237 loadFixDecl mod_name fixity_env (version, FixD sig@(FixitySig rdr_name fixity loc))
238 = -- Ignore the version; when the fixity changes the version of
239 -- its 'host' entity changes, so we don't need a separate version
240 -- number for fixities
241 mkImportedGlobalName mod_name (rdrNameOcc rdr_name) `thenRn` \ name ->
243 new_fixity_env = addToNameEnv fixity_env name (FixitySig name fixity loc)
245 returnRn new_fixity_env
247 -- Ignore the other sorts of decl
248 loadFixDecl mod_name fixity_env other_decl = returnRn fixity_env
252 -> (Version, RdrNameHsDecl)
255 loadDecl mod decls_map (version, decl)
256 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
257 case maybe_avail of {
258 Nothing -> returnRn decls_map; -- No bindings
261 getDeclSysBinders new_name decl `thenRn` \ sys_bndrs ->
263 main_name = availName avail
264 new_decls_map = foldl add_decl decls_map
265 [ (name, (version, avail, name==main_name, (mod, decl')))
266 | name <- sys_bndrs ++ availNames avail]
267 add_decl decls_map (name, stuff)
268 = WARN( name `elemNameEnv` decls_map, ppr name )
269 addToNameEnv decls_map name stuff
271 returnRn new_decls_map
274 -- newImportedBinder puts into the cache the binder with the
275 -- module information set correctly. When the decl is later renamed,
276 -- the binding site will thereby get the correct module.
277 new_name rdr_name loc = newImportedBinder mod rdr_name
280 If a signature decl is being loaded, and optIgnoreIfacePragmas is on,
281 we toss away unfolding information.
283 Also, if the signature is loaded from a module we're importing from source,
284 we do the same. This is to avoid situations when compiling a pair of mutually
285 recursive modules, peering at unfolding info in the interface file of the other,
286 e.g., you compile A, it looks at B's interface file and may as a result change
287 its interface file. Hence, B is recompiled, maybe changing its interface file,
288 which will the unfolding info used in A to become invalid. Simple way out is to
289 just ignore unfolding info.
291 [Jan 99: I junked the second test above. If we're importing from an hi-boot
292 file there isn't going to *be* any pragma info. Maybe the above comment
293 dates from a time where we picked up a .hi file first if it existed?]
296 SigD (IfaceSig name tp ls loc) | opt_IgnoreIfacePragmas
297 -> SigD (IfaceSig name tp [] loc)
300 loadInstDecl :: Module
303 -> RnM d (Bag GatedDecl)
304 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
306 -- Find out what type constructors and classes are "gates" for the
307 -- instance declaration. If all these "gates" are slurped in then
308 -- we should slurp the instance decl too.
310 -- We *don't* want to count names in the context part as gates, though.
312 -- instance Foo a => Baz (T a) where ...
314 -- Here the gates are Baz and T, but *not* Foo.
316 munged_inst_ty = removeContext inst_ty
317 free_names = extractHsTyRdrNames munged_inst_ty
319 setModuleRn (moduleName mod) $
320 mapRn mkImportedGlobalFromRdrName free_names `thenRn` \ gate_names ->
321 returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
324 -- In interface files, the instance decls now look like
325 -- forall a. Foo a -> Baz (T a)
326 -- so we have to strip off function argument types as well
327 -- as the bit before the '=>' (which is always empty in interface files)
328 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
329 removeContext ty = removeFuns ty
331 removeFuns (MonoFunTy _ ty) = removeFuns ty
335 loadRule :: Module -> Bag GatedDecl
336 -> RdrNameRuleDecl -> RnM d (Bag GatedDecl)
337 -- "Gate" the rule simply by whether the rule variable is
338 -- needed. We can refine this later.
339 loadRule mod rules decl@(IfaceRuleDecl var body src_loc)
340 = setModuleRn (moduleName mod) $
341 mkImportedGlobalFromRdrName var `thenRn` \ var_name ->
342 returnRn ((unitNameSet var_name, (mod, RuleD decl)) `consBag` rules)
344 -- SUP: TEMPORARY HACK, ignoring module deprecations for now
345 loadDeprec :: Module -> DeprecationEnv -> RdrNameDeprecation -> RnM d DeprecationEnv
346 loadDeprec mod deprec_env (Deprecation (IEModuleContents _) txt)
347 = traceRn (text "module deprecation not yet implemented:" <+> ppr mod <> colon <+> ppr txt) `thenRn_`
349 loadDeprec mod deprec_env (Deprecation ie txt)
350 = setModuleRn (moduleName mod) $
351 mapRn mkImportedGlobalFromRdrName (namesFromIE ie) `thenRn` \ names ->
352 traceRn (text "loaded deprecation(s) for" <+> hcat (punctuate comma (map ppr names)) <> colon <+> ppr txt) `thenRn_`
353 returnRn (extendNameEnv deprec_env (zip names (repeat txt)))
355 namesFromIE :: IE a -> [a]
356 namesFromIE (IEVar n ) = [n]
357 namesFromIE (IEThingAbs n ) = [n]
358 namesFromIE (IEThingAll n ) = [n]
359 namesFromIE (IEThingWith n ns) = n:ns
360 namesFromIE (IEModuleContents _ ) = []
364 %********************************************************
366 \subsection{Loading usage information}
368 %********************************************************
371 checkUpToDate :: ModuleName -> RnMG Bool -- True <=> no need to recompile
372 checkUpToDate mod_name
373 = getIfacesRn `thenRn` \ ifaces ->
374 findAndReadIface doc_str mod_name
376 (error "checkUpToDate") `thenRn` \ (_, read_result) ->
378 -- CHECK WHETHER WE HAVE IT ALREADY
380 Nothing -> -- Old interface file not found, so we'd better bail out
381 traceRn (sep [ptext SLIT("Didnt find old iface"),
382 pprModuleName mod_name]) `thenRn_`
386 -> -- Found it, so now check it
387 checkModUsage (pi_usages iface)
389 -- Only look in current directory, with suffix .hi
390 doc_str = sep [ptext SLIT("need usage info from"), pprModuleName mod_name]
392 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
394 checkModUsage ((mod_name, old_mod_vers, _, Specifically []) : rest)
395 -- If CurrentModule.hi contains
397 -- then that simply records that Foo lies below CurrentModule in the
398 -- hierarchy, but CurrentModule doesn't depend in any way on Foo.
399 -- In this case we don't even want to open Foo's interface.
400 = traceRn (ptext SLIT("Nothing used from:") <+> ppr mod_name) `thenRn_`
401 checkModUsage rest -- This one's ok, so check the rest
403 checkModUsage ((mod_name, old_mod_vers, _, whats_imported) : rest)
404 = loadInterface doc_str mod_name ImportBySystem `thenRn` \ (mod, ifaces) ->
406 maybe_mod_vers = case lookupFM (iImpModInfo ifaces) mod_name of
407 Just (version, _, Just (_, _, _)) -> Just version
410 case maybe_mod_vers of {
411 Nothing -> -- If we can't find a version number for the old module then
412 -- bail out saying things aren't up to date
413 traceRn (sep [ptext SLIT("Can't find version number for module"),
414 pprModuleName mod_name])
415 `thenRn_` returnRn False ;
419 -- If the module version hasn't changed, just move on
420 if new_mod_vers == old_mod_vers then
421 traceRn (sep [ptext SLIT("Module version unchanged:"), pprModuleName mod_name])
422 `thenRn_` checkModUsage rest
424 traceRn (sep [ptext SLIT("Module version has changed:"), pprModuleName mod_name])
426 -- Module version changed, so check entities inside
428 -- If the usage info wants to say "I imported everything from this module"
429 -- it does so by making whats_imported equal to Everything
430 -- In that case, we must recompile
431 case whats_imported of {
432 Everything -> traceRn (ptext SLIT("...and I needed the whole module")) `thenRn_`
433 returnRn False; -- Bale out
435 Specifically old_local_vers ->
437 -- Non-empty usage list, so check item by item
438 checkEntityUsage mod_name (iDecls ifaces) old_local_vers `thenRn` \ up_to_date ->
440 traceRn (ptext SLIT("...but the bits I use haven't.")) `thenRn_`
441 checkModUsage rest -- This one's ok, so check the rest
443 returnRn False -- This one failed, so just bail out now
446 doc_str = sep [ptext SLIT("need version info for"), pprModuleName mod_name]
449 checkEntityUsage mod decls []
450 = returnRn True -- Yes! All up to date!
452 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
453 = mkImportedGlobalName mod occ_name `thenRn` \ name ->
454 case lookupNameEnv decls name of
456 Nothing -> -- We used it before, but it ain't there now
457 traceRn (sep [ptext SLIT("No longer exported:"), ppr name])
458 `thenRn_` returnRn False
460 Just (new_vers,_,_,_) -- It's there, but is it up to date?
461 | new_vers == old_vers
462 -- Up to date, so check the rest
463 -> checkEntityUsage mod decls rest
466 -- Out of date, so bale out
467 -> traceRn (sep [ptext SLIT("Out of date:"), ppr name]) `thenRn_`
472 %*********************************************************
474 \subsection{Getting in a declaration}
476 %*********************************************************
479 importDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
480 -- Returns Nothing for
483 -- (c) already slurped
489 = getSlurped `thenRn` \ already_slurped ->
490 if name `elemNameSet` already_slurped then
491 returnRn Nothing -- Already dealt with
493 if isLocallyDefined name then -- Don't bring in decls from
494 -- the renamed module's own interface file
495 addWarnRn (importDeclWarn name) `thenRn_`
498 getNonWiredInDecl name
502 getNonWiredInDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
503 getNonWiredInDecl needed_name
504 = traceRn doc_str `thenRn_`
505 loadHomeInterface doc_str needed_name `thenRn` \ ifaces ->
506 case lookupNameEnv (iDecls ifaces) needed_name of
508 Just (version,avail,_,decl)
509 -> recordSlurp (Just version) avail `thenRn_`
512 Nothing -- Can happen legitimately for "Optional" occurrences
513 -> addErrRn (getDeclErr needed_name) `thenRn_`
516 doc_str = ptext SLIT("need decl for") <+> ppr needed_name
519 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
520 It behaves exactly as if the wired in decl were actually in an interface file.
523 \item if the wired-in name is a data type constructor or a data constructor,
524 it brings in the type constructor and all the data constructors; and
525 marks as ``occurrences'' any free vars of the data con.
527 \item similarly for synonum type constructor
529 \item if the wired-in name is another wired-in Id, it marks as ``occurrences''
530 the free vars of the Id's type.
532 \item it loads the interface file for the wired-in thing for the
533 sole purpose of making sure that its instance declarations are available
535 All this is necessary so that we know all types that are ``in play'', so
536 that we know just what instances to bring into scope.
541 %*********************************************************
543 \subsection{Getting what a module exports}
545 %*********************************************************
547 @getInterfaceExports@ is called only for directly-imported modules.
550 getInterfaceExports :: ModuleName -> WhereFrom -> RnMG (Module, Avails)
551 getInterfaceExports mod_name from
552 = loadInterface doc_str mod_name from `thenRn` \ (mod, ifaces) ->
553 case lookupFM (iImpModInfo ifaces) mod_name of
554 Nothing -> -- Not there; it must be that the interface file wasn't found;
555 -- the error will have been reported already.
556 -- (Actually loadInterface should put the empty export env in there
557 -- anyway, but this does no harm.)
560 Just (_, _, Just (mod, _, avails)) -> returnRn (mod, avails)
562 doc_str = sep [pprModuleName mod_name, ptext SLIT("is directly imported")]
566 %*********************************************************
568 \subsection{Instance declarations are handled specially}
570 %*********************************************************
573 getImportedInstDecls :: NameSet -> RnMG [(Module,RdrNameHsDecl)]
574 getImportedInstDecls gates
575 = -- First, load any orphan-instance modules that aren't aready loaded
576 -- Orphan-instance modules are recorded in the module dependecnies
577 getIfacesRn `thenRn` \ ifaces ->
580 [mod | (mod, (_, True, Nothing)) <- fmToList (iImpModInfo ifaces)]
582 loadOrphanModules orphan_mods `thenRn_`
584 -- Now we're ready to grab the instance declarations
585 -- Find the un-gated ones and return them,
586 -- removing them from the bag kept in Ifaces
587 getIfacesRn `thenRn` \ ifaces ->
589 (decls, new_insts) = selectGated gates (iInsts ifaces)
591 setIfacesRn (ifaces { iInsts = new_insts }) `thenRn_`
593 traceRn (sep [text "getImportedInstDecls:",
594 nest 4 (fsep (map ppr gate_list)),
595 text "Slurped" <+> int (length decls) <+> text "instance declarations",
596 nest 4 (vcat (map ppr_brief_inst_decl decls))]) `thenRn_`
599 gate_list = nameSetToList gates
601 load_home gate | isLocallyDefined gate
604 = loadHomeInterface (ppr gate <+> text "is an instance gate") gate `thenRn_`
607 ppr_brief_inst_decl (mod, InstD (InstDecl inst_ty _ _ _ _))
609 HsForAllTy _ _ tau -> ppr tau
612 getImportedRules :: RnMG [(Module,RdrNameHsDecl)]
614 | opt_IgnoreIfacePragmas = returnRn []
616 = getIfacesRn `thenRn` \ ifaces ->
618 gates = iSlurp ifaces -- Anything at all that's been slurped
619 (decls, new_rules) = selectGated gates (iRules ifaces)
621 setIfacesRn (ifaces { iRules = new_rules }) `thenRn_`
622 traceRn (sep [text "getImportedRules:",
623 text "Slurped" <+> int (length decls) <+> text "rules"]) `thenRn_`
626 selectGated gates decl_bag
627 -- Select only those decls whose gates are *all* in 'gates'
629 | opt_NoPruneDecls -- Just to try the effect of not gating at all
630 = (foldrBag (\ (_,d) ds -> d:ds) [] decl_bag, emptyBag) -- Grab them all
634 = foldrBag select ([], emptyBag) decl_bag
636 select (reqd, decl) (yes, no)
637 | isEmptyNameSet (reqd `minusNameSet` gates) = (decl:yes, no)
638 | otherwise = (yes, (reqd,decl) `consBag` no)
640 lookupFixity :: Name -> RnMS Fixity
642 | isLocallyDefined name
643 = getFixityEnv `thenRn` \ local_fix_env ->
644 case lookupNameEnv local_fix_env name of
645 Just (FixitySig _ fix _) -> returnRn fix
646 Nothing -> returnRn defaultFixity
648 | otherwise -- Imported
649 -- For imported names, we have to get their fixities by doing a loadHomeInterface,
650 -- and consulting the Ifaces that comes back from that, because the interface
651 -- file for the Name might not have been loaded yet. Why not? Suppose you import module A,
652 -- which exports a function 'f', which is defined in module B. Then B isn't loaded
653 -- right away (after all, it's possible that nothing from B will be used).
654 -- When we come across a use of 'f', we need to know its fixity, and it's then,
655 -- and only then, that we load B.hi. That is what's happening here.
656 = loadHomeInterface doc name `thenRn` \ ifaces ->
657 case lookupNameEnv (iFixes ifaces) name of
658 Just (FixitySig _ fix _) -> returnRn fix
659 Nothing -> returnRn defaultFixity
661 doc = ptext SLIT("Checking fixity for") <+> ppr name
665 %*********************************************************
667 \subsection{Keeping track of what we've slurped, and version numbers}
669 %*********************************************************
671 getImportVersions figures out what the ``usage information'' for this
672 moudule is; that is, what it must record in its interface file as the
673 things it uses. It records:
676 \item anything reachable from its body code
677 \item any module exported with a @module Foo@.
680 Why the latter? Because if @Foo@ changes then this module's export list
681 will change, so we must recompile this module at least as far as
682 making a new interface file --- but in practice that means complete
687 module A( f, g ) where | module B( f ) where
688 import B( f ) | f = h 3
692 Should we record @B.f@ in @A@'s usages? In fact we don't. Certainly,
693 if anything about @B.f@ changes than anyone who imports @A@ should be
694 recompiled; they'll get an early exit if they don't use @B.f@.
695 However, even if @B.f@ doesn't change at all, @B.h@ may do so, and
696 this change may not be reflected in @f@'s version number. So there
697 are two things going on when compiling module @A@:
700 \item Are @A.o@ and @A.hi@ correct? Then we can bale out early.
701 \item Should modules that import @A@ be recompiled?
704 For (1) it is slightly harmful to record @B.f@ in @A@'s usages,
705 because a change in @B.f@'s version will provoke full recompilation of
706 @A@, producing an identical @A.o@, and @A.hi@ differing only in its
707 usage-version of @B.f@ (and this usage-version info isn't used by any
710 For (2), because of the tricky @B.h@ question above, we ensure that
711 @A.hi@ is touched (even if identical to its previous version) if A's
712 recompilation was triggered by an imported @.hi@ file date change.
713 Given that, there's no need to record @B.f@ in @A@'s usages.
715 On the other hand, if @A@ exports @module B@, then we {\em do} count
716 @module B@ among @A@'s usages, because we must recompile @A@ to ensure
717 that @A.hi@ changes appropriately.
719 HOWEVER, we *do* record the usage
721 in A.hi, to record the fact that A does import B. This is used to decide
722 to look to look for B.hi rather than B.hi-boot when compiling a module that
723 imports A. This line says that A imports B, but uses nothing in it.
724 So we'll get an early bale-out when compiling A if B's version changes.
727 getImportVersions :: ModuleName -- Name of this module
728 -> ExportEnv -- Info about exports
729 -> RnMG (VersionInfo Name) -- Version info for these names
731 getImportVersions this_mod (ExportEnv export_avails _ export_all_mods)
732 = getIfacesRn `thenRn` \ ifaces ->
734 mod_map = iImpModInfo ifaces
735 imp_names = iVSlurp ifaces
737 -- mv_map groups together all the things imported from a particular module.
738 mv_map :: FiniteMap ModuleName [(Name,Version)]
739 mv_map = foldr add_mv emptyFM imp_names
741 -- Build the result list by adding info for each module.
742 -- For (a) a library module, we don't record it at all unless it contains orphans
743 -- (We must never lose track of orphans.)
745 -- (b) a source-imported module, don't record the dependency at all
747 -- (b) may seem a bit strange. The idea is that the usages in a .hi file records
748 -- *all* the module's dependencies other than the loop-breakers. We use
749 -- this info in findAndReadInterface to decide whether to look for a .hi file or
752 -- This means we won't track version changes, or orphans, from .hi-boot files.
753 -- The former is potentially rather bad news. It could be fixed by recording
754 -- whether something is a boot file along with the usage info for it, but
755 -- I can't be bothered just now.
757 mk_version_info mod_name (version, has_orphans, contents) so_far
759 go_for_it exports = (mod_name, version, has_orphans, exports) : so_far
762 Nothing -> -- We didn't even open the interface
763 -- This happens when a module, Foo, that we explicitly imported has
764 -- 'import Baz' in its interface file, recording that Baz is below
765 -- Foo in the module dependency hierarchy. We want to propagate this
766 -- information. The Nothing says that we didn't even open the interface
767 -- file but we must still propagate the dependeny info.
768 go_for_it (Specifically [])
770 Just (mod, boot_import, _) -- We did open the interface
771 | boot_import -- Don't record any usage info for this module
772 || (is_lib_module && not has_orphans)
775 | is_lib_module -- Record the module but not detailed
776 || mod_name `elem` export_all_mods -- version information for the imports
777 -> go_for_it Everything
780 -> case lookupFM mv_map mod_name of
781 Just whats_imported -> go_for_it (Specifically whats_imported)
782 Nothing -> go_for_it (Specifically [])
783 -- This happens if you have
785 -- but don't actually *use* anything from Foo
786 -- In which case record an empty dependency list
788 is_lib_module = isLibModule mod
791 -- A module shouldn't load its own interface
792 -- This seems like a convenient place to check
793 WARN( maybeToBool (lookupFM mod_map this_mod),
794 ptext SLIT("Wierd:") <+> ppr this_mod <+> ptext SLIT("loads its own interface") )
796 returnRn (foldFM mk_version_info [] mod_map)
798 add_mv v@(name, version) mv_map
799 = addToFM_C add_item mv_map mod [v]
801 mod = moduleName (nameModule name)
802 add_item vs _ = (v:vs)
807 = getIfacesRn `thenRn` \ ifaces ->
808 returnRn (iSlurp ifaces)
810 recordSlurp maybe_version avail
811 = getIfacesRn `thenRn` \ ifaces@(Ifaces { iSlurp = slurped_names,
812 iVSlurp = imp_names }) ->
814 new_slurped_names = addAvailToNameSet slurped_names avail
816 new_imp_names = case maybe_version of
817 Just version -> (availName avail, version) : imp_names
820 setIfacesRn (ifaces { iSlurp = new_slurped_names,
821 iVSlurp = new_imp_names })
825 %*********************************************************
827 \subsection{Getting binders out of a declaration}
829 %*********************************************************
831 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
832 It's used for both source code (from @availsFromDecl@) and interface files
835 It doesn't deal with source-code specific things: @ValD@, @DefD@. They
836 are handled by the sourc-code specific stuff in @RnNames@.
839 getDeclBinders :: (RdrName -> SrcLoc -> RnM d Name) -- New-name function
841 -> RnM d (Maybe AvailInfo)
843 getDeclBinders new_name (TyClD (TyData _ _ tycon _ condecls _ _ src_loc))
844 = new_name tycon src_loc `thenRn` \ tycon_name ->
845 getConFieldNames new_name condecls `thenRn` \ sub_names ->
846 returnRn (Just (AvailTC tycon_name (tycon_name : nub sub_names)))
847 -- The "nub" is because getConFieldNames can legitimately return duplicates,
848 -- when a record declaration has the same field in multiple constructors
850 getDeclBinders new_name (TyClD (TySynonym tycon _ _ src_loc))
851 = new_name tycon src_loc `thenRn` \ tycon_name ->
852 returnRn (Just (AvailTC tycon_name [tycon_name]))
854 getDeclBinders new_name (TyClD (ClassDecl _ cname _ _ sigs _ _ _ _ _ src_loc))
855 = new_name cname src_loc `thenRn` \ class_name ->
857 -- Record the names for the class ops
859 -- just want class-op sigs
860 op_sigs = filter isClassOpSig sigs
862 mapRn (getClassOpNames new_name) op_sigs `thenRn` \ sub_names ->
864 returnRn (Just (AvailTC class_name (class_name : sub_names)))
866 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
867 = new_name var src_loc `thenRn` \ var_name ->
868 returnRn (Just (Avail var_name))
870 getDeclBinders new_name (FixD _) = returnRn Nothing
872 -- foreign declarations
873 getDeclBinders new_name (ForD (ForeignDecl nm kind _ dyn _ loc))
874 | binds_haskell_name kind dyn
875 = new_name nm loc `thenRn` \ name ->
876 returnRn (Just (Avail name))
878 | otherwise -- a foreign export
879 = lookupImplicitOccRn nm `thenRn_`
882 getDeclBinders new_name (DefD _) = returnRn Nothing
883 getDeclBinders new_name (InstD _) = returnRn Nothing
884 getDeclBinders new_name (RuleD _) = returnRn Nothing
886 binds_haskell_name (FoImport _) _ = True
887 binds_haskell_name FoLabel _ = True
888 binds_haskell_name FoExport ext_nm = isDynamic ext_nm
891 getConFieldNames new_name (ConDecl con _ _ (RecCon fielddecls) src_loc : rest)
892 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
893 getConFieldNames new_name rest `thenRn` \ ns ->
896 fields = concat (map fst fielddecls)
898 getConFieldNames new_name (ConDecl con _ _ condecl src_loc : rest)
899 = new_name con src_loc `thenRn` \ n ->
902 new_name f src_loc `thenRn` \ new_f ->
904 _ -> returnRn [n]) `thenRn` \ nn ->
905 getConFieldNames new_name rest `thenRn` \ ns ->
908 getConFieldNames new_name [] = returnRn []
910 getClassOpNames new_name (ClassOpSig op _ _ _ src_loc) = new_name op src_loc
913 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
914 A the moment that's just the tycon and datacon that come with a class decl.
915 They aren't returned by @getDeclBinders@ because they aren't in scope;
916 but they {\em should} be put into the @DeclsMap@ of this module.
918 Note that this excludes the default-method names of a class decl,
919 and the dict fun of an instance decl, because both of these have
920 bindings of their own elsewhere.
923 getDeclSysBinders new_name (TyClD (ClassDecl _ cname _ _ sigs _ _ tname dname snames src_loc))
924 = new_name dname src_loc `thenRn` \ datacon_name ->
925 new_name tname src_loc `thenRn` \ tycon_name ->
926 sequenceRn [new_name n src_loc | n <- snames] `thenRn` \ scsel_names ->
927 returnRn (tycon_name : datacon_name : scsel_names)
929 getDeclSysBinders new_name other_decl
933 %*********************************************************
935 \subsection{Reading an interface file}
937 %*********************************************************
940 findAndReadIface :: SDoc -> ModuleName -> WhereFrom
941 -> Bool -- Only relevant for SystemImport
942 -- True <=> Look for a .hi file
943 -- False <=> Look for .hi-boot file unless there's
944 -- a library .hi file
945 -> RnM d (Bool, Maybe (Module, ParsedIface))
946 -- Bool is True if the interface actually read was a .hi-boot one
947 -- Nothing <=> file not found, or unreadable, or illegible
948 -- Just x <=> successfully found and parsed
950 findAndReadIface doc_str mod_name from hi_file
951 = traceRn trace_msg `thenRn_`
952 -- we keep two maps for interface files,
953 -- one for 'normal' ones, the other for .hi-boot files,
954 -- hence the need to signal which kind we're interested.
956 getHiMaps `thenRn` \ hi_maps ->
958 case find_path from hi_maps of
960 (hi_boot, Just (fpath, mod)) -> traceRn (ptext SLIT("...reading from") <+> text fpath)
962 readIface mod fpath `thenRn` \ result ->
963 returnRn (hi_boot, result)
964 (hi_boot, Nothing) -> traceRn (ptext SLIT("...not found")) `thenRn_`
965 returnRn (hi_boot, Nothing)
967 find_path ImportByUser (hi_map, _) = (False, lookupFM hi_map mod_name)
968 find_path ImportByUserSource (_, hiboot_map) = (True, lookupFM hiboot_map mod_name)
970 find_path ImportBySystem (hi_map, hiboot_map)
972 = -- If the module we seek is in our dependent set,
973 -- Look for a .hi file
974 (False, lookupFM hi_map mod_name)
977 -- Check if there's a library module of that name
978 -- If not, look for an hi-boot file
979 = case lookupFM hi_map mod_name of
980 stuff@(Just (_, mod)) | isLibModule mod -> (False, stuff)
981 other -> (True, lookupFM hiboot_map mod_name)
983 trace_msg = sep [hsep [ptext SLIT("Reading"),
985 ptext SLIT("interface for"),
986 pprModuleName mod_name <> semi],
987 nest 4 (ptext SLIT("reason:") <+> doc_str)]
990 @readIface@ tries just the one file.
993 readIface :: Module -> String -> RnM d (Maybe (Module, ParsedIface))
994 -- Nothing <=> file not found, or unreadable, or illegible
995 -- Just x <=> successfully found and parsed
996 readIface the_mod file_path
997 = ioToRnM (hGetStringBuffer False file_path) `thenRn` \ read_result ->
1000 case parseIface contents
1001 PState{ bol = 0#, atbol = 1#,
1004 loc = mkSrcLoc (mkFastString file_path) 1 } of
1005 POk _ (PIface mod_nm iface) ->
1006 warnCheckRn (mod_nm == moduleName the_mod)
1007 (hiModuleNameMismatchWarn the_mod mod_nm) `thenRn_`
1008 returnRn (Just (the_mod, iface))
1010 PFailed err -> failWithRn Nothing err
1011 other -> failWithRn Nothing (ptext SLIT("Unrecognisable interface file"))
1012 -- This last case can happen if the interface file is (say) empty
1013 -- in which case the parser thinks it looks like an IdInfo or
1014 -- something like that. Just an artefact of the fact that the
1015 -- parser is used for several purposes at once.
1018 | isDoesNotExistError err -> returnRn Nothing
1019 | otherwise -> failWithRn Nothing (cannaeReadFile file_path err)
1022 %*********************************************************
1026 %*********************************************************
1029 noIfaceErr filename boot_file
1030 = hsep [ptext SLIT("Could not find valid"), boot,
1031 ptext SLIT("interface file"), quotes (pprModule filename)]
1033 boot | boot_file = ptext SLIT("[boot]")
1036 cannaeReadFile file err
1037 = hcat [ptext SLIT("Failed in reading file: "),
1039 ptext SLIT("; error="),
1043 = ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name)
1045 getDeclWarn name loc
1046 = sep [ptext SLIT("Failed to find (optional) interface decl for") <+> quotes (ppr name),
1047 ptext SLIT("desired at") <+> ppr loc]
1051 "Compiler tried to import decl from interface file with same name as module."),
1053 "(possible cause: module name clashes with interface file already in scope.)")
1055 hsep [ptext SLIT("name:"), quotes (ppr name)]
1057 warnRedundantSourceImport mod_name
1058 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
1059 <+> quotes (pprModuleName mod_name)
1061 hiModuleNameMismatchWarn :: Module -> ModuleName -> Message
1062 hiModuleNameMismatchWarn requested_mod mod_nm =
1063 hsep [ ptext SLIT("Something is amiss; requested module name")
1064 , pprModule requested_mod
1065 , ptext SLIT("differs from name found in the interface file ")
1066 , pprModuleName mod_nm