2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
10 getImportedInstDecls, getImportedRules,
12 importDecl, ImportDeclResult(..), recordLocalSlurps,
13 mkImportInfo, getSlurped,
15 RecompileRequired, outOfDate, upToDate, recompileRequired
19 #include "HsVersions.h"
21 import CmdLineOpts ( DynFlags, opt_NoPruneDecls, opt_NoPruneTyDecls, opt_IgnoreIfacePragmas )
23 import HsSyn ( HsDecl(..), InstDecl(..), HsType(..) )
24 import HsImpExp ( ImportDecl(..) )
25 import BasicTypes ( Version, defaultFixity )
26 import RdrHsSyn ( RdrNameHsDecl, RdrNameTyClDecl, RdrNameInstDecl )
27 import RnHiFiles ( tryLoadInterface, loadHomeInterface, loadInterface,
32 import Name ( Name {-instance NamedThing-}, nameOccName,
33 nameModule, isLocallyDefined,
37 import Module ( Module, ModuleEnv,
38 moduleName, isModuleInThisPackage,
39 ModuleName, WhereFrom(..),
40 emptyModuleEnv, lookupModuleEnvByName,
41 extendModuleEnv_C, lookupWithDefaultModuleEnv
44 import PrelInfo ( wiredInThingEnv )
45 import Maybes ( orElse )
54 %*********************************************************
56 \subsection{Getting what a module exports}
58 %*********************************************************
60 @getInterfaceExports@ is called only for directly-imported modules.
63 getInterfaceExports :: ModuleName -> WhereFrom -> RnMG (Module, Avails)
64 getInterfaceExports mod_name from
65 = getHomeIfaceTableRn `thenRn` \ hit ->
66 case lookupModuleEnvByName hit mod_name of {
67 Just mi -> returnRn (mi_module mi, mi_exports mi) ;
70 loadInterface doc_str mod_name from `thenRn` \ ifaces ->
71 case lookupModuleEnvByName (iPIT ifaces) mod_name of
72 Just mi -> returnRn (mi_module mi, mi_exports mi) ;
73 -- loadInterface always puts something in the map
74 -- even if it's a fake
75 Nothing -> pprPanic "getInterfaceExports" (ppr mod_name)
78 doc_str = sep [ppr mod_name, ptext SLIT("is directly imported")]
82 %*********************************************************
84 \subsection{Instance declarations are handled specially}
86 %*********************************************************
88 This has to be in RnIfaces (or RnHiFiles) because it calls loadHomeInterface
91 lookupFixityRn :: Name -> RnMS Fixity
93 | isLocallyDefined name
94 = getFixityEnv `thenRn` \ local_fix_env ->
95 returnRn (lookupLocalFixity local_fix_env name)
97 | otherwise -- Imported
98 -- For imported names, we have to get their fixities by doing a loadHomeInterface,
99 -- and consulting the Ifaces that comes back from that, because the interface
100 -- file for the Name might not have been loaded yet. Why not? Suppose you import module A,
101 -- which exports a function 'f', which is defined in module B. Then B isn't loaded
102 -- right away (after all, it's possible that nothing from B will be used).
103 -- When we come across a use of 'f', we need to know its fixity, and it's then,
104 -- and only then, that we load B.hi. That is what's happening here.
105 = getHomeIfaceTableRn `thenRn` \ hit ->
106 loadHomeInterface doc name `thenRn` \ ifaces ->
107 case lookupTable hit (iPIT ifaces) name of
108 Just iface -> returnRn (lookupNameEnv (mi_fixities iface) name `orElse` defaultFixity)
109 Nothing -> returnRn defaultFixity
111 doc = ptext SLIT("Checking fixity for") <+> ppr name
115 %*********************************************************
117 \subsection{Instance declarations are handled specially}
119 %*********************************************************
122 getImportedInstDecls :: NameSet -> RnMG [(Module,RdrNameHsDecl)]
123 getImportedInstDecls gates
124 = -- First, load any orphan-instance modules that aren't aready loaded
125 -- Orphan-instance modules are recorded in the module dependecnies
126 getIfacesRn `thenRn` \ ifaces ->
129 [mod | (mod, (True, _, False)) <- fmToList (iImpModInfo ifaces)]
131 loadOrphanModules orphan_mods `thenRn_`
133 -- Now we're ready to grab the instance declarations
134 -- Find the un-gated ones and return them,
135 -- removing them from the bag kept in Ifaces
136 getIfacesRn `thenRn` \ ifaces ->
138 (decls, new_insts) = selectGated gates (iInsts ifaces)
140 setIfacesRn (ifaces { iInsts = new_insts }) `thenRn_`
142 traceRn (sep [text "getImportedInstDecls:",
143 nest 4 (fsep (map ppr gate_list)),
144 text "Slurped" <+> int (length decls) <+> text "instance declarations",
145 nest 4 (vcat (map ppr_brief_inst_decl decls))]) `thenRn_`
148 gate_list = nameSetToList gates
150 ppr_brief_inst_decl (mod, InstD (InstDecl inst_ty _ _ _ _))
152 HsForAllTy _ _ tau -> ppr tau
155 getImportedRules :: RnMG [(Module,RdrNameHsDecl)]
157 | opt_IgnoreIfacePragmas = returnRn []
159 = getIfacesRn `thenRn` \ ifaces ->
161 gates = iSlurp ifaces -- Anything at all that's been slurped
162 rules = iRules ifaces
163 (decls, new_rules) = selectGated gates rules
168 setIfacesRn (ifaces { iRules = new_rules }) `thenRn_`
169 traceRn (sep [text "getImportedRules:",
170 text "Slurped" <+> int (length decls) <+> text "rules"]) `thenRn_`
173 selectGated gates decl_bag
174 -- Select only those decls whose gates are *all* in 'gates'
176 | opt_NoPruneDecls -- Just to try the effect of not gating at all
177 = (foldrBag (\ (_,d) ds -> d:ds) [] decl_bag, emptyBag) -- Grab them all
181 = foldrBag select ([], emptyBag) decl_bag
183 select (reqd, decl) (yes, no)
184 | isEmptyNameSet (reqd `minusNameSet` gates) = (decl:yes, no)
185 | otherwise = (yes, (reqd,decl) `consBag` no)
189 %*********************************************************
191 \subsection{Keeping track of what we've slurped, and version numbers}
193 %*********************************************************
195 getImportVersions figures out what the ``usage information'' for this
196 moudule is; that is, what it must record in its interface file as the
197 things it uses. It records:
200 \item (a) anything reachable from its body code
201 \item (b) any module exported with a @module Foo@
202 \item (c) anything reachable from an exported item
205 Why (b)? Because if @Foo@ changes then this module's export list
206 will change, so we must recompile this module at least as far as
207 making a new interface file --- but in practice that means complete
210 Why (c)? Consider this:
212 module A( f, g ) where | module B( f ) where
213 import B( f ) | f = h 3
217 Here, @B.f@ isn't used in A. Should we nevertheless record @B.f@ in
218 @A@'s usages? Our idea is that we aren't going to touch A.hi if it is
219 *identical* to what it was before. If anything about @B.f@ changes
220 than anyone who imports @A@ should be recompiled in case they use
221 @B.f@ (they'll get an early exit if they don't). So, if anything
222 about @B.f@ changes we'd better make sure that something in A.hi
223 changes, and the convenient way to do that is to record the version
224 number @B.f@ in A.hi in the usage list. If B.f changes that'll force a
225 complete recompiation of A, which is overkill but it's the only way to
226 write a new, slightly different, A.hi.
228 But the example is tricker. Even if @B.f@ doesn't change at all,
229 @B.h@ may do so, and this change may not be reflected in @f@'s version
230 number. But with -O, a module that imports A must be recompiled if
231 @B.h@ changes! So A must record a dependency on @B.h@. So we treat
232 the occurrence of @B.f@ in the export list *just as if* it were in the
233 code of A, and thereby haul in all the stuff reachable from it.
235 [NB: If B was compiled with -O, but A isn't, we should really *still*
236 haul in all the unfoldings for B, in case the module that imports A *is*
237 compiled with -O. I think this is the case.]
239 Even if B is used at all we get a usage line for B
240 import B <n> :: ... ;
241 in A.hi, to record the fact that A does import B. This is used to decide
242 to look to look for B.hi rather than B.hi-boot when compiling a module that
243 imports A. This line says that A imports B, but uses nothing in it.
244 So we'll get an early bale-out when compiling A if B's version changes.
247 mkImportInfo :: ModuleName -- Name of this module
248 -> [ImportDecl n] -- The import decls
249 -> RnMG [ImportVersion Name]
251 mkImportInfo this_mod imports
252 = getIfacesRn `thenRn` \ ifaces ->
253 getHomeIfaceTableRn `thenRn` \ hit ->
255 import_all_mods :: [ModuleName]
256 -- Modules where we imported all the names
257 -- (apart from hiding some, perhaps)
258 import_all_mods = nub [ m | ImportDecl m _ _ _ imp_list _ <- imports,
259 import_all imp_list ]
261 import_all (Just (False, _)) = False -- Imports are specified explicitly
262 import_all other = True -- Everything is imported
264 mod_map = iImpModInfo ifaces
265 imp_names = iVSlurp ifaces
268 -- mv_map groups together all the things imported from a particular module.
269 mv_map :: ModuleEnv [Name]
270 mv_map = foldr add_mv emptyModuleEnv imp_names
272 add_mv name mv_map = addItem mv_map (nameModule name) name
274 -- Build the result list by adding info for each module.
275 -- For (a) a library module, we don't record it at all unless it contains orphans
276 -- (We must never lose track of orphans.)
278 -- (b) a source-imported module, don't record the dependency at all
280 -- (b) may seem a bit strange. The idea is that the usages in a .hi file records
281 -- *all* the module's dependencies other than the loop-breakers. We use
282 -- this info in findAndReadInterface to decide whether to look for a .hi file or
285 -- This means we won't track version changes, or orphans, from .hi-boot files.
286 -- The former is potentially rather bad news. It could be fixed by recording
287 -- whether something is a boot file along with the usage info for it, but
288 -- I can't be bothered just now.
290 mk_imp_info mod_name (has_orphans, is_boot, opened) so_far
291 | mod_name == this_mod -- Check if M appears in the set of modules 'below' M
292 -- This seems like a convenient place to check
293 = WARN( not is_boot, ptext SLIT("Wierd:") <+> ppr this_mod <+>
294 ptext SLIT("imports itself (perhaps indirectly)") )
297 | not opened -- We didn't even open the interface
298 = -- This happens when a module, Foo, that we explicitly imported has
299 -- 'import Baz' in its interface file, recording that Baz is below
300 -- Foo in the module dependency hierarchy. We want to propagate this
301 -- information. The Nothing says that we didn't even open the interface
302 -- file but we must still propagate the dependency info.
303 -- The module in question must be a local module (in the same package)
304 go_for_it NothingAtAll
307 | is_lib_module && not has_orphans
310 | is_lib_module -- Record the module version only
311 = go_for_it (Everything module_vers)
314 = go_for_it whats_imported
317 go_for_it exports = (mod_name, has_orphans, is_boot, exports) : so_far
318 mod_iface = lookupTableByModName hit pit mod_name `orElse` panic "mkImportInfo"
319 mod = mi_module mod_iface
320 is_lib_module = not (isModuleInThisPackage mod)
321 version_info = mi_version mod_iface
322 version_env = vers_decls version_info
323 module_vers = vers_module version_info
325 whats_imported = Specifically module_vers
326 export_vers import_items
327 (vers_rules version_info)
329 import_items = [(n,v) | n <- lookupWithDefaultModuleEnv mv_map [] mod,
330 let v = lookupNameEnv version_env n `orElse`
331 pprPanic "mk_whats_imported" (ppr n)
333 export_vers | moduleName mod `elem` import_all_mods
334 = Just (vers_exports version_info)
338 import_info = foldFM mk_imp_info [] mod_map
340 traceRn (text "Modules in Ifaces: " <+> fsep (map ppr (keysFM mod_map))) `thenRn_`
344 addItem :: ModuleEnv [a] -> Module -> a -> ModuleEnv [a]
345 addItem fm mod x = extendModuleEnv_C add_item fm mod [x]
352 = getIfacesRn `thenRn` \ ifaces ->
353 returnRn (iSlurp ifaces)
355 recordSlurp ifaces@(Ifaces { iSlurp = slurped_names, iVSlurp = imp_names })
358 new_slurped_names = addAvailToNameSet slurped_names avail
359 new_imp_names = availName avail : imp_names
361 ifaces { iSlurp = new_slurped_names, iVSlurp = new_imp_names }
363 recordLocalSlurps local_avails
364 = getIfacesRn `thenRn` \ ifaces ->
366 new_slurped_names = foldl addAvailToNameSet (iSlurp ifaces) local_avails
368 setIfacesRn (ifaces { iSlurp = new_slurped_names })
372 %*********************************************************
374 \subsection{Getting in a declaration}
376 %*********************************************************
379 importDecl :: Name -> RnMG ImportDeclResult
381 data ImportDeclResult
385 | HereItIs (Module, RdrNameTyClDecl)
388 = -- Check if it was loaded before beginning this module
389 checkAlreadyAvailable name `thenRn` \ done ->
391 returnRn AlreadySlurped
394 -- Check if we slurped it in while compiling this module
395 getIfacesRn `thenRn` \ ifaces ->
396 if name `elemNameSet` iSlurp ifaces then
397 returnRn AlreadySlurped
400 -- Don't slurp in decls from this module's own interface file
401 -- (Indeed, this shouldn't happen.)
402 if isLocallyDefined name then
403 addWarnRn (importDeclWarn name) `thenRn_`
404 returnRn AlreadySlurped
407 -- When we find a wired-in name we must load its home
408 -- module so that we find any instance decls lurking therein
409 if name `elemNameEnv` wiredInThingEnv then
410 loadHomeInterface doc name `thenRn_`
413 else getNonWiredInDecl name
415 doc = ptext SLIT("need home module for wired in thing") <+> ppr name
417 getNonWiredInDecl :: Name -> RnMG ImportDeclResult
418 getNonWiredInDecl needed_name
419 = traceRn doc_str `thenRn_`
420 loadHomeInterface doc_str needed_name `thenRn` \ ifaces ->
421 case lookupNameEnv (iDecls ifaces) needed_name of
423 {- OMIT DEFERRED STUFF FOR NOW, TILL GHCI WORKS
424 Just (version, avail, is_tycon_name, decl@(_, TyClD (TyData DataType _ _ _ _ ncons _ _ _ _)))
425 -- This case deals with deferred import of algebraic data types
427 | not opt_NoPruneTyDecls
429 && (opt_IgnoreIfacePragmas || ncons > 1)
430 -- We only defer if imported interface pragmas are ingored
431 -- or if it's not a product type.
432 -- Sole reason: The wrapper for a strict function may need to look
433 -- inside its arg, and hence need to see its arg type's constructors.
435 && not (getUnique tycon_name `elem` cCallishTyKeys)
436 -- Never defer ccall types; we have to unbox them,
437 -- and importing them does no harm
440 -> -- OK, so we're importing a deferrable data type
441 if needed_name == tycon_name
442 -- The needed_name is the TyCon of a data type decl
443 -- Record that it's slurped, put it in the deferred set
444 -- and don't return a declaration at all
445 setIfacesRn (recordSlurp (ifaces {iDeferred = iDeferred ifaces
446 `addOneToNameSet` tycon_name})
447 version (AvailTC needed_name [needed_name])) `thenRn_`
451 -- The needed name is a constructor of a data type decl,
452 -- getting a constructor, so remove the TyCon from the deferred set
453 -- (if it's there) and return the full declaration
454 setIfacesRn (recordSlurp (ifaces {iDeferred = iDeferred ifaces
455 `delFromNameSet` tycon_name})
456 version avail) `thenRn_`
457 returnRn (HereItIs decl)
459 tycon_name = availName avail
463 -> setIfacesRn (recordSlurp ifaces avail) `thenRn_`
464 returnRn (HereItIs decl)
467 -> addErrRn (getDeclErr needed_name) `thenRn_`
468 returnRn AlreadySlurped
470 doc_str = ptext SLIT("need decl for") <+> ppr needed_name
473 getDeferredDecls :: RnMG [(Module, RdrNameHsDecl)]
475 = getIfacesRn `thenRn` \ ifaces ->
477 decls_map = iDecls ifaces
478 deferred_names = nameSetToList (iDeferred ifaces)
479 get_abstract_decl n = case lookupNameEnv decls_map n of
480 Just (_, _, _, decl) -> decl
482 traceRn (sep [text "getDeferredDecls", nest 4 (fsep (map ppr deferred_names))]) `thenRn_`
483 returnRn (map get_abstract_decl deferred_names)
487 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
488 It behaves exactly as if the wired in decl were actually in an interface file.
491 \item if the wired-in name is a data type constructor or a data constructor,
492 it brings in the type constructor and all the data constructors; and
493 marks as ``occurrences'' any free vars of the data con.
495 \item similarly for synonum type constructor
497 \item if the wired-in name is another wired-in Id, it marks as ``occurrences''
498 the free vars of the Id's type.
500 \item it loads the interface file for the wired-in thing for the
501 sole purpose of making sure that its instance declarations are available
503 All this is necessary so that we know all types that are ``in play'', so
504 that we know just what instances to bring into scope.
507 %********************************************************
509 \subsection{Checking usage information}
511 %********************************************************
513 @recompileRequired@ is called from the HscMain. It checks whether
514 a recompilation is required. It needs access to the persistent state,
515 finder, etc, because it may have to load lots of interface files to
516 check their versions.
519 type RecompileRequired = Bool
520 upToDate = False -- Recompile not required
521 outOfDate = True -- Recompile required
523 recompileRequired :: Module
524 -> Bool -- Source unchanged
525 -> Maybe ModIface -- Old interface, if any
526 -> RnMG RecompileRequired
527 recompileRequired mod source_unchanged maybe_iface
528 = traceRn (text "Considering whether compilation is required for" <+> ppr mod <> colon) `thenRn_`
530 -- CHECK WHETHER THE SOURCE HAS CHANGED
531 if not source_unchanged then
532 traceRn (nest 4 (text "Source file changed or recompilation check turned off")) `thenRn_`
536 -- CHECK WHETHER WE HAVE AN OLD IFACE
538 Nothing -> traceRn (nest 4 (ptext SLIT("No old interface file"))) `thenRn_`
541 Just iface -> -- Source code unchanged and no errors yet... carry on
542 checkList [checkModUsage u | u <- mi_usages iface]
544 checkList :: [RnMG RecompileRequired] -> RnMG RecompileRequired
545 checkList [] = returnRn upToDate
546 checkList (check:checks) = check `thenRn` \ recompile ->
554 checkModUsage :: ImportVersion Name -> RnMG RecompileRequired
555 -- Given the usage information extracted from the old
556 -- M.hi file for the module being compiled, figure out
557 -- whether M needs to be recompiled.
559 checkModUsage (mod_name, _, _, NothingAtAll)
560 -- If CurrentModule.hi contains
562 -- then that simply records that Foo lies below CurrentModule in the
563 -- hierarchy, but CurrentModule doesn't depend in any way on Foo.
564 -- In this case we don't even want to open Foo's interface.
565 = up_to_date (ptext SLIT("Nothing used from:") <+> ppr mod_name)
567 checkModUsage (mod_name, _, _, whats_imported)
568 = tryLoadInterface doc_str mod_name ImportBySystem `thenRn` \ (ifaces, maybe_err) ->
570 Just err -> out_of_date (sep [ptext SLIT("Can't find version number for module"),
572 -- Couldn't find or parse a module mentioned in the
573 -- old interface file. Don't complain -- it might just be that
574 -- the current module doesn't need that import and it's been deleted
578 getHomeIfaceTableRn `thenRn` \ hit ->
580 mod_details = lookupTableByModName hit (iPIT ifaces) mod_name
581 `orElse` panic "checkModUsage"
582 new_vers = mi_version mod_details
583 new_decl_vers = vers_decls new_vers
585 case whats_imported of { -- NothingAtAll dealt with earlier
587 Everything old_mod_vers -> checkModuleVersion old_mod_vers new_vers `thenRn` \ recompile ->
589 out_of_date (ptext SLIT("...and I needed the whole module"))
593 Specifically old_mod_vers maybe_old_export_vers old_decl_vers old_rule_vers ->
596 checkModuleVersion old_mod_vers new_vers `thenRn` \ recompile ->
597 if not recompile then
602 if checkExportList maybe_old_export_vers new_vers then
603 out_of_date (ptext SLIT("Export list changed"))
607 if old_rule_vers /= vers_rules new_vers then
608 out_of_date (ptext SLIT("Rules changed"))
611 -- CHECK ITEMS ONE BY ONE
612 checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers] `thenRn` \ recompile ->
614 returnRn outOfDate -- This one failed, so just bail out now
616 up_to_date (ptext SLIT("...but the bits I use haven't."))
620 doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
622 ------------------------
623 checkModuleVersion old_mod_vers new_vers
624 | vers_module new_vers == old_mod_vers
625 = up_to_date (ptext SLIT("Module version unchanged"))
628 = out_of_date (ptext SLIT("Module version has changed"))
630 ------------------------
631 checkExportList Nothing new_vers = upToDate
632 checkExportList (Just v) new_vers = v /= vers_exports new_vers
634 ------------------------
635 checkEntityUsage new_vers (name,old_vers)
636 = case lookupNameEnv new_vers name of
638 Nothing -> -- We used it before, but it ain't there now
639 out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
641 Just new_vers -- It's there, but is it up to date?
642 | new_vers == old_vers -> returnRn upToDate
643 | otherwise -> out_of_date (sep [ptext SLIT("Out of date:"), ppr name])
645 up_to_date msg = traceRn msg `thenRn_` returnRn upToDate
646 out_of_date msg = traceRn msg `thenRn_` returnRn outOfDate
650 %*********************************************************
654 %*********************************************************
658 = vcat [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
659 ptext SLIT("from module") <+> quotes (ppr (nameModule name))
664 "Compiler tried to import decl from interface file with same name as module."),
666 "(possible cause: module name clashes with interface file already in scope.)")
668 hsep [ptext SLIT("name:"), quotes (ppr name)]