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,
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, RdrNameInstDecl )
27 import RnHiFiles ( tryLoadInterface, loadHomeInterface, loadInterface, loadOrphanModules )
30 import Name ( Name {-instance NamedThing-}, nameOccName,
31 nameModule, isLocallyDefined,
35 import Module ( Module, ModuleEnv,
36 moduleName, isModuleInThisPackage,
37 ModuleName, WhereFrom(..),
38 emptyModuleEnv, lookupModuleEnvByName,
39 extendModuleEnv_C, lookupWithDefaultModuleEnv
42 import PrelInfo ( wiredInThingEnv )
43 import Maybes ( orElse )
52 %*********************************************************
54 \subsection{Getting what a module exports}
56 %*********************************************************
58 @getInterfaceExports@ is called only for directly-imported modules.
61 getInterfaceExports :: ModuleName -> WhereFrom -> RnMG (Module, Avails)
62 getInterfaceExports mod_name from
63 = getHomeIfaceTableRn `thenRn` \ hit ->
64 case lookupModuleEnvByName hit mod_name of {
65 Just mi -> returnRn (mi_module mi, mi_exports mi) ;
68 loadInterface doc_str mod_name from `thenRn` \ ifaces ->
69 case lookupModuleEnvByName (iPIT ifaces) mod_name of
70 Just mi -> returnRn (mi_module mi, mi_exports mi) ;
71 -- loadInterface always puts something in the map
72 -- even if it's a fake
73 Nothing -> pprPanic "getInterfaceExports" (ppr mod_name)
76 doc_str = sep [ppr mod_name, ptext SLIT("is directly imported")]
80 %*********************************************************
82 \subsection{Instance declarations are handled specially}
84 %*********************************************************
87 getImportedInstDecls :: NameSet -> RnMG [(Module,RdrNameHsDecl)]
88 getImportedInstDecls gates
89 = -- First, load any orphan-instance modules that aren't aready loaded
90 -- Orphan-instance modules are recorded in the module dependecnies
91 getIfacesRn `thenRn` \ ifaces ->
94 [mod | (mod, (True, _, False)) <- fmToList (iImpModInfo ifaces)]
96 loadOrphanModules orphan_mods `thenRn_`
98 -- Now we're ready to grab the instance declarations
99 -- Find the un-gated ones and return them,
100 -- removing them from the bag kept in Ifaces
101 getIfacesRn `thenRn` \ ifaces ->
103 (decls, new_insts) = selectGated gates (iInsts ifaces)
105 setIfacesRn (ifaces { iInsts = new_insts }) `thenRn_`
107 traceRn (sep [text "getImportedInstDecls:",
108 nest 4 (fsep (map ppr gate_list)),
109 text "Slurped" <+> int (length decls) <+> text "instance declarations",
110 nest 4 (vcat (map ppr_brief_inst_decl decls))]) `thenRn_`
113 gate_list = nameSetToList gates
115 ppr_brief_inst_decl (mod, InstD (InstDecl inst_ty _ _ _ _))
117 HsForAllTy _ _ tau -> ppr tau
120 getImportedRules :: RnMG [(Module,RdrNameHsDecl)]
122 | opt_IgnoreIfacePragmas = returnRn []
124 = getIfacesRn `thenRn` \ ifaces ->
126 gates = iSlurp ifaces -- Anything at all that's been slurped
127 rules = iRules ifaces
128 (decls, new_rules) = selectGated gates rules
133 setIfacesRn (ifaces { iRules = new_rules }) `thenRn_`
134 traceRn (sep [text "getImportedRules:",
135 text "Slurped" <+> int (length decls) <+> text "rules"]) `thenRn_`
138 selectGated gates decl_bag
139 -- Select only those decls whose gates are *all* in 'gates'
141 | opt_NoPruneDecls -- Just to try the effect of not gating at all
142 = (foldrBag (\ (_,d) ds -> d:ds) [] decl_bag, emptyBag) -- Grab them all
146 = foldrBag select ([], emptyBag) decl_bag
148 select (reqd, decl) (yes, no)
149 | isEmptyNameSet (reqd `minusNameSet` gates) = (decl:yes, no)
150 | otherwise = (yes, (reqd,decl) `consBag` no)
152 lookupFixityRn :: Name -> RnMS Fixity
154 | isLocallyDefined name
155 = getFixityEnv `thenRn` \ local_fix_env ->
156 returnRn (lookupLocalFixity local_fix_env name)
158 | otherwise -- Imported
159 -- For imported names, we have to get their fixities by doing a loadHomeInterface,
160 -- and consulting the Ifaces that comes back from that, because the interface
161 -- file for the Name might not have been loaded yet. Why not? Suppose you import module A,
162 -- which exports a function 'f', which is defined in module B. Then B isn't loaded
163 -- right away (after all, it's possible that nothing from B will be used).
164 -- When we come across a use of 'f', we need to know its fixity, and it's then,
165 -- and only then, that we load B.hi. That is what's happening here.
166 = getHomeIfaceTableRn `thenRn` \ hit ->
167 loadHomeInterface doc name `thenRn` \ ifaces ->
168 case lookupTable hit (iPIT ifaces) name of
169 Just iface -> returnRn (lookupNameEnv (mi_fixities iface) name `orElse` defaultFixity)
170 Nothing -> returnRn defaultFixity
172 doc = ptext SLIT("Checking fixity for") <+> ppr name
176 %*********************************************************
178 \subsection{Keeping track of what we've slurped, and version numbers}
180 %*********************************************************
182 getImportVersions figures out what the ``usage information'' for this
183 moudule is; that is, what it must record in its interface file as the
184 things it uses. It records:
187 \item (a) anything reachable from its body code
188 \item (b) any module exported with a @module Foo@
189 \item (c) anything reachable from an exported item
192 Why (b)? Because if @Foo@ changes then this module's export list
193 will change, so we must recompile this module at least as far as
194 making a new interface file --- but in practice that means complete
197 Why (c)? Consider this:
199 module A( f, g ) where | module B( f ) where
200 import B( f ) | f = h 3
204 Here, @B.f@ isn't used in A. Should we nevertheless record @B.f@ in
205 @A@'s usages? Our idea is that we aren't going to touch A.hi if it is
206 *identical* to what it was before. If anything about @B.f@ changes
207 than anyone who imports @A@ should be recompiled in case they use
208 @B.f@ (they'll get an early exit if they don't). So, if anything
209 about @B.f@ changes we'd better make sure that something in A.hi
210 changes, and the convenient way to do that is to record the version
211 number @B.f@ in A.hi in the usage list. If B.f changes that'll force a
212 complete recompiation of A, which is overkill but it's the only way to
213 write a new, slightly different, A.hi.
215 But the example is tricker. Even if @B.f@ doesn't change at all,
216 @B.h@ may do so, and this change may not be reflected in @f@'s version
217 number. But with -O, a module that imports A must be recompiled if
218 @B.h@ changes! So A must record a dependency on @B.h@. So we treat
219 the occurrence of @B.f@ in the export list *just as if* it were in the
220 code of A, and thereby haul in all the stuff reachable from it.
222 [NB: If B was compiled with -O, but A isn't, we should really *still*
223 haul in all the unfoldings for B, in case the module that imports A *is*
224 compiled with -O. I think this is the case.]
226 Even if B is used at all we get a usage line for B
227 import B <n> :: ... ;
228 in A.hi, to record the fact that A does import B. This is used to decide
229 to look to look for B.hi rather than B.hi-boot when compiling a module that
230 imports A. This line says that A imports B, but uses nothing in it.
231 So we'll get an early bale-out when compiling A if B's version changes.
234 mkImportInfo :: ModuleName -- Name of this module
235 -> [ImportDecl n] -- The import decls
236 -> RnMG [ImportVersion Name]
238 mkImportInfo this_mod imports
239 = getIfacesRn `thenRn` \ ifaces ->
240 getHomeIfaceTableRn `thenRn` \ hit ->
242 import_all_mods :: [ModuleName]
243 -- Modules where we imported all the names
244 -- (apart from hiding some, perhaps)
245 import_all_mods = nub [ m | ImportDecl m _ _ _ imp_list _ <- imports,
246 import_all imp_list ]
248 import_all (Just (False, _)) = False -- Imports are specified explicitly
249 import_all other = True -- Everything is imported
251 mod_map = iImpModInfo ifaces
252 imp_names = iVSlurp ifaces
255 -- mv_map groups together all the things imported from a particular module.
256 mv_map :: ModuleEnv [Name]
257 mv_map = foldr add_mv emptyModuleEnv imp_names
259 add_mv name mv_map = addItem mv_map (nameModule name) name
261 -- Build the result list by adding info for each module.
262 -- For (a) a library module, we don't record it at all unless it contains orphans
263 -- (We must never lose track of orphans.)
265 -- (b) a source-imported module, don't record the dependency at all
267 -- (b) may seem a bit strange. The idea is that the usages in a .hi file records
268 -- *all* the module's dependencies other than the loop-breakers. We use
269 -- this info in findAndReadInterface to decide whether to look for a .hi file or
272 -- This means we won't track version changes, or orphans, from .hi-boot files.
273 -- The former is potentially rather bad news. It could be fixed by recording
274 -- whether something is a boot file along with the usage info for it, but
275 -- I can't be bothered just now.
277 mk_imp_info mod_name (has_orphans, is_boot, opened) so_far
278 | mod_name == this_mod -- Check if M appears in the set of modules 'below' M
279 -- This seems like a convenient place to check
280 = WARN( not is_boot, ptext SLIT("Wierd:") <+> ppr this_mod <+>
281 ptext SLIT("imports itself (perhaps indirectly)") )
284 | not opened -- We didn't even open the interface
285 = -- This happens when a module, Foo, that we explicitly imported has
286 -- 'import Baz' in its interface file, recording that Baz is below
287 -- Foo in the module dependency hierarchy. We want to propagate this
288 -- information. The Nothing says that we didn't even open the interface
289 -- file but we must still propagate the dependency info.
290 -- The module in question must be a local module (in the same package)
291 go_for_it NothingAtAll
294 | is_lib_module && not has_orphans
297 | is_lib_module -- Record the module version only
298 = go_for_it (Everything module_vers)
301 = go_for_it whats_imported
304 go_for_it exports = (mod_name, has_orphans, is_boot, exports) : so_far
305 mod_iface = lookupTableByModName hit pit mod_name `orElse` panic "mkImportInfo"
306 mod = mi_module mod_iface
307 is_lib_module = not (isModuleInThisPackage mod)
308 version_info = mi_version mod_iface
309 version_env = vers_decls version_info
310 module_vers = vers_module version_info
312 whats_imported = Specifically module_vers
313 export_vers import_items
314 (vers_rules version_info)
316 import_items = [(n,v) | n <- lookupWithDefaultModuleEnv mv_map [] mod,
317 let v = lookupNameEnv version_env n `orElse`
318 pprPanic "mk_whats_imported" (ppr n)
320 export_vers | moduleName mod `elem` import_all_mods
321 = Just (vers_exports version_info)
325 import_info = foldFM mk_imp_info [] mod_map
327 traceRn (text "Modules in Ifaces: " <+> fsep (map ppr (keysFM mod_map))) `thenRn_`
331 addItem :: ModuleEnv [a] -> Module -> a -> ModuleEnv [a]
332 addItem fm mod x = extendModuleEnv_C add_item fm mod [x]
339 = getIfacesRn `thenRn` \ ifaces ->
340 returnRn (iSlurp ifaces)
342 recordSlurp ifaces@(Ifaces { iSlurp = slurped_names, iVSlurp = imp_names })
345 new_slurped_names = addAvailToNameSet slurped_names avail
346 new_imp_names = availName avail : imp_names
348 ifaces { iSlurp = new_slurped_names, iVSlurp = new_imp_names }
350 recordLocalSlurps local_avails
351 = getIfacesRn `thenRn` \ ifaces ->
353 new_slurped_names = foldl addAvailToNameSet (iSlurp ifaces) local_avails
355 setIfacesRn (ifaces { iSlurp = new_slurped_names })
359 %*********************************************************
361 \subsection{Getting in a declaration}
363 %*********************************************************
366 importDecl :: Name -> RnMG ImportDeclResult
368 data ImportDeclResult
372 | HereItIs (Module, RdrNameHsDecl)
375 = -- Check if it was loaded before beginning this module
376 checkAlreadyAvailable name `thenRn` \ done ->
378 returnRn AlreadySlurped
381 -- Check if we slurped it in while compiling this module
382 getIfacesRn `thenRn` \ ifaces ->
383 if name `elemNameSet` iSlurp ifaces then
384 returnRn AlreadySlurped
387 -- Don't slurp in decls from this module's own interface file
388 -- (Indeed, this shouldn't happen.)
389 if isLocallyDefined name then
390 addWarnRn (importDeclWarn name) `thenRn_`
391 returnRn AlreadySlurped
394 -- When we find a wired-in name we must load its home
395 -- module so that we find any instance decls lurking therein
396 if name `elemNameEnv` wiredInThingEnv then
397 loadHomeInterface doc name `thenRn_`
400 else getNonWiredInDecl name
402 doc = ptext SLIT("need home module for wired in thing") <+> ppr name
404 getNonWiredInDecl :: Name -> RnMG ImportDeclResult
405 getNonWiredInDecl needed_name
406 = traceRn doc_str `thenRn_`
407 loadHomeInterface doc_str needed_name `thenRn` \ ifaces ->
408 case lookupNameEnv (iDecls ifaces) needed_name of
410 {- OMIT DEFERRED STUFF FOR NOW, TILL GHCI WORKS
411 Just (version, avail, is_tycon_name, decl@(_, TyClD (TyData DataType _ _ _ _ ncons _ _ _ _)))
412 -- This case deals with deferred import of algebraic data types
414 | not opt_NoPruneTyDecls
416 && (opt_IgnoreIfacePragmas || ncons > 1)
417 -- We only defer if imported interface pragmas are ingored
418 -- or if it's not a product type.
419 -- Sole reason: The wrapper for a strict function may need to look
420 -- inside its arg, and hence need to see its arg type's constructors.
422 && not (getUnique tycon_name `elem` cCallishTyKeys)
423 -- Never defer ccall types; we have to unbox them,
424 -- and importing them does no harm
427 -> -- OK, so we're importing a deferrable data type
428 if needed_name == tycon_name
429 -- The needed_name is the TyCon of a data type decl
430 -- Record that it's slurped, put it in the deferred set
431 -- and don't return a declaration at all
432 setIfacesRn (recordSlurp (ifaces {iDeferred = iDeferred ifaces
433 `addOneToNameSet` tycon_name})
434 version (AvailTC needed_name [needed_name])) `thenRn_`
438 -- The needed name is a constructor of a data type decl,
439 -- getting a constructor, so remove the TyCon from the deferred set
440 -- (if it's there) and return the full declaration
441 setIfacesRn (recordSlurp (ifaces {iDeferred = iDeferred ifaces
442 `delFromNameSet` tycon_name})
443 version avail) `thenRn_`
444 returnRn (HereItIs decl)
446 tycon_name = availName avail
450 -> setIfacesRn (recordSlurp ifaces avail) `thenRn_`
451 returnRn (HereItIs decl)
454 -> addErrRn (getDeclErr needed_name) `thenRn_`
455 returnRn AlreadySlurped
457 doc_str = ptext SLIT("need decl for") <+> ppr needed_name
460 getDeferredDecls :: RnMG [(Module, RdrNameHsDecl)]
462 = getIfacesRn `thenRn` \ ifaces ->
464 decls_map = iDecls ifaces
465 deferred_names = nameSetToList (iDeferred ifaces)
466 get_abstract_decl n = case lookupNameEnv decls_map n of
467 Just (_, _, _, decl) -> decl
469 traceRn (sep [text "getDeferredDecls", nest 4 (fsep (map ppr deferred_names))]) `thenRn_`
470 returnRn (map get_abstract_decl deferred_names)
474 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
475 It behaves exactly as if the wired in decl were actually in an interface file.
478 \item if the wired-in name is a data type constructor or a data constructor,
479 it brings in the type constructor and all the data constructors; and
480 marks as ``occurrences'' any free vars of the data con.
482 \item similarly for synonum type constructor
484 \item if the wired-in name is another wired-in Id, it marks as ``occurrences''
485 the free vars of the Id's type.
487 \item it loads the interface file for the wired-in thing for the
488 sole purpose of making sure that its instance declarations are available
490 All this is necessary so that we know all types that are ``in play'', so
491 that we know just what instances to bring into scope.
494 %********************************************************
496 \subsection{Checking usage information}
498 %********************************************************
500 @recompileRequired@ is called from the HscMain. It checks whether
501 a recompilation is required. It needs access to the persistent state,
502 finder, etc, because it may have to load lots of interface files to
503 check their versions.
506 type RecompileRequired = Bool
507 upToDate = False -- Recompile not required
508 outOfDate = True -- Recompile required
510 recompileRequired :: DynFlags -> Finder
511 -> HomeIfaceTable -> HomeSymbolTable
512 -> PersistentCompilerState
514 -> Bool -- Source unchanged
515 -> Maybe ModIface -- Old interface, if any
516 -> IO (PersistentCompilerState, Bool, RecompileRequired)
517 -- True <=> errors happened
518 recompileRequired dflags finder hit hst pcs mod source_unchanged maybe_iface
519 = initRn dflags finder hit hst pcs mod $
520 traceRn (text "Considering whether compilation is required for" <+> ppr mod <> colon) `thenRn_`
522 -- CHECK WHETHER THE SOURCE HAS CHANGED
523 if not source_unchanged then
524 traceRn (nest 4 (text "Source file changed or recompilation check turned off")) `thenRn_`
528 -- CHECK WHETHER WE HAVE AN OLD IFACE
530 Nothing -> traceRn (nest 4 (ptext SLIT("No old interface file"))) `thenRn_`
533 Just iface -> -- Source code unchanged and no errors yet... carry on
534 checkList [checkModUsage u | u <- mi_usages iface]
536 checkList :: [RnMG RecompileRequired] -> RnMG RecompileRequired
537 checkList [] = returnRn upToDate
538 checkList (check:checks) = check `thenRn` \ recompile ->
546 checkModUsage :: ImportVersion Name -> RnMG RecompileRequired
547 -- Given the usage information extracted from the old
548 -- M.hi file for the module being compiled, figure out
549 -- whether M needs to be recompiled.
551 checkModUsage (mod_name, _, _, NothingAtAll)
552 -- If CurrentModule.hi contains
554 -- then that simply records that Foo lies below CurrentModule in the
555 -- hierarchy, but CurrentModule doesn't depend in any way on Foo.
556 -- In this case we don't even want to open Foo's interface.
557 = up_to_date (ptext SLIT("Nothing used from:") <+> ppr mod_name)
559 checkModUsage (mod_name, _, _, whats_imported)
560 = tryLoadInterface doc_str mod_name ImportBySystem `thenRn` \ (ifaces, maybe_err) ->
562 Just err -> out_of_date (sep [ptext SLIT("Can't find version number for module"),
564 -- Couldn't find or parse a module mentioned in the
565 -- old interface file. Don't complain -- it might just be that
566 -- the current module doesn't need that import and it's been deleted
570 getHomeIfaceTableRn `thenRn` \ hit ->
572 mod_details = lookupTableByModName hit (iPIT ifaces) mod_name
573 `orElse` panic "checkModUsage"
574 new_vers = mi_version mod_details
575 new_decl_vers = vers_decls new_vers
577 case whats_imported of { -- NothingAtAll dealt with earlier
579 Everything old_mod_vers -> checkModuleVersion old_mod_vers new_vers `thenRn` \ recompile ->
581 out_of_date (ptext SLIT("...and I needed the whole module"))
585 Specifically old_mod_vers maybe_old_export_vers old_decl_vers old_rule_vers ->
588 checkModuleVersion old_mod_vers new_vers `thenRn` \ recompile ->
589 if not recompile then
594 if checkExportList maybe_old_export_vers new_vers then
595 out_of_date (ptext SLIT("Export list changed"))
599 if old_rule_vers /= vers_rules new_vers then
600 out_of_date (ptext SLIT("Rules changed"))
603 -- CHECK ITEMS ONE BY ONE
604 checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers] `thenRn` \ recompile ->
606 returnRn outOfDate -- This one failed, so just bail out now
608 up_to_date (ptext SLIT("...but the bits I use haven't."))
612 doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
614 ------------------------
615 checkModuleVersion old_mod_vers new_vers
616 | vers_module new_vers == old_mod_vers
617 = up_to_date (ptext SLIT("Module version unchanged"))
620 = out_of_date (ptext SLIT("Module version has changed"))
622 ------------------------
623 checkExportList Nothing new_vers = upToDate
624 checkExportList (Just v) new_vers = v /= vers_exports new_vers
626 ------------------------
627 checkEntityUsage new_vers (name,old_vers)
628 = case lookupNameEnv new_vers name of
630 Nothing -> -- We used it before, but it ain't there now
631 out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
633 Just new_vers -- It's there, but is it up to date?
634 | new_vers == old_vers -> returnRn upToDate
635 | otherwise -> out_of_date (sep [ptext SLIT("Out of date:"), ppr name])
637 up_to_date msg = traceRn msg `thenRn_` returnRn upToDate
638 out_of_date msg = traceRn msg `thenRn_` returnRn outOfDate
642 %*********************************************************
646 %*********************************************************
650 = vcat [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
651 ptext SLIT("from module") <+> quotes (ppr (nameModule name))
656 "Compiler tried to import decl from interface file with same name as module."),
658 "(possible cause: module name clashes with interface file already in scope.)")
660 hsep [ptext SLIT("name:"), quotes (ppr name)]