[project @ 2000-10-25 15:57:33 by simonpj]
[ghc-hetmet.git] / ghc / compiler / rename / RnIfaces.lhs
index b6f4521..a56da3b 100644 (file)
 %
-% (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
+% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
 %
 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
 
 \begin{code}
-#include "HsVersions.h"
-
-module RnIfaces (
+module RnIfaces
+     (
        getInterfaceExports,
-       getImportedInstDecls,
-       getSpecialInstModules,
-       getDecl, getWiredInDecl,
-       getImportVersions,
-
-       checkUpToDate,
+       recordLocalSlurps, 
+       mkImportInfo, 
 
-       getDeclBinders,
-       mkSearchPath
-    ) where
+       slurpImpDecls, closeDecls,
 
-IMP_Ubiq()
+       RecompileRequired, outOfDate, upToDate, recompileRequired
+       )
+where
 
+#include "HsVersions.h"
 
-import HsSyn           ( HsDecl(..), TyDecl(..), ClassDecl(..), HsTyVar, Bind, HsExpr, Sig(..), 
-                         HsBinds(..), MonoBinds, DefaultDecl, ConDecl(..), HsType, BangType, IfaceSig(..),
-                         FixityDecl(..), Fixity, Fake, InPat, InstDecl(..), SYN_IE(Version), HsIdInfo
+import CmdLineOpts     ( DynFlags, opt_NoPruneDecls, opt_NoPruneTyDecls, opt_IgnoreIfacePragmas )
+import HscTypes
+import HsSyn           ( HsDecl(..), Sig(..), TyClDecl(..), ConDecl(..), ConDetails(..),
+                         InstDecl(..), HsType(..), hsTyVarNames, getBangType
                        )
-import HsPragmas       ( noGenPragmas )
-import RdrHsSyn                ( SYN_IE(RdrNameHsDecl), SYN_IE(RdrNameInstDecl), 
-                         RdrName, rdrNameOcc
+import HsImpExp                ( ImportDecl(..) )
+import RdrHsSyn                ( RdrNameHsDecl, RdrNameTyClDecl, RdrNameInstDecl )
+import RnHsSyn         ( RenamedHsDecl, extractHsTyNames, extractHsCtxtTyNames, tyClDeclFVs )
+import RnHiFiles       ( tryLoadInterface, loadHomeInterface, loadInterface, 
+                         loadOrphanModules
                        )
-import RnEnv           ( newGlobalName, lookupRn, addImplicitOccsRn, availNames )
-import RnSource                ( rnHsType )
+import RnSource                ( rnTyClDecl, rnDecl )
+import RnEnv
 import RnMonad
-import ParseIface      ( parseIface )
-
-import ErrUtils                ( SYN_IE(Error), SYN_IE(Warning) )
-import FiniteMap       ( FiniteMap, emptyFM, unitFM, lookupFM, addToFM, addListToFM, fmToList )
-import Name            ( Name {-instance NamedThing-}, Provenance, OccName(..),
-                         modAndOcc, occNameString, moduleString, pprModule,
-                         NameSet(..), emptyNameSet, unionNameSets, nameSetToList,
-                         minusNameSet, mkNameSet,
-                         isWiredInName, maybeWiredInTyConName, maybeWiredInIdName
-                        )
-import Id              ( GenId, Id(..), idType, dataConTyCon, isDataCon )
-import TyCon           ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
+import Id              ( idType )
 import Type            ( namesOfType )
-import TyVar           ( GenTyVar )
-import SrcLoc          ( mkIfaceSrcLoc )
-import PrelMods                ( gHC__ )
+import TyCon           ( isSynTyCon, getSynTyConDefn )
+import Name            ( Name {-instance NamedThing-}, nameOccName,
+                         nameModule, isLocallyDefined, nameUnique,
+                         NamedThing(..),
+                         elemNameEnv
+                        )
+import Module          ( Module, ModuleEnv,
+                         moduleName, isModuleInThisPackage,
+                         ModuleName, WhereFrom(..),
+                         emptyModuleEnv, lookupModuleEnvByName,
+                         extendModuleEnv_C, lookupWithDefaultModuleEnv
+                       )
+import NameSet
+import PrelInfo                ( wiredInThingEnv, fractionalClassKeys )
+import TysWiredIn      ( doubleTyCon )
+import Maybes          ( orElse )
+import FiniteMap
+import Outputable
 import Bag
-import Maybes          ( MaybeErr(..), expectJust, maybeToBool )
-import ListSetOps      ( unionLists )
-import Pretty
-import PprStyle                ( PprStyle(..) )
-import Util            ( pprPanic )
+
+import List            ( nub )
 \end{code}
 
 
+%*********************************************************
+%*                                                     *
+\subsection{Getting what a module exports}
+%*                                                     *
+%*********************************************************
+
+@getInterfaceExports@ is called only for directly-imported modules.
+
+\begin{code}
+getInterfaceExports :: ModuleName -> WhereFrom -> RnMG (Module, [(ModuleName,Avails)])
+getInterfaceExports mod_name from
+  = getHomeIfaceTableRn                `thenRn` \ hit ->
+    case lookupModuleEnvByName hit mod_name of {
+       Just mi -> returnRn (mi_module mi, mi_exports mi) ;
+        Nothing  -> 
+
+    loadInterface doc_str mod_name from        `thenRn` \ ifaces ->
+    case lookupModuleEnvByName (iPIT ifaces) mod_name of
+       Just mi -> returnRn (mi_module mi, mi_exports mi) ;
+               -- loadInterface always puts something in the map
+               -- even if it's a fake
+       Nothing -> pprPanic "getInterfaceExports" (ppr mod_name)
+    }
+    where
+      doc_str = sep [ppr mod_name, ptext SLIT("is directly imported")]
+\end{code}
+
 
 %*********************************************************
 %*                                                     *
-\subsection{Loading a new interface file}
+\subsection{Instance declarations are handled specially}
 %*                                                     *
 %*********************************************************
 
 \begin{code}
-loadInterface :: Pretty -> Module -> RnMG Ifaces
-loadInterface doc_str load_mod 
-  = getIfacesRn                `thenRn` \ ifaces ->
+getImportedInstDecls :: NameSet -> RnMG [(Module,RdrNameHsDecl)]
+getImportedInstDecls gates
+  =            -- First, load any orphan-instance modules that aren't aready loaded
+       -- Orphan-instance modules are recorded in the module dependecnies
+    getIfacesRn                                        `thenRn` \ ifaces ->
     let
-       Ifaces this_mod mod_vers_map export_env_map vers_map decls_map inst_map inst_mods = ifaces
+       orphan_mods =
+         [mod | (mod, (True, _, False)) <- fmToList (iImpModInfo ifaces)]
     in
-       -- CHECK WHETHER WE HAVE IT ALREADY
-    if maybeToBool (lookupFM export_env_map load_mod) 
-    then
-       returnRn ifaces         -- Already in the cache; don't re-read it
-    else
+    loadOrphanModules orphan_mods                      `thenRn_` 
 
-       -- READ THE MODULE IN
-    findAndReadIface doc_str load_mod          `thenRn` \ read_result ->
-    case read_result of {
-       -- Check for not found
-       Nothing ->      -- Not found, so add an empty export env to the Ifaces map
-                       -- so that we don't look again
-                  let
-                       new_export_env_map = addToFM export_env_map load_mod ([],[])
-                       new_ifaces = Ifaces this_mod mod_vers_map 
-                                           new_export_env_map 
-                                           vers_map decls_map inst_map inst_mods
-                  in
-                  setIfacesRn new_ifaces               `thenRn_`
-                  failWithRn new_ifaces (noIfaceErr load_mod) ;
-
-       -- Found and parsed!
-       Just (ParsedIface _ mod_vers usages exports rd_inst_mods fixs decls insts) ->
-
-       -- LOAD IT INTO Ifaces
-    mapRn loadExport exports                                   `thenRn` \ avails_s ->
-    foldlRn (loadDecl load_mod) (decls_map,vers_map) decls     `thenRn` \ (new_decls_map, new_vers_map) ->
-    foldlRn (loadInstDecl load_mod) inst_map insts             `thenRn` \ new_insts_map ->
+       -- Now we're ready to grab the instance declarations
+       -- Find the un-gated ones and return them, 
+       -- removing them from the bag kept in Ifaces
+    getIfacesRn                                        `thenRn` \ ifaces ->
     let
-        export_env = (concat avails_s, fixs)
-
-                       -- Exclude this module from the "special-inst" modules
-        new_inst_mods = inst_mods `unionLists` (filter (/= this_mod) rd_inst_mods)
-
-        new_ifaces = Ifaces this_mod
-                            (addToFM mod_vers_map load_mod mod_vers)
-                            (addToFM export_env_map load_mod export_env)
-                            new_vers_map
-                            new_decls_map
-                            new_insts_map
-                            new_inst_mods 
+       (decls, new_insts) = selectGated gates (iInsts ifaces)
     in
-    setIfacesRn new_ifaces             `thenRn_`
-    returnRn new_ifaces
-    }
+    setIfacesRn (ifaces { iInsts = new_insts })                `thenRn_`
 
-loadExport :: ExportItem -> RnMG [AvailInfo]
-loadExport (mod, entities)
-  = mapRn load_entity entities
+    traceRn (sep [text "getImportedInstDecls:", 
+                 nest 4 (fsep (map ppr gate_list)),
+                 text "Slurped" <+> int (length decls) <+> text "instance declarations",
+                 nest 4 (vcat (map ppr_brief_inst_decl decls))])       `thenRn_`
+    returnRn decls
   where
-    new_name occ = newGlobalName mod occ
-
-    load_entity (occ, occs)
-      =        new_name occ            `thenRn` \ name ->
-        mapRn new_name occs    `thenRn` \ names ->
-        returnRn (Avail name names)
-
-loadVersion :: Module -> VersionMap -> (OccName,Version) -> RnMG VersionMap
-loadVersion mod vers_map (occ, version)
-  = newGlobalName mod occ                      `thenRn` \ name ->
-    returnRn (addToFM vers_map name version)
-
-
-loadDecl :: Module -> (DeclsMap, VersionMap)
-        -> (Version, RdrNameHsDecl)
-        -> RnMG (DeclsMap, VersionMap)
-loadDecl mod (decls_map, vers_map) (version, decl)
-  = getDeclBinders new_implicit_name decl      `thenRn` \ avail@(Avail name _) ->
-    returnRn (addListToFM decls_map
-                         [(name,(avail,decl)) | name <- availNames avail],
-             addToFM vers_map name version
-    )
+    gate_list      = nameSetToList gates
+
+ppr_brief_inst_decl (mod, InstD (InstDecl inst_ty _ _ _ _))
+  = case inst_ty of
+       HsForAllTy _ _ tau -> ppr tau
+       other              -> ppr inst_ty
+
+getImportedRules :: RnMG [(Module,RdrNameHsDecl)]
+getImportedRules 
+  | opt_IgnoreIfacePragmas = returnRn []
+  | otherwise
+  = getIfacesRn        `thenRn` \ ifaces ->
+    let
+       gates              = iSlurp ifaces      -- Anything at all that's been slurped
+       rules              = iRules ifaces
+       (decls, new_rules) = selectGated gates rules
+    in
+    if null decls then
+       returnRn []
+    else
+    setIfacesRn (ifaces { iRules = new_rules })                     `thenRn_`
+    traceRn (sep [text "getImportedRules:", 
+                 text "Slurped" <+> int (length decls) <+> text "rules"])   `thenRn_`
+    returnRn decls
+
+selectGated gates decl_bag
+       -- Select only those decls whose gates are *all* in 'gates'
+#ifdef DEBUG
+  | opt_NoPruneDecls   -- Just to try the effect of not gating at all
+  = (foldrBag (\ (_,d) ds -> d:ds) [] decl_bag, emptyBag)      -- Grab them all
+
+  | otherwise
+#endif
+  = foldrBag select ([], emptyBag) decl_bag
   where
-    new_implicit_name rdr_name loc = newGlobalName mod (rdrNameOcc rdr_name)
+    select (reqd, decl) (yes, no)
+       | isEmptyNameSet (reqd `minusNameSet` gates) = (decl:yes, no)
+       | otherwise                                  = (yes,      (reqd,decl) `consBag` no)
+\end{code}
+
+
+%*********************************************************
+%*                                                     *
+\subsection{Keeping track of what we've slurped, and version numbers}
+%*                                                     *
+%*********************************************************
+
+getImportVersions figures out what the ``usage information'' for this
+moudule is; that is, what it must record in its interface file as the
+things it uses.  It records:
+
+\begin{itemize}
+\item  (a) anything reachable from its body code
+\item  (b) any module exported with a @module Foo@
+\item   (c) anything reachable from an exported item
+\end{itemize}
+
+Why (b)?  Because if @Foo@ changes then this module's export list
+will change, so we must recompile this module at least as far as
+making a new interface file --- but in practice that means complete
+recompilation.
+
+Why (c)?  Consider this:
+\begin{verbatim}
+       module A( f, g ) where  |       module B( f ) where
+         import B( f )         |         f = h 3
+         g = ...               |         h = ...
+\end{verbatim}
+
+Here, @B.f@ isn't used in A.  Should we nevertheless record @B.f@ in
+@A@'s usages?  Our idea is that we aren't going to touch A.hi if it is
+*identical* to what it was before.  If anything about @B.f@ changes
+than anyone who imports @A@ should be recompiled in case they use
+@B.f@ (they'll get an early exit if they don't).  So, if anything
+about @B.f@ changes we'd better make sure that something in A.hi
+changes, and the convenient way to do that is to record the version
+number @B.f@ in A.hi in the usage list.  If B.f changes that'll force a
+complete recompiation of A, which is overkill but it's the only way to 
+write a new, slightly different, A.hi.
+
+But the example is tricker.  Even if @B.f@ doesn't change at all,
+@B.h@ may do so, and this change may not be reflected in @f@'s version
+number.  But with -O, a module that imports A must be recompiled if
+@B.h@ changes!  So A must record a dependency on @B.h@.  So we treat
+the occurrence of @B.f@ in the export list *just as if* it were in the
+code of A, and thereby haul in all the stuff reachable from it.
+
+[NB: If B was compiled with -O, but A isn't, we should really *still*
+haul in all the unfoldings for B, in case the module that imports A *is*
+compiled with -O.  I think this is the case.]
+
+Even if B is used at all we get a usage line for B
+       import B <n> :: ... ;
+in A.hi, to record the fact that A does import B.  This is used to decide
+to look to look for B.hi rather than B.hi-boot when compiling a module that
+imports A.  This line says that A imports B, but uses nothing in it.
+So we'll get an early bale-out when compiling A if B's version changes.
 
-loadInstDecl :: Module -> Bag IfaceInst -> RdrNameInstDecl -> RnMG (Bag IfaceInst)
-loadInstDecl mod_name insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
-  = initRnMS emptyRnEnv mod_name InterfaceMode $
+\begin{code}
+mkImportInfo :: ModuleName                     -- Name of this module
+            -> [ImportDecl n]                  -- The import decls
+            -> RnMG [ImportVersion Name]
 
-       -- Find out what type constructors and classes are mentioned in the
-       -- instance declaration.  We have to be a bit clever.
+mkImportInfo this_mod imports
+  = getIfacesRn                                        `thenRn` \ ifaces ->
+    getHomeIfaceTableRn                                `thenRn` \ hit -> 
+    let
+       import_all_mods :: [ModuleName]
+               -- Modules where we imported all the names
+               -- (apart from hiding some, perhaps)
+       import_all_mods = nub [ m | ImportDecl m _ _ _ imp_list _ <- imports,
+                                   import_all imp_list ]
+
+       import_all (Just (False, _)) = False    -- Imports are specified explicitly
+       import_all other             = True     -- Everything is imported
+
+       mod_map   = iImpModInfo ifaces
+       imp_names = iVSlurp     ifaces
+       pit       = iPIT        ifaces
+
+       -- mv_map groups together all the things imported from a particular module.
+       mv_map :: ModuleEnv [Name]
+       mv_map = foldr add_mv emptyModuleEnv imp_names
+
+        add_mv name mv_map = addItem mv_map (nameModule name) name
+
+       -- Build the result list by adding info for each module.
+       -- For (a) a library module, we don't record it at all unless it contains orphans
+       --         (We must never lose track of orphans.)
+       -- 
+       --     (b) a source-imported module, don't record the dependency at all
+       --      
+       -- (b) may seem a bit strange.  The idea is that the usages in a .hi file records
+       -- *all* the module's dependencies other than the loop-breakers.  We use
+       -- this info in findAndReadInterface to decide whether to look for a .hi file or
+       -- a .hi-boot file.  
        --
-       -- We want to rename the type so that we can find what
-       -- (free) type constructors are inside it.  But we must *not* thereby
-       -- put new occurrences into the global pool because otherwise we'll force
-       -- them all to be loaded.  We kill two birds with ones stone by renaming
-       -- with a fresh occurrence pool.
-    findOccurrencesRn (rnHsType inst_ty)       `thenRn` \ ty_names ->
-
-    returnRn ((ty_names, mod_name, decl) `consBag` insts)
+       -- This means we won't track version changes, or orphans, from .hi-boot files.
+       -- The former is potentially rather bad news.  It could be fixed by recording
+       -- whether something is a boot file along with the usage info for it, but 
+       -- I can't be bothered just now.
+
+       mk_imp_info mod_name (has_orphans, is_boot, opened) so_far
+          | mod_name == this_mod       -- Check if M appears in the set of modules 'below' M
+                                       -- This seems like a convenient place to check
+          = WARN( not is_boot, ptext SLIT("Wierd:") <+> ppr this_mod <+> 
+                               ptext SLIT("imports itself (perhaps indirectly)") )
+            so_far
+          | not opened                 -- We didn't even open the interface
+          =            -- This happens when a module, Foo, that we explicitly imported has 
+                       -- 'import Baz' in its interface file, recording that Baz is below
+                       -- Foo in the module dependency hierarchy.  We want to propagate this
+                       -- information.  The Nothing says that we didn't even open the interface
+                       -- file but we must still propagate the dependency info.
+                       -- The module in question must be a local module (in the same package)
+            go_for_it NothingAtAll
+
+
+          | is_lib_module && not has_orphans
+          = so_far             
+          
+          | is_lib_module                      -- Record the module version only
+          = go_for_it (Everything module_vers)
+
+          | otherwise
+          = go_for_it whats_imported
+
+            where
+               go_for_it exports = (mod_name, has_orphans, is_boot, exports) : so_far
+               mod_iface         = lookupTableByModName hit pit mod_name `orElse` panic "mkImportInfo"
+               mod               = mi_module mod_iface
+               is_lib_module     = not (isModuleInThisPackage mod)
+               version_info      = mi_version mod_iface
+               version_env       = vers_decls version_info
+               module_vers       = vers_module version_info
+
+               whats_imported = Specifically module_vers
+                                             export_vers import_items 
+                                             (vers_rules version_info)
+
+               import_items = [(n,v) | n <- lookupWithDefaultModuleEnv mv_map [] mod,
+                                       let v = lookupNameEnv version_env n `orElse` 
+                                               pprPanic "mk_whats_imported" (ppr n)
+                              ]
+               export_vers | moduleName mod `elem` import_all_mods 
+                           = Just (vers_exports version_info)
+                           | otherwise
+                           = Nothing
+       
+       import_info = foldFM mk_imp_info [] mod_map
+    in
+    traceRn (text "Modules in Ifaces: " <+> fsep (map ppr (keysFM mod_map)))   `thenRn_`
+    returnRn import_info
+
+
+addItem :: ModuleEnv [a] -> Module -> a -> ModuleEnv [a]
+addItem fm mod x = extendModuleEnv_C add_item fm mod [x]
+                where
+                  add_item xs _ = x:xs
 \end{code}
 
+%*********************************************************
+%*                                                      *
+\subsection{Slurping declarations}
+%*                                                      *
+%*********************************************************
+
+\begin{code}
+-------------------------------------------------------
+slurpImpDecls source_fvs
+  = traceRn (text "slurpImp" <+> fsep (map ppr (nameSetToList source_fvs))) `thenRn_`
+
+       -- The current slurped-set records all local things
+    getSlurped                                 `thenRn` \ source_binders ->
+    slurpSourceRefs source_binders source_fvs  `thenRn` \ (decls, needed) ->
+
+       -- Then get everything else
+    closeDecls decls needed                    `thenRn` \ decls1 ->
+
+       -- Finally, get any deferred data type decls
+    slurpDeferredDecls decls1                  `thenRn` \ final_decls -> 
+
+    returnRn final_decls
+
+
+-------------------------------------------------------
+slurpSourceRefs :: NameSet                     -- Variables defined in source
+               -> FreeVars                     -- Variables referenced in source
+               -> RnMG ([RenamedHsDecl],
+                        FreeVars)              -- Un-satisfied needs
+-- The declaration (and hence home module) of each gate has
+-- already been loaded
+
+slurpSourceRefs source_binders source_fvs
+  = go_outer []                        -- Accumulating decls
+            emptyFVs                   -- Unsatisfied needs
+            emptyFVs                   -- Accumulating gates
+            (nameSetToList source_fvs) -- Things whose defn hasn't been loaded yet
+  where
+       -- The outer loop repeatedly slurps the decls for the current gates
+       -- and the instance decls 
+
+       -- The outer loop is needed because consider
+       --      instance Foo a => Baz (Maybe a) where ...
+       -- It may be that @Baz@ and @Maybe@ are used in the source module,
+       -- but not @Foo@; so we need to chase @Foo@ too.
+       --
+       -- We also need to follow superclass refs.  In particular, 'chasing @Foo@' must
+       -- include actually getting in Foo's class decl
+       --      class Wib a => Foo a where ..
+       -- so that its superclasses are discovered.  The point is that Wib is a gate too.
+       -- We do this for tycons too, so that we look through type synonyms.
+
+    go_outer decls fvs all_gates []    
+       = returnRn (decls, fvs)
+
+    go_outer decls fvs all_gates refs  -- refs are not necessarily slurped yet
+       = traceRn (text "go_outer" <+> ppr refs)                `thenRn_`
+         foldlRn go_inner (decls, fvs, emptyFVs) refs          `thenRn` \ (decls1, fvs1, gates1) ->
+         getImportedInstDecls (all_gates `plusFV` gates1)      `thenRn` \ inst_decls ->
+         rnInstDecls decls1 fvs1 gates1 inst_decls             `thenRn` \ (decls2, fvs2, gates2) ->
+         go_outer decls2 fvs2 (all_gates `plusFV` gates2)
+                              (nameSetToList (gates2 `minusNameSet` all_gates))
+               -- Knock out the all_gates because even if we don't slurp any new
+               -- decls we can get some apparently-new gates from wired-in names
+
+    go_inner (decls, fvs, gates) wanted_name
+       = importDecl wanted_name                `thenRn` \ import_result ->
+         case import_result of
+           AlreadySlurped -> returnRn (decls, fvs, gates)
+           WiredIn        -> returnRn (decls, fvs, gates `plusFV` getWiredInGates wanted_name)
+           Deferred       -> returnRn (decls, fvs, gates `addOneFV` wanted_name)       -- It's a type constructor
+                       
+           HereItIs decl -> rnIfaceTyClDecl decl               `thenRn` \ (new_decl, fvs1) ->
+                            returnRn (TyClD new_decl : decls, 
+                                      fvs1 `plusFV` fvs,
+                                      gates `plusFV` getGates source_fvs new_decl)
+
+rnInstDecls decls fvs gates []
+  = returnRn (decls, fvs, gates)
+rnInstDecls decls fvs gates (d:ds) 
+  = rnIfaceDecl d              `thenRn` \ (new_decl, fvs1) ->
+    rnInstDecls (new_decl:decls) 
+               (fvs1 `plusFV` fvs)
+               (gates `plusFV` getInstDeclGates new_decl)
+               ds
+\end{code}
 
-%********************************************************
-%*                                                     *
-\subsection{Loading usage information}
-%*                                                     *
-%********************************************************
 
 \begin{code}
-checkUpToDate :: Module -> RnMG Bool           -- True <=> no need to recompile
-checkUpToDate mod_name
-  = findAndReadIface doc_str mod_name          `thenRn` \ read_result ->
-    case read_result of
-       Nothing ->      -- Old interface file not found, so we'd better bale out
-                   traceRn (ppSep [ppStr "Didnt find old iface", pprModule PprDebug mod_name]) `thenRn_`
-                   returnRn False
-
-       Just (ParsedIface _ _ usages _ _ _ _ _) 
-               ->      -- Found it, so now check it
-                   checkModUsage usages
+-------------------------------------------------------
+-- closeDecls keeps going until the free-var set is empty
+closeDecls decls needed
+  | not (isEmptyFVs needed)
+  = slurpDecls decls needed    `thenRn` \ (decls1, needed1) ->
+    closeDecls decls1 needed1
+
+  | otherwise
+  = getImportedRules                   `thenRn` \ rule_decls ->
+    case rule_decls of
+       []    -> returnRn decls -- No new rules, so we are done
+       other -> rnIfaceDecls decls emptyFVs rule_decls         `thenRn` \ (decls1, needed1) ->
+                closeDecls decls1 needed1
+                
+
+-------------------------------------------------------
+-- Augment decls with any decls needed by needed.
+-- Return also free vars of the new decls (only)
+slurpDecls decls needed
+  = go decls emptyFVs (nameSetToList needed) 
   where
-       -- Only look in current directory, with suffix .hi
-    doc_str = ppSep [ppStr "Need usage info from", pprModule PprDebug mod_name]
+    go decls fvs []         = returnRn (decls, fvs)
+    go decls fvs (ref:refs) = slurpDecl decls fvs ref  `thenRn` \ (decls1, fvs1) ->
+                             go decls1 fvs1 refs
+
+-------------------------------------------------------
+slurpDecl decls fvs wanted_name
+  = importDecl wanted_name             `thenRn` \ import_result ->
+    case import_result of
+       -- Found a declaration... rename it
+       HereItIs decl -> rnIfaceTyClDecl decl           `thenRn` \ (new_decl, fvs1) ->
+                        returnRn (TyClD new_decl:decls, fvs1 `plusFV` fvs)
+
+       -- No declaration... (wired in thing, or deferred, or already slurped)
+       other -> returnRn (decls, fvs)
+
+
+-------------------------------------------------------
+rnIfaceDecls :: [RenamedHsDecl] -> FreeVars
+            -> [(Module, RdrNameHsDecl)]
+            -> RnM d ([RenamedHsDecl], FreeVars)
+rnIfaceDecls decls fvs []     = returnRn (decls, fvs)
+rnIfaceDecls decls fvs (d:ds) = rnIfaceDecl d          `thenRn` \ (new_decl, fvs1) ->
+                               rnIfaceDecls (new_decl:decls) (fvs1 `plusFV` fvs) ds
+
+rnIfaceDecl    (mod, decl) = initIfaceRnMS mod (rnDecl decl)   
+rnIfaceTyClDecl (mod, decl) = initIfaceRnMS mod (rnTyClDecl decl)      `thenRn` \ decl' ->
+                             returnRn (decl', tyClDeclFVs decl')
+\end{code}
 
 
-checkModUsage [] = returnRn True               -- Yes!  Everything is up to date!
+\begin{code}
+getSlurped
+  = getIfacesRn        `thenRn` \ ifaces ->
+    returnRn (iSlurp ifaces)
+
+recordSlurp ifaces@(Ifaces { iSlurp = slurped_names, iVSlurp = imp_names })
+           avail
+  = let
+       new_slurped_names = addAvailToNameSet slurped_names avail
+       new_imp_names     = availName avail : imp_names
+    in
+    ifaces { iSlurp  = new_slurped_names, iVSlurp = new_imp_names }
 
-checkModUsage ((mod, old_mod_vers, old_local_vers) : rest)
-  = loadInterface doc_str mod          `thenRn` \ ifaces ->
+recordLocalSlurps local_avails
+  = getIfacesRn        `thenRn` \ ifaces ->
     let
-       Ifaces _ mod_vers_map _ new_vers_map _ _ _ = ifaces
-       maybe_new_mod_vers = lookupFM mod_vers_map mod
-       Just new_mod_vers  = maybe_new_mod_vers
+       new_slurped_names = foldl addAvailToNameSet (iSlurp ifaces) local_avails
     in
-       -- If we can't find a version number for the old module then
-       -- bale out saying things aren't up to date
-    if not (maybeToBool maybe_new_mod_vers) then
-       returnRn False
-    else
-
-       -- If the module version hasn't changed, just move on
-    if new_mod_vers == old_mod_vers then
-       traceRn (ppSep [ppStr "Module version unchanged:", pprModule PprDebug mod])     `thenRn_`
-       checkModUsage rest
-    else
-    traceRn (ppSep [ppStr "Module version has changed:", pprModule PprDebug mod])      `thenRn_`
+    setIfacesRn (ifaces { iSlurp  = new_slurped_names })
+\end{code}
 
-       -- New module version, so check entities inside
-    checkEntityUsage mod new_vers_map old_local_vers   `thenRn` \ up_to_date ->
-    if up_to_date then
-       traceRn (ppStr "...but the bits I use havn't.") `thenRn_`
-       checkModUsage rest      -- This one's ok, so check the rest
-    else
-       returnRn False          -- This one failed, so just bail out now
-  where
-    doc_str = ppSep [ppStr "need version info for", pprModule PprDebug mod]
 
 
-checkEntityUsage mod new_vers_map [] 
-  = returnRn True      -- Yes!  All up to date!
+%*********************************************************
+%*                                                      *
+\subsection{Deferred declarations}
+%*                                                      *
+%*********************************************************
 
-checkEntityUsage mod new_vers_map ((occ_name,old_vers) : rest)
-  = newGlobalName mod occ_name         `thenRn` \ name ->
-    case lookupFM new_vers_map name of
+The idea of deferred declarations is this.  Suppose we have a function
+       f :: T -> Int
+       data T = T1 A | T2 B
+       data A = A1 X | A2 Y
+       data B = B1 P | B2 Q
+Then we don't want to load T and all its constructors, and all
+the types those constructors refer to, and all the types *those*
+constructors refer to, and so on.  That might mean loading many more
+interface files than is really necessary.  So we 'defer' loading T.
+
+But f might be strict, and the calling convention for evaluating
+values of type T depends on how many constructors T has, so 
+we do need to load T, but not the full details of the type T.
+So we load the full decl for T, but only skeleton decls for A and B:
+       f :: T -> Int
+       data T = {- 2 constructors -}
+
+Whether all this is worth it is moot.
 
-       Nothing       ->        -- We used it before, but it ain't there now
-                         traceRn (ppSep [ppStr "...and this no longer exported:", ppr PprDebug name])  `thenRn_`
-                         returnRn False
-
-       Just new_vers ->        -- It's there, but is it up to date?
-                         if new_vers == old_vers then
-                               -- Up to date, so check the rest
-                               checkEntityUsage mod new_vers_map rest
-                         else
-                               traceRn (ppSep [ppStr "...and this is out of date:", ppr PprDebug name])  `thenRn_`
-                               returnRn False  -- Out of date, so bale out
+\begin{code}
+slurpDeferredDecls :: [RenamedHsDecl] -> RnMG [RenamedHsDecl]
+slurpDeferredDecls decls = returnRn decls
+
+{-     OMIT FOR NOW
+slurpDeferredDecls :: [RenamedHsDecl] -> RnMG [RenamedHsDecl]
+slurpDeferredDecls decls
+  = getDeferredDecls                                           `thenRn` \ def_decls ->
+    rnIfaceDecls decls emptyFVs (map stripDecl def_decls)      `thenRn` \ (decls1, fvs) ->
+    ASSERT( isEmptyFVs fvs )
+    returnRn decls1
+
+stripDecl (mod, TyClD (TyData dt _ tc tvs _ nconstrs _ loc name1 name2))
+  = (mod, TyClD (TyData dt [] tc tvs [] nconstrs Nothing loc
+               name1 name2))
+       -- Nuke the context and constructors
+       -- But retain the *number* of constructors!
+       -- Also the tvs will have kinds on them.
+-}
 \end{code}
 
 
 %*********************************************************
-%*                                                     *
-\subsection{Getting in a declaration}
-%*                                                     *
+%*                                                      *
+\subsection{Extracting the `gates'}
+%*                                                      *
 %*********************************************************
 
-\begin{code}
-getDecl :: Name -> RnMG (AvailInfo, RdrNameHsDecl)
-getDecl name
-  = traceRn doc_str                    `thenRn_`
-    loadInterface doc_str mod          `thenRn` \ (Ifaces _ _ _ _ decls_map _ _) ->
-    case lookupFM decls_map name of
+When we import a declaration like
+\begin{verbatim}
+       data T = T1 Wibble | T2 Wobble
+\end{verbatim}
+we don't want to treat @Wibble@ and @Wobble@ as gates
+{\em unless} @T1@, @T2@ respectively are mentioned by the user program.
+If only @T@ is mentioned
+we want only @T@ to be a gate;
+that way we don't suck in useless instance
+decls for (say) @Eq Wibble@, when they can't possibly be useful.
 
-      Just avail_w_decl -> returnRn avail_w_decl
+@getGates@ takes a newly imported (and renamed) decl, and the free
+vars of the source program, and extracts from the decl the gate names.
 
-      Nothing          ->      -- Can happen legitimately for "Optional" occurrences
-                          returnRn (NotAvailable, ValD EmptyBinds)
+\begin{code}
+getGates source_fvs (IfaceSig _ ty _ _)
+  = extractHsTyNames ty
+
+getGates source_fvs (ClassDecl ctxt cls tvs _ sigs _ _ _ )
+  = (delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) sigs)
+                       (hsTyVarNames tvs)
+     `addOneToNameSet` cls)
+    `plusFV` maybe_double
   where
-     (mod,_) = modAndOcc name
-     doc_str = ppSep [ppStr "Need decl for", ppr PprDebug name]
-\end{code}
+    get (ClassOpSig n _ ty _) 
+       | n `elemNameSet` source_fvs = extractHsTyNames ty
+       | otherwise                  = emptyFVs
+
+       -- If we load any numeric class that doesn't have
+       -- Int as an instance, add Double to the gates. 
+       -- This takes account of the fact that Double might be needed for
+       -- defaulting, but we don't want to load Double (and all its baggage)
+       -- if the more exotic classes aren't used at all.
+    maybe_double | nameUnique cls `elem` fractionalClassKeys 
+                = unitFV (getName doubleTyCon)
+                | otherwise
+                = emptyFVs
+
+getGates source_fvs (TySynonym tycon tvs ty _)
+  = delListFromNameSet (extractHsTyNames ty)
+                      (hsTyVarNames tvs)
+       -- A type synonym type constructor isn't a "gate" for instance decls
+
+getGates source_fvs (TyData _ ctxt tycon tvs cons _ _ _ _ _)
+  = delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) cons)
+                      (hsTyVarNames tvs)
+    `addOneToNameSet` tycon
+  where
+    get (ConDecl n _ tvs ctxt details _)
+       | n `elemNameSet` source_fvs
+               -- If the constructor is method, get fvs from all its fields
+       = delListFromNameSet (get_details details `plusFV` 
+                             extractHsCtxtTyNames ctxt)
+                            (hsTyVarNames tvs)
+    get (ConDecl n _ tvs ctxt (RecCon fields) _)
+               -- Even if the constructor isn't mentioned, the fields
+               -- might be, as selectors.  They can't mention existentially
+               -- bound tyvars (typechecker checks for that) so no need for 
+               -- the deleteListFromNameSet part
+       = foldr (plusFV . get_field) emptyFVs fields
+       
+    get other_con = emptyFVs
 
-@getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
-It behaves exactly as if the wired in decl were actually in an interface file.
-Specifically,
-  *    if the wired-in name is a data type constructor or a data constructor, 
-       it brings in the type constructor and all the data constructors; and
-       marks as "occurrences" any free vars of the data con.
+    get_details (VanillaCon tys) = plusFVs (map get_bang tys)
+    get_details (InfixCon t1 t2) = get_bang t1 `plusFV` get_bang t2
+    get_details (RecCon fields)  = plusFVs [get_bang t | (_, t) <- fields]
 
-  *    similarly for synonum type constructor
+    get_field (fs,t) | any (`elemNameSet` source_fvs) fs = get_bang t
+                    | otherwise                         = emptyFVs
 
-  *    if the wired-in name is another wired-in Id, it marks as "occurrences"
-       the free vars of the Id's type.
+    get_bang bty = extractHsTyNames (getBangType bty)
+\end{code}
 
-  *    it loads the interface file for the wired-in thing for the
-       sole purpose of making sure that its instance declarations are available
+@getWiredInGates@ is just like @getGates@, but it sees a wired-in @Name@
+rather than a declaration.
 
-All this is necessary so that we know all types that are "in play", so
-that we know just what instances to bring into scope.
-       
 \begin{code}
-getWiredInDecl :: Name -> RnMG AvailInfo
-getWiredInDecl name
-  =    -- Force in the home module in case it has instance decls for
-       -- the thing we are interested in
-    (if not is_tycon || mod == gHC__ then
-       returnRn ()                     -- Mini hack 1: no point for non-tycons; and if we
-                                       -- do this we find PrelNum trying to import PackedString,
-                                       -- because PrelBase's .hi file mentions PackedString.unpackString
-                                       -- But PackedString.hi isn't built by that point!
-                                       --
-                                       -- Mini hack 2; GHC is guaranteed not to have
-                                       -- instance decls, so it's a waste of time
-                                       -- to read it
-    else
-       loadInterface doc_str mod       `thenRn_`
-       returnRn ()
-    )                                          `thenRn_`
-
-    if is_tycon then
-       get_wired_tycon the_tycon
-    else                               -- Must be a wired-in-Id
-    if (isDataCon the_id) then         -- ... a wired-in data constructor
-       get_wired_tycon (dataConTyCon the_id)
-    else                               -- ... a wired-in non data-constructor
-       get_wired_id the_id
-  where
-    doc_str = ppSep [ppStr "Need home module for wired in thing", ppr PprDebug name]
-    (mod,_) = modAndOcc name
-    maybe_wired_in_tycon = maybeWiredInTyConName name
-    is_tycon            = maybeToBool maybe_wired_in_tycon
-    maybe_wired_in_id    = maybeWiredInIdName    name
-    Just the_tycon      = maybe_wired_in_tycon
-    Just the_id         = maybe_wired_in_id
-
-get_wired_id id
-  = addImplicitOccsRn (nameSetToList id_mentioned)     `thenRn_`
-    returnRn (Avail (getName id) [])
-  where
-    id_mentioned        = namesOfType (idType id)
+getWiredInGates :: Name -> FreeVars
+getWiredInGates name   -- No classes are wired in
+  = case lookupNameEnv wiredInThingEnv name of
+       Just (AnId the_id) -> getWiredInGates_s (namesOfType (idType the_id))
+
+       Just (ATyCon tc)
+         |  isSynTyCon tc
+         -> getWiredInGates_s (delListFromNameSet (namesOfType ty) (map getName tyvars))
+         where
+            (tyvars,ty)  = getSynTyConDefn tc
 
-get_wired_tycon tycon 
-  | isSynTyCon tycon
-  = addImplicitOccsRn (nameSetToList mentioned)                `thenRn_`
-    returnRn (Avail (getName tycon) [])
-  where
-    (tyvars,ty) = getSynTyConDefn tycon
-    mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
+       other -> unitFV name
 
-get_wired_tycon tycon 
-  | otherwise          -- data or newtype
-  = addImplicitOccsRn (nameSetToList mentioned)                `thenRn_`
-    returnRn (Avail (getName tycon) (map getName data_cons))
-  where
-    data_cons = tyConDataCons tycon
-    mentioned = foldr (unionNameSets . namesOfType . idType) emptyNameSet data_cons
+getWiredInGates_s names = foldr (plusFV . getWiredInGates) emptyFVs (nameSetToList names)
+\end{code}
+
+\begin{code}
+getInstDeclGates (InstD (InstDecl inst_ty _ _ _ _)) = extractHsTyNames inst_ty
+getInstDeclGates other                             = emptyFVs
 \end{code}
 
 
 %*********************************************************
 %*                                                     *
-\subsection{Getting other stuff}
+\subsection{Getting in a declaration}
 %*                                                     *
 %*********************************************************
 
 \begin{code}
-getInterfaceExports :: Module -> RnMG (Avails, [(OccName,Fixity)])
-getInterfaceExports mod
-  = loadInterface doc_str mod          `thenRn` \ (Ifaces _ _ export_envs _ _ _ _) ->
-    case lookupFM export_envs mod of
-       Nothing ->      -- Not there; it must be that the interface file wasn't found;
-                       -- the error will have been reported already.
-                       -- (Actually loadInterface should put the empty export env in there
-                       --  anyway, but this does no harm.)
-                     returnRn ([],[])
-
-       Just stuff -> returnRn stuff
-  where
-    doc_str = ppSep [pprModule PprDebug mod, ppStr "is directly imported"]
+importDecl :: Name -> RnMG ImportDeclResult
+
+data ImportDeclResult
+  = AlreadySlurped
+  | WiredIn    
+  | Deferred
+  | HereItIs (Module, RdrNameTyClDecl)
+
+importDecl name
+  =    -- Check if it was loaded before beginning this module
+    checkAlreadyAvailable name         `thenRn` \ done ->
+    if done then
+       returnRn AlreadySlurped
+    else
 
+       -- Check if we slurped it in while compiling this module
+    getIfacesRn                                `thenRn` \ ifaces ->
+    if name `elemNameSet` iSlurp ifaces then   
+       returnRn AlreadySlurped 
+    else 
+
+       -- Don't slurp in decls from this module's own interface file
+       -- (Indeed, this shouldn't happen.)
+    if isLocallyDefined name then
+       addWarnRn (importDeclWarn name) `thenRn_`
+       returnRn AlreadySlurped
+    else
 
-getImportedInstDecls :: RnMG [IfaceInst]
-getImportedInstDecls
-  =    -- First load any special-instance modules that aren't aready loaded
-    getSpecialInstModules                      `thenRn` \ inst_mods ->
-    mapRn load_it inst_mods                    `thenRn_`
+       -- When we find a wired-in name we must load its home
+       -- module so that we find any instance decls lurking therein
+    if name `elemNameEnv` wiredInThingEnv then
+       loadHomeInterface doc name      `thenRn_`
+       returnRn WiredIn
 
-       -- Now we're ready to grab the instance declarations
-    getIfacesRn                                                `thenRn` \ ifaces ->
-    let
-        Ifaces _ _ _ _ _ insts _ = ifaces
-    in
-    returnRn (bagToList insts) 
+    else getNonWiredInDecl name
   where
-    load_it mod = loadInterface (doc_str mod) mod
-    doc_str mod = ppSep [pprModule PprDebug mod, ppStr "is a special-instance module"]
+    doc = ptext SLIT("need home module for wired in thing") <+> ppr name
+
+getNonWiredInDecl :: Name -> RnMG ImportDeclResult
+getNonWiredInDecl needed_name 
+  = traceRn doc_str                            `thenRn_`
+    loadHomeInterface doc_str needed_name      `thenRn` \ ifaces ->
+    case lookupNameEnv (iDecls ifaces) needed_name of
+
+{-             OMIT DEFERRED STUFF FOR NOW, TILL GHCI WORKS
+      Just (version, avail, is_tycon_name, decl@(_, TyClD (TyData DataType _ _ _ _ ncons _ _ _ _)))
+       -- This case deals with deferred import of algebraic data types
+
+       |  not opt_NoPruneTyDecls
+
+       && (opt_IgnoreIfacePragmas || ncons > 1)
+               -- We only defer if imported interface pragmas are ingored
+               -- or if it's not a product type.
+               -- Sole reason: The wrapper for a strict function may need to look
+               -- inside its arg, and hence need to see its arg type's constructors.
+
+       && not (getUnique tycon_name `elem` cCallishTyKeys)
+               -- Never defer ccall types; we have to unbox them, 
+               -- and importing them does no harm
+
+
+       ->      -- OK, so we're importing a deferrable data type
+           if needed_name == tycon_name
+               -- The needed_name is the TyCon of a data type decl
+               -- Record that it's slurped, put it in the deferred set
+               -- and don't return a declaration at all
+               setIfacesRn (recordSlurp (ifaces {iDeferred = iDeferred ifaces 
+                                                             `addOneToNameSet` tycon_name})
+                                        version (AvailTC needed_name [needed_name]))   `thenRn_`
+               returnRn Deferred
+
+           else
+               -- The needed name is a constructor of a data type decl,
+               -- getting a constructor, so remove the TyCon from the deferred set
+               -- (if it's there) and return the full declaration
+               setIfacesRn (recordSlurp (ifaces {iDeferred = iDeferred ifaces 
+                                                              `delFromNameSet` tycon_name})
+                                   version avail)      `thenRn_`
+               returnRn (HereItIs decl)
+       where
+          tycon_name = availName avail
+-}
 
-getSpecialInstModules :: RnMG [Module]
-getSpecialInstModules 
-  = getIfacesRn                                                `thenRn` \ ifaces ->
-    let
-        Ifaces _ _ _ _ _ _ inst_mods = ifaces
-    in
-    returnRn inst_mods
-\end{code}
+      Just (avail,_,decl)
+       -> setIfacesRn (recordSlurp ifaces avail)       `thenRn_`
+          returnRn (HereItIs decl)
 
-\begin{code}
-getImportVersions :: [AvailInfo]                       -- Imported avails
-                 -> RnMG (VersionInfo Name)    -- Version info for these names
+      Nothing 
+       -> addErrRn (getDeclErr needed_name)    `thenRn_` 
+          returnRn AlreadySlurped
+  where
+     doc_str = ptext SLIT("need decl for") <+> ppr needed_name
 
-getImportVersions imported_avails      
-  = getIfacesRn                                        `thenRn` \ ifaces ->
+{-             OMIT FOR NOW
+getDeferredDecls :: RnMG [(Module, RdrNameHsDecl)]
+getDeferredDecls 
+  = getIfacesRn                `thenRn` \ ifaces ->
     let
-        Ifaces _ mod_versions_map _ version_map _ _ _ = ifaces
-
-        -- import_versions is harder: we have to group together all the things imported
-        -- from a particular module.  We do this with yet another finite map
-
-        mv_map :: FiniteMap Module [LocalVersion Name]
-        mv_map            = foldl add_mv emptyFM imported_avails
-        add_mv mv_map (Avail name _) 
-           | isWiredInName name = mv_map       -- Don't record versions for wired-in names
-           | otherwise = case lookupFM mv_map mod of
-                               Just versions -> addToFM mv_map mod ((name,version):versions)
-                               Nothing       -> addToFM mv_map mod [(name,version)]
-           where
-            (mod,_) = modAndOcc name
-            version = case lookupFM version_map name of
-                        Just v  -> v
-                        Nothing -> pprPanic "getVersionInfo:" (ppr PprDebug name)
-
-        import_versions = [ (mod, expectJust "import_versions" (lookupFM mod_versions_map mod), local_versions)
-                          | (mod, local_versions) <- fmToList mv_map
-                          ]
-
-        -- Question: should we filter the builtins out of import_versions?
+       decls_map           = iDecls ifaces
+       deferred_names      = nameSetToList (iDeferred ifaces)
+        get_abstract_decl n = case lookupNameEnv decls_map n of
+                                Just (_, _, _, decl) -> decl
     in
-    returnRn import_versions
+    traceRn (sep [text "getDeferredDecls", nest 4 (fsep (map ppr deferred_names))])    `thenRn_`
+    returnRn (map get_abstract_decl deferred_names)
+-}
 \end{code}
 
-%*********************************************************
+@getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
+It behaves exactly as if the wired in decl were actually in an interface file.
+Specifically,
+\begin{itemize}
+\item  if the wired-in name is a data type constructor or a data constructor, 
+       it brings in the type constructor and all the data constructors; and
+       marks as ``occurrences'' any free vars of the data con.
+
+\item  similarly for synonum type constructor
+
+\item  if the wired-in name is another wired-in Id, it marks as ``occurrences''
+       the free vars of the Id's type.
+
+\item  it loads the interface file for the wired-in thing for the
+       sole purpose of making sure that its instance declarations are available
+\end{itemize}
+All this is necessary so that we know all types that are ``in play'', so
+that we know just what instances to bring into scope.
+       
+
+%********************************************************
 %*                                                     *
-\subsection{Getting binders out of a declaration}
+\subsection{Checking usage information}
 %*                                                     *
-%*********************************************************
+%********************************************************
 
-@getDeclBinders@ returns the names for a @RdrNameHsDecl@.
-It's used for both source code (from @availsFromDecl@) and interface files
-(from @loadDecl@).
+@recompileRequired@ is called from the HscMain.   It checks whether
+a recompilation is required.  It needs access to the persistent state,
+finder, etc, because it may have to load lots of interface files to
+check their versions.
 
-It doesn't deal with source-code specific things: ValD, DefD.  They
-are handled by the sourc-code specific stuff in RnNames.
+\begin{code}
+type RecompileRequired = Bool
+upToDate  = False      -- Recompile not required
+outOfDate = True       -- Recompile required
+
+recompileRequired :: Module 
+                 -> Bool               -- Source unchanged
+                 -> Maybe ModIface     -- Old interface, if any
+                 -> RnMG RecompileRequired
+recompileRequired mod source_unchanged maybe_iface
+  = traceRn (text "Considering whether compilation is required for" <+> ppr mod <> colon)      `thenRn_`
+
+       -- CHECK WHETHER THE SOURCE HAS CHANGED
+    if not source_unchanged then
+       traceRn (nest 4 (text "Source file changed or recompilation check turned off")) `thenRn_` 
+       returnRn outOfDate
+    else
 
+       -- CHECK WHETHER WE HAVE AN OLD IFACE
+    case maybe_iface of 
+       Nothing -> traceRn (nest 4 (ptext SLIT("No old interface file")))       `thenRn_`
+                  returnRn outOfDate ;
+
+       Just iface  ->          -- Source code unchanged and no errors yet... carry on 
+                       checkList [checkModUsage u | u <- mi_usages iface]
+
+checkList :: [RnMG RecompileRequired] -> RnMG RecompileRequired
+checkList []            = returnRn upToDate
+checkList (check:checks) = check       `thenRn` \ recompile ->
+                          if recompile then 
+                               returnRn outOfDate
+                          else
+                               checkList checks
+\end{code}
+       
 \begin{code}
-getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)             -- New-name function
-               -> RdrNameHsDecl
-               -> RnMG AvailInfo
-
-getDeclBinders new_name (TyD (TyData _ tycon _ condecls _ _ src_loc))
-  = new_name tycon src_loc                     `thenRn` \ tycon_name ->
-    getConFieldNames new_name condecls         `thenRn` \ sub_names ->
-    returnRn (Avail tycon_name sub_names)
-
-getDeclBinders new_name (TyD (TyNew _ tycon _ (NewConDecl con _ con_loc) _ _ src_loc))
-  = new_name tycon src_loc             `thenRn` \ tycon_name ->
-    new_name con src_loc               `thenRn` \ con_name ->
-    returnRn (Avail tycon_name [con_name])
-
-getDeclBinders new_name (TyD (TySynonym tycon _ _ src_loc))
-  = new_name tycon src_loc             `thenRn` \ tycon_name ->
-    returnRn (Avail tycon_name [])
-
-getDeclBinders new_name (ClD (ClassDecl _ cname _ sigs _ _ src_loc))
-  = new_name cname src_loc                     `thenRn` \ class_name ->
-    mapRn (getClassOpNames new_name) sigs      `thenRn` \ sub_names ->
-    returnRn (Avail class_name sub_names)
-
-getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
-  = new_name var src_loc                       `thenRn` \ var_name ->
-    returnRn (Avail var_name [])
-
-getDeclBinders new_name (DefD _)  = returnRn NotAvailable
-getDeclBinders new_name (InstD _) = returnRn NotAvailable
-
-----------------
-getConFieldNames new_name (ConDecl con _ src_loc : rest)
-  = new_name con src_loc               `thenRn` \ n ->
-    getConFieldNames new_name rest     `thenRn` \ ns -> 
-    returnRn (n:ns)
-
-getConFieldNames new_name (NewConDecl con _ src_loc : rest)
-  = new_name con src_loc               `thenRn` \ n ->
-    getConFieldNames new_name rest     `thenRn` \ ns -> 
-    returnRn (n:ns)
-
-getConFieldNames new_name (ConOpDecl _ con _ src_loc : rest)
-  = new_name con src_loc               `thenRn` \ n ->
-    getConFieldNames new_name rest     `thenRn` \ ns -> 
-    returnRn (n:ns)
-
-getConFieldNames new_name (RecConDecl con fielddecls src_loc : rest)
-  = mapRn (\n -> new_name n src_loc) (con:fields)      `thenRn` \ cfs ->
-    getConFieldNames new_name rest                     `thenRn` \ ns  -> 
-    returnRn (cfs ++ ns)
-  where
-    fields = concat (map fst fielddecls)
+checkModUsage :: ImportVersion Name -> RnMG RecompileRequired
+-- Given the usage information extracted from the old
+-- M.hi file for the module being compiled, figure out
+-- whether M needs to be recompiled.
+
+checkModUsage (mod_name, _, _, NothingAtAll)
+       -- If CurrentModule.hi contains 
+       --      import Foo :: ;
+       -- then that simply records that Foo lies below CurrentModule in the
+       -- hierarchy, but CurrentModule doesn't depend in any way on Foo.
+       -- In this case we don't even want to open Foo's interface.
+  = up_to_date (ptext SLIT("Nothing used from:") <+> ppr mod_name)
+
+checkModUsage (mod_name, _, _, whats_imported)
+  = tryLoadInterface doc_str mod_name ImportBySystem   `thenRn` \ (ifaces, maybe_err) ->
+    case maybe_err of {
+       Just err -> out_of_date (sep [ptext SLIT("Can't find version number for module"), 
+                                     ppr mod_name]) ;
+               -- Couldn't find or parse a module mentioned in the
+               -- old interface file.  Don't complain -- it might just be that
+               -- the current module doesn't need that import and it's been deleted
+
+       Nothing -> 
+
+    getHomeIfaceTableRn                                        `thenRn` \ hit ->
+    let
+       mod_details   = lookupTableByModName hit (iPIT ifaces) mod_name
+                       `orElse` panic "checkModUsage"
+       new_vers      = mi_version mod_details
+       new_decl_vers = vers_decls new_vers
+    in
+    case whats_imported of {   -- NothingAtAll dealt with earlier
 
-getConFieldNames new_name [] = returnRn []
+      Everything old_mod_vers -> checkModuleVersion old_mod_vers new_vers      `thenRn` \ recompile ->
+                                if recompile then
+                                       out_of_date (ptext SLIT("...and I needed the whole module"))
+                                else
+                                       returnRn upToDate ;
 
-getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
-\end{code}
+      Specifically old_mod_vers maybe_old_export_vers old_decl_vers old_rule_vers ->
 
+       -- CHECK MODULE
+    checkModuleVersion old_mod_vers new_vers   `thenRn` \ recompile ->
+    if not recompile then
+       returnRn upToDate
+    else
+                                
+       -- CHECK EXPORT LIST
+    if checkExportList maybe_old_export_vers new_vers then
+       out_of_date (ptext SLIT("Export list changed"))
+    else
 
-%*********************************************************
-%*                                                     *
-\subsection{Reading an interface file}
-%*                                                     *
-%*********************************************************
+       -- CHECK RULES
+    if old_rule_vers /= vers_rules new_vers then
+       out_of_date (ptext SLIT("Rules changed"))
+    else
 
-\begin{code}
-findAndReadIface :: Pretty -> Module -> RnMG (Maybe ParsedIface)
-       -- Nothing <=> file not found, or unreadable, or illegible
-       -- Just x  <=> successfully found and parsed 
-findAndReadIface doc_str mod
-  = traceRn trace_msg                  `thenRn_`
-    getSearchPathRn                    `thenRn` \ dirs ->
-    try dirs dirs
+       -- CHECK ITEMS ONE BY ONE
+    checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers]  `thenRn` \ recompile ->
+    if recompile then
+       returnRn outOfDate      -- This one failed, so just bail out now
+    else
+       up_to_date (ptext SLIT("...but the bits I use haven't."))
+
+    }}
   where
-    trace_msg = ppHang (ppBesides [ppStr "Reading interface for ", 
-                                  pprModule PprDebug mod, ppSemi])
-                    4 (ppBesides [ppStr "reason: ", doc_str])
-
-    try all_dirs [] = traceRn (ppStr "...failed")      `thenRn_`
-                     returnRn Nothing
-
-    try all_dirs (dir:dirs)
-       = readIface file_path   `thenRn` \ read_result ->
-         case read_result of
-               Nothing    -> try all_dirs dirs
-               Just iface -> traceRn (ppStr "...done") `thenRn_`
-                             returnRn (Just iface)
-       where
-         file_path = dir ++ "/" ++ moduleString mod ++ ".hi"
-\end{code}
+    doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
 
-@readIface@ trys just one file.
+------------------------
+checkModuleVersion old_mod_vers new_vers
+  | vers_module new_vers == old_mod_vers
+  = up_to_date (ptext SLIT("Module version unchanged"))
 
-\begin{code}
-readIface :: String -> RnMG (Maybe ParsedIface)        
-       -- Nothing <=> file not found, or unreadable, or illegible
-       -- Just x  <=> successfully found and parsed 
-readIface file_path
-  = ioToRnMG (readFile file_path)      `thenRn` \ read_result ->
-    case read_result of
-       Right contents    -> case parseIface contents of
-                               Failed err      -> failWithRn Nothing err 
-                               Succeeded iface -> returnRn (Just iface)
+  | otherwise
+  = out_of_date (ptext SLIT("Module version has changed"))
 
-       Left  (NoSuchThing _) -> returnRn Nothing
+------------------------
+checkExportList Nothing  new_vers = upToDate
+checkExportList (Just v) new_vers = v /= vers_exports new_vers
 
-       Left  err             -> failWithRn Nothing
-                                           (cannaeReadFile file_path err)
+------------------------
+checkEntityUsage new_vers (name,old_vers)
+  = case lookupNameEnv new_vers name of
 
-\end{code}
-
-mkSearchPath takes a string consisting of a colon-separated list of directories, and turns it into
-a list of directories.  For example:
+       Nothing       ->        -- We used it before, but it ain't there now
+                         out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
 
-       mkSearchPath "foo:.:baz"  =  ["foo", ".", "baz"]
+       Just new_vers   -- It's there, but is it up to date?
+         | new_vers == old_vers -> returnRn upToDate
+         | otherwise            -> out_of_date (sep [ptext SLIT("Out of date:"), ppr name])
 
-\begin{code}
-mkSearchPath :: Maybe String -> SearchPath
-mkSearchPath Nothing = ["."]
-mkSearchPath (Just s)
-  = go s
-  where
-    go "" = []
-    go s  = first : go (drop 1 rest)
-         where
-           (first,rest) = span (/= ':') s
+up_to_date  msg = traceRn msg `thenRn_` returnRn upToDate
+out_of_date msg = traceRn msg `thenRn_` returnRn outOfDate
 \end{code}
 
+
 %*********************************************************
-%*                                                     *
+%*                                                      *
 \subsection{Errors}
-%*                                                     *
+%*                                                      *
 %*********************************************************
 
 \begin{code}
-noIfaceErr mod sty
-  = ppBesides [ppStr "Could not find interface for ", ppQuote (pprModule sty mod)]
---     , ppStr " in"]) 4 (ppAboves (map ppStr dirs))
-
-cannaeReadFile file err sty
-  = ppBesides [ppPStr SLIT("Failed in reading file: "), ppStr file, ppStr "; error=", ppStr (show err)]
+getDeclErr name
+  = vcat [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
+         ptext SLIT("from module") <+> quotes (ppr (nameModule name))
+        ]
+
+importDeclWarn name
+  = sep [ptext SLIT(
+    "Compiler tried to import decl from interface file with same name as module."), 
+        ptext SLIT(
+    "(possible cause: module name clashes with interface file already in scope.)")
+       ] $$
+    hsep [ptext SLIT("name:"), quotes (ppr name)]
 \end{code}