[project @ 2005-01-18 12:18:11 by simonpj]
[ghc-hetmet.git] / ghc / compiler / compMan / CompManager.lhs
index 080158b..406c7a3 100644 (file)
@@ -5,9 +5,10 @@
 %
 \begin{code}
 module CompManager ( 
-    ModuleGraph, ModSummary(..),
+    ModSummary,                -- Abstract
+    ModuleGraph,       -- All the modules from the home package
 
-    CmState,           -- abstract
+    CmState,           -- Abstract
 
     cmInit,       -- :: GhciMode -> IO CmState
 
@@ -27,6 +28,7 @@ module CompManager (
     cmGetInfo,    -- :: CmState -> String -> IO (CmState, [(TyThing,Fixity)])
     GetInfoResult,
     cmBrowseModule, -- :: CmState -> IO [TyThing]
+    cmShowModule,
 
     CmRunResult(..),
     cmRunStmt,         -- :: CmState -> String -> IO (CmState, CmRunResult)
@@ -37,10 +39,10 @@ module CompManager (
 
     HValue,
     cmCompileExpr,     -- :: CmState -> String -> IO (CmState, Maybe HValue)
-
-    cmGetModInfo       -- :: CmState -> (ModuleGraph, HomePackageTable)
-
+    cmGetModuleGraph,  -- :: CmState -> ModuleGraph
     cmSetDFlags,
+    cmGetDFlags,
+
     cmGetBindings,     -- :: CmState -> [TyThing]
     cmGetPrintUnqual,  -- :: CmState -> PrintUnqualified
 #endif
@@ -49,37 +51,40 @@ where
 
 #include "HsVersions.h"
 
+import Packages                ( isHomePackage )
 import DriverPipeline  ( CompResult(..), preprocess, compile, link )
 import HscMain         ( newHscEnv )
 import DriverState     ( v_Output_file, v_NoHsMain, v_MainModIs )
 import DriverPhases
 import Finder
 import HscTypes
-import PrelNames        ( gHC_PRIM_Name )
-import Module          ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
-                         ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
-                         extendModuleEnvList, extendModuleEnv,
-                         moduleNameUserString,
+import PrelNames        ( gHC_PRIM )
+import Module          ( Module, mkModule, delModuleEnvList, mkModuleEnv,
+                         lookupModuleEnv, moduleEnvElts, extendModuleEnv,
+                         moduleUserString,
                          ModLocation(..) )
 import GetImports
-import UniqFM
+import LoadIface       ( noIfaceErr )
 import Digraph         ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
 import ErrUtils                ( showPass )
 import SysTools                ( cleanTempFilesExcept )
 import BasicTypes      ( SuccessFlag(..), succeeded, failed )
+import StringBuffer    ( hGetStringBuffer )
 import Util
 import Outputable
 import Panic
-import CmdLineOpts     ( DynFlags(..), getDynFlags )
+import CmdLineOpts     ( DynFlags(..) )
 import Maybes          ( expectJust, orElse, mapCatMaybes )
+import FiniteMap
 
 import DATA_IOREF      ( readIORef )
 
 #ifdef GHCI
 import HscMain         ( hscGetInfo, GetInfoResult, hscStmt, hscTcExpr, hscKcType )
 import TcRnDriver      ( mkExportEnv, getModuleContents )
-import IfaceSyn                ( IfaceDecl, IfaceInst )
+import IfaceSyn                ( IfaceDecl )
 import RdrName         ( GlobalRdrEnv, plusGlobalRdrEnv )
+import Module          ( showModMsg )
 import Name            ( Name )
 import NameEnv
 import Id              ( idType )
@@ -91,6 +96,7 @@ import GHC.Exts               ( unsafeCoerce# )
 import Foreign
 import SrcLoc          ( SrcLoc )
 import Control.Exception as Exception ( Exception, try )
+import CmdLineOpts     ( DynFlag(..), dopt_unset )
 #endif
 
 import EXCEPTION       ( throwDyn )
@@ -105,6 +111,83 @@ import Time                ( ClockTime )
 \end{code}
 
 
+%************************************************************************
+%*                                                                     *
+               The module dependency graph
+               ModSummary, ModGraph, NodeKey, NodeMap
+%*                                                                     *
+%************************************************************************
+
+The nodes of the module graph are
+       EITHER a regular Haskell source module
+       OR     a hi-boot source module
+
+A ModuleGraph contains all the nodes from the home package (only).  
+There will be a node for each source module, plus a node for each hi-boot
+module.
+
+\begin{code}
+type ModuleGraph = [ModSummary]  -- The module graph, 
+                                -- NOT NECESSARILY IN TOPOLOGICAL ORDER
+
+emptyMG :: ModuleGraph
+emptyMG = []
+
+--------------------
+data ModSummary
+   = ModSummary {
+        ms_mod      :: Module,         -- Name of the module
+       ms_boot     :: IsBootInterface, -- Whether this is an hi-boot file
+        ms_location :: ModLocation,    -- Location
+        ms_srcimps  :: [Module],       -- Source imports
+        ms_imps     :: [Module],       -- Non-source imports
+        ms_hs_date  :: ClockTime       -- Timestamp of summarised file
+     }
+
+-- The ModLocation contains both the original source filename and the
+-- filename of the cleaned-up source file after all preprocessing has been
+-- done.  The point is that the summariser will have to cpp/unlit/whatever
+-- all files anyway, and there's no point in doing this twice -- just 
+-- park the result in a temp file, put the name of it in the location,
+-- and let @compile@ read from that file on the way back up.
+
+instance Outputable ModSummary where
+   ppr ms
+      = sep [text "ModSummary {",
+             nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
+                          text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
+                          text "ms_imps =" <+> ppr (ms_imps ms),
+                          text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
+             char '}'
+            ]
+
+ms_allimps ms = ms_srcimps ms ++ ms_imps ms
+
+--------------------
+type NodeKey   = (Module, IsBootInterface)  -- The nodes of the graph are 
+type NodeMap a = FiniteMap NodeKey a       -- keyed by (mod,boot) pairs
+
+msKey :: ModSummary -> NodeKey
+msKey (ModSummary { ms_mod = mod, ms_boot = boot }) = (mod,boot)
+
+emptyNodeMap :: NodeMap a
+emptyNodeMap = emptyFM
+
+mkNodeMap :: [(NodeKey,a)] -> NodeMap a
+mkNodeMap = listToFM
+       
+nodeMapElts :: NodeMap a -> [a]
+nodeMapElts = eltsFM
+\end{code}
+
+
+%************************************************************************
+%*                                                                     *
+               The compilation manager state
+%*                                                                     *
+%************************************************************************
+
+
 \begin{code}
 -- Persistent state for the entire system
 data CmState
@@ -115,7 +198,7 @@ data CmState
      }
 
 #ifdef GHCI
-cmGetModInfo    cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
+cmGetModuleGraph cmstate = cm_mg cmstate
 cmGetBindings    cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
 cmHPT           cmstate = hsc_HPT (cm_hsc cmstate)
@@ -145,7 +228,7 @@ discardCMInfo cm_state
 
 type UnlinkedImage = [Linkable]        -- the unlinked images (should be a set, really)
 
-findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
+findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
 findModuleLinkable_maybe lis mod
    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
         []   -> Nothing
@@ -177,7 +260,7 @@ cmSetContext cmstate toplevs exports = do
       hsc_env = cm_hsc cmstate
       hpt     = hsc_HPT hsc_env
 
-  export_env  <- mkExportEnv hsc_env (map mkModuleName exports)
+  export_env  <- mkExportEnv hsc_env (map mkModule exports)
   toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
 
   let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
@@ -187,7 +270,7 @@ cmSetContext cmstate toplevs exports = do
 
 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
 mkTopLevEnv hpt mod
- = case lookupModuleEnvByName hpt (mkModuleName mod) of
+ = case lookupModuleEnv hpt (mkModule mod) of
       Nothing      -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
       Just details -> case hm_globals details of
                        Nothing  -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
@@ -199,15 +282,19 @@ cmGetContext CmState{cm_ic=ic} =
 
 cmModuleIsInterpreted :: CmState -> String -> IO Bool
 cmModuleIsInterpreted cmstate str 
- = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
+ = case lookupModuleEnv (cmHPT cmstate) (mkModule str) of
       Just details       -> return (isJust (hm_globals details))
       _not_a_home_module -> return False
 
 -----------------------------------------------------------------------------
+
 cmSetDFlags :: CmState -> DynFlags -> CmState
 cmSetDFlags cm_state dflags 
   = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
 
+cmGetDFlags :: CmState -> DynFlags
+cmGetDFlags cm_state = hsc_dflags (cm_hsc cm_state)
+
 -----------------------------------------------------------------------------
 -- cmInfoThing: convert a String to a TyThing
 
@@ -223,7 +310,7 @@ cmGetInfo cmstate id = hscGetInfo (cm_hsc cmstate) (cm_ic cmstate) id
 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
 cmBrowseModule cmstate str exports_only
   = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate) 
-                                      (mkModuleName str) exports_only
+                                      (mkModule str) exports_only
        ; case mb_decls of
           Nothing -> return []         -- An error of some kind
           Just ds -> return ds
@@ -231,6 +318,19 @@ cmBrowseModule cmstate str exports_only
 
 
 -----------------------------------------------------------------------------
+cmShowModule :: CmState -> ModSummary -> String
+cmShowModule cmstate mod_summary
+  = case lookupModuleEnv hpt mod of
+       Nothing       -> panic "missing linkable"
+       Just mod_info -> showModMsg obj_linkable mod locn
+                     where
+                        obj_linkable = isObjectLinkable (hm_linkable mod_info)
+  where
+    hpt  = hsc_HPT (cm_hsc cmstate)
+    mod  = ms_mod mod_summary
+    locn = ms_location mod_summary
+
+-----------------------------------------------------------------------------
 -- cmRunStmt:  Run a statement/expr.
 
 data CmRunResult
@@ -241,7 +341,12 @@ data CmRunResult
 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)            
 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
    = do 
-        maybe_stuff <- hscStmt hsc_env icontext expr
+       -- Turn off -fwarn-unused-bindings when running a statement, to hide
+       -- warnings about the implicit bindings we introduce.
+       let dflags'  = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
+           hsc_env' = hsc_env{ hsc_dflags = dflags' }
+
+        maybe_stuff <- hscStmt hsc_env' icontext expr
 
         case maybe_stuff of
           Nothing -> return (cmstate, CmRunFailed)
@@ -423,7 +528,7 @@ cmDepAnal cmstate rootnames
            hPutStrLn stderr (showSDoc (hcat [
             text "Chasing modules from: ",
             hcat (punctuate comma (map text rootnames))]))
-       downsweep rootnames (cm_mg cmstate)
+       downsweep dflags rootnames (cm_mg cmstate)
   where
     hsc_env = cm_hsc cmstate
     dflags  = hsc_dflags hsc_env
@@ -435,7 +540,7 @@ cmDepAnal cmstate rootnames
 -- the system state at the same time.
 
 cmLoadModules :: CmState               -- The HPT may not be as up to date
-              -> ModuleGraph           -- Bang up to date
+              -> ModuleGraph           -- Bang up to date; but may contain hi-boot no
               -> IO (CmState,          -- new state
                     SuccessFlag,       -- was successful
                     [String])          -- list of modules loaded
@@ -455,22 +560,22 @@ cmLoadModules cmstate1 mg2unsorted
         let 
            main_mod = mb_main_mod `orElse` "Main"
            a_root_is_Main 
-               = any ((==main_mod).moduleNameUserString.modSummaryName) 
+               = any ((==main_mod).moduleUserString.ms_mod) 
                      mg2unsorted
 
-        let mg2unsorted_names = map modSummaryName mg2unsorted
+        let mg2unsorted_names = map ms_mod mg2unsorted
+
+        -- mg2 should be cycle free; but it includes hi-boot ModSummary nodes
+        let mg2 :: [SCC ModSummary]
+           mg2 = topological_sort False mg2unsorted
 
-        -- reachable_from follows source as well as normal imports
-        let reachable_from :: ModuleName -> [ModuleName]
-            reachable_from = downwards_closure_of_module mg2unsorted
-        -- should be cycle free; ignores 'import source's
-        let mg2 = topological_sort False mg2unsorted
-        -- ... whereas this takes them into account.  Used for
+        -- mg2_with_srcimps drops the hi-boot nodes, returning a 
+       -- graph with cycles.  Among other things, it is used for
         -- backing out partially complete cycles following a failed
         -- upsweep, and for removing from hpt all the modules
         -- not in strict downwards closure, during calls to compile.
-        let mg2_with_srcimps = topological_sort True mg2unsorted
+        let mg2_with_srcimps :: [SCC ModSummary]
+           mg2_with_srcimps = topological_sort True mg2unsorted
 
        -- Sort out which linkables we wish to keep in the unlinked image.
        -- See getValidLinkables below for details.
@@ -480,8 +585,7 @@ cmLoadModules cmstate1 mg2unsorted
 
        -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
 
-               -- Uniq of ModuleName is the same as Module, fortunately...
-       let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
+       let hpt2 = delModuleEnvList hpt1 (map linkableModule new_linkables)
             hsc_env2 = hsc_env { hsc_HPT = hpt2 }
 
        -- When (verb >= 2) $
@@ -498,19 +602,17 @@ cmLoadModules cmstate1 mg2unsorted
         -- 1.  All home imports of ms are either in ms or S
         -- 2.  A valid old linkable exists for each module in ms
 
-        stable_mods <- preUpsweep valid_old_linkables
-                                 mg2unsorted_names [] mg2_with_srcimps
-
-        let stable_summaries
-               = concatMap (findInSummaries mg2unsorted) stable_mods
-
-           stable_linkables
-              = filter (\m -> linkableModName m `elem` stable_mods) 
-                   valid_old_linkables
+       -- mg2_with_srcimps has no hi-boot nodes, 
+       -- and hence neither does stable_mods 
+        stable_summaries <- preUpsweep valid_old_linkables
+                                      mg2unsorted_names [] mg2_with_srcimps
+        let stable_mods      = map ms_mod stable_summaries
+           stable_linkables = filter (\m -> linkableModule m `elem` stable_mods) 
+                                     valid_old_linkables
 
         when (verb >= 2) $
            hPutStrLn stderr (showSDoc (text "Stable modules:" 
-                               <+> sep (map (text.moduleNameUserString) stable_mods)))
+                               <+> sep (map (text.moduleUserString) stable_mods)))
 
        -- Unload any modules which are going to be re-linked this
        -- time around.
@@ -525,7 +627,7 @@ cmLoadModules cmstate1 mg2unsorted
         -- done before the upsweep is abandoned.
         let upsweep_these
                = filter (\scc -> any (`notElem` stable_mods) 
-                                     (map modSummaryName (flattenSCC scc)))
+                                     (map ms_mod (flattenSCC scc)))
                         mg2
 
         --hPutStrLn stderr "after tsort:\n"
@@ -540,11 +642,11 @@ cmLoadModules cmstate1 mg2unsorted
         -- turn.  Final result is version 3 of everything.
 
        -- clean up between compilations
-       let cleanup = cleanTempFilesExcept verb 
+       let cleanup = cleanTempFilesExcept dflags
                          (ppFilesFromSummaries (flattenSCCs mg2))
 
         (upsweep_ok, hsc_env3, modsUpswept)
-           <- upsweep_mods hsc_env2 valid_linkables reachable_from 
+           <- upsweep_mods hsc_env2 valid_linkables
                            cleanup upsweep_these
 
         -- At this point, modsUpswept and newLis should have the same
@@ -570,7 +672,7 @@ cmLoadModules cmstate1 mg2unsorted
                 hPutStrLn stderr "Upsweep completely successful."
 
              -- clean up after ourselves
-             cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
+             cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
 
              ofile <- readIORef v_Output_file
              no_hs_main <- readIORef v_NoHsMain
@@ -600,19 +702,19 @@ cmLoadModules cmstate1 mg2unsorted
                hPutStrLn stderr "Upsweep partially successful."
 
               let modsDone_names
-                     = map modSummaryName modsDone
+                     = map ms_mod modsDone
               let mods_to_zap_names 
                      = findPartiallyCompletedCycles modsDone_names 
                          mg2_with_srcimps
               let mods_to_keep
-                     = filter ((`notElem` mods_to_zap_names).modSummaryName) 
+                     = filter ((`notElem` mods_to_zap_names).ms_mod) 
                          modsDone
 
-              let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep) 
+              let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep) 
                                              (hsc_HPT hsc_env3)
 
              -- Clean up after ourselves
-             cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
+             cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
 
              -- Link everything together
               linkresult <- link ghci_mode dflags False hpt4
@@ -633,7 +735,7 @@ cmLoadFinish ok Failed cmstate
 -- newly loaded module, or the Prelude if none were loaded.
 cmLoadFinish ok Succeeded cmstate
   = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
-           mods_loaded = map (moduleNameUserString.modSummaryName) 
+           mods_loaded = map (moduleUserString.ms_mod) 
                             (cm_mg cmstate)
 
        return (new_cmstate, ok, mods_loaded)
@@ -669,16 +771,18 @@ ppFilesFromSummaries summaries
 getValidLinkables
        :: GhciMode
        -> [Linkable]           -- old linkables
-       -> [ModuleName]         -- all home modules
+       -> [Module]             -- all home modules
        -> [SCC ModSummary]     -- all modules in the program, dependency order
        -> IO ( [Linkable],     -- still-valid linkables 
                [Linkable]      -- new linkables we just found
              )
 
-getValidLinkables mode old_linkables all_home_mods module_graph = do
-  ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods) 
-               [] module_graph
-  return (partition_it ls [] [])
+getValidLinkables mode old_linkables all_home_mods module_graph
+  = do {       -- Process the SCCs in bottom-to-top order
+               -- (foldM works left-to-right)
+         ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods) 
+                     [] module_graph
+       ; return (partition_it ls [] []) }
  where
   partition_it []         valid new = (valid,new)
   partition_it ((l,b):ls) valid new 
@@ -686,20 +790,28 @@ getValidLinkables mode old_linkables all_home_mods module_graph = do
        | otherwise = partition_it ls (l:valid) new
 
 
+getValidLinkablesSCC
+       :: GhciMode
+       -> [Linkable]           -- old linkables
+       -> [Module]             -- all home modules
+       -> [(Linkable,Bool)]
+       -> SCC ModSummary
+       -> IO [(Linkable,Bool)]
+
 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
    = let 
          scc             = flattenSCC scc0
-          scc_names       = map modSummaryName scc
+          scc_names       = map ms_mod scc
          home_module m   = m `elem` all_home_mods && m `notElem` scc_names
           scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
                -- NB. ms_imps, not ms_allimps above.  We don't want to
                -- force a module's SOURCE imports to be already compiled for
                -- its object linkable to be valid.
 
-         has_object m = 
-               case findModuleLinkable_maybe (map fst new_linkables) m of
-                   Nothing -> False
-                   Just l  -> isObjectLinkable l
+               -- The new_linkables is only the *valid* linkables below here
+         has_object m = case findModuleLinkable_maybe (map fst new_linkables) m of
+                           Nothing -> False
+                           Just l  -> isObjectLinkable l
 
           objects_allowed = mode == Batch || all has_object scc_allhomeimps
      in do
@@ -729,7 +841,7 @@ getValidLinkable old_linkables objects_allowed new_linkables summary
        -- have a .o-file linkable.  We only permit it if all the
        -- modules it depends on also have .o files; a .o file can't
        -- link to a bytecode module
-   = do let mod_name = modSummaryName summary
+   = do let mod_name = ms_mod summary
 
        maybe_disk_linkable
           <- if (not objects_allowed)
@@ -795,61 +907,46 @@ hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
 --     * has an interface in the HPT (interactive mode only)
 
 preUpsweep :: [Linkable]       -- new valid linkables
-           -> [ModuleName]     -- names of all mods encountered in downsweep
-           -> [ModuleName]     -- accumulating stable modules
+           -> [Module]         -- names of all mods encountered in downsweep
+           -> [ModSummary]     -- accumulating stable modules
            -> [SCC ModSummary]  -- scc-ified mod graph, including src imps
-           -> IO [ModuleName]  -- stable modules
+           -> IO [ModSummary]  -- stable modules
 
 preUpsweep valid_lis all_home_mods stable []  = return stable
 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
    = do let scc = flattenSCC scc0
-            scc_allhomeimps :: [ModuleName]
+            scc_allhomeimps :: [Module]
             scc_allhomeimps 
                = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
             all_imports_in_scc_or_stable
                = all in_stable_or_scc scc_allhomeimps
-            scc_names
-               = map modSummaryName scc
-            in_stable_or_scc m
-               = m `elem` scc_names || m `elem` stable
+           scc_mods     = map ms_mod scc
+            stable_names = scc_mods ++ map ms_mod stable
+            in_stable_or_scc m = m `elem` stable_names
 
            -- now we check for valid linkables: each module in the SCC must 
            -- have a valid linkable (see getValidLinkables above).
-           has_valid_linkable new_summary
-             = isJust (findModuleLinkable_maybe valid_lis modname)
-              where modname = modSummaryName new_summary
+           has_valid_linkable scc_mod
+             = isJust (findModuleLinkable_maybe valid_lis scc_mod)
 
            scc_is_stable = all_imports_in_scc_or_stable
-                         && all has_valid_linkable scc
+                         && all has_valid_linkable scc_mods
 
         if scc_is_stable
-         then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
-         else preUpsweep valid_lis all_home_mods stable sccs
-
+         then preUpsweep valid_lis all_home_mods (scc ++ stable) sccs
+         else preUpsweep valid_lis all_home_mods stable         sccs
 
--- Helper for preUpsweep.  Assuming that new_summary's imports are all
--- stable (in the sense of preUpsweep), determine if new_summary is itself
--- stable, and, if so, in batch mode, return its linkable.
-findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
-findInSummaries old_summaries mod_name
-   = [s | s <- old_summaries, modSummaryName s == mod_name]
-
-findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
-findModInSummaries old_summaries mod
-   = case [s | s <- old_summaries, ms_mod s == mod] of
-        [] -> Nothing
-        (s:_) -> Just s
 
 -- Return (names of) all those in modsDone who are part of a cycle
 -- as defined by theGraph.
-findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
+findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
 findPartiallyCompletedCycles modsDone theGraph
    = chew theGraph
      where
         chew [] = []
         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
         chew ((CyclicSCC vs):rest)
-           = let names_in_this_cycle = nub (map modSummaryName vs)
+           = let names_in_this_cycle = nub (map ms_mod vs)
                  mods_in_this_cycle  
                     = nub ([done | done <- modsDone, 
                                    done `elem` names_in_this_cycle])
@@ -865,7 +962,6 @@ findPartiallyCompletedCycles modsDone theGraph
 -- There better had not be any cyclic groups here -- we check for them.
 upsweep_mods :: HscEnv                 -- Includes up-to-date HPT
              -> [Linkable]             -- Valid linkables
-             -> (ModuleName -> [ModuleName])  -- to construct downward closures
             -> IO ()                 -- how to clean up unwanted tmp files
              -> [SCC ModSummary]      -- mods to do (the worklist)
                                       -- ...... RETURNING ......
@@ -873,31 +969,30 @@ upsweep_mods :: HscEnv                    -- Includes up-to-date HPT
                     HscEnv,            -- With an updated HPT
                     [ModSummary])      -- Mods which succeeded
 
-upsweep_mods hsc_env oldUI reachable_from cleanup
+upsweep_mods hsc_env oldUI cleanup
      []
    = return (Succeeded, hsc_env, [])
 
-upsweep_mods hsc_env oldUI reachable_from cleanup
-     ((CyclicSCC ms):_)
+upsweep_mods hsc_env oldUI cleanup
+     (CyclicSCC ms:_)
    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
-                          unwords (map (moduleNameUserString.modSummaryName) ms))
+                          unwords (map (moduleUserString.ms_mod) ms))
         return (Failed, hsc_env, [])
 
-upsweep_mods hsc_env oldUI reachable_from cleanup
-     ((AcyclicSCC mod):mods)
+upsweep_mods hsc_env oldUI cleanup
+     (AcyclicSCC mod:mods)
    = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
-       --           show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
+       --           show (map (moduleUserString.moduleName.mi_module.hm_iface) 
+       --                     (moduleEnvElts (hsc_HPT hsc_env)))
 
         (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod 
-                                           (reachable_from (modSummaryName mod))
 
        cleanup         -- Remove unwanted tmp files between compilations
 
         if failed ok_flag then
             return (Failed, hsc_env1, [])
          else do 
-            (restOK, hsc_env2, modOKs) 
-                       <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
+            (restOK, hsc_env2, modOKs) <- upsweep_mods hsc_env1 oldUI cleanup mods
              return (restOK, hsc_env2, mod:modOKs)
 
 
@@ -906,41 +1001,34 @@ upsweep_mods hsc_env oldUI reachable_from cleanup
 upsweep_mod :: HscEnv
             -> UnlinkedImage
             -> ModSummary
-            -> [ModuleName]
             -> IO (SuccessFlag, 
                   HscEnv)              -- With updated HPT
 
-upsweep_mod hsc_env oldUI summary1 reachable_inc_me
+upsweep_mod hsc_env oldUI summary1
+   | ms_boot summary1  -- The summary describes an hi-boot file, 
+   =                   -- so there is nothing to do
+     return (Succeeded, hsc_env)
+
+   | otherwise -- The summary describes a regular source file, so compile it
    = do 
         let this_mod = ms_mod summary1
            location = ms_location summary1
-           mod_name = moduleName this_mod
            hpt1     = hsc_HPT hsc_env
 
-        let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
+        let mb_old_iface = case lookupModuleEnv hpt1 this_mod of
                             Just mod_info -> Just (hm_iface mod_info)
                             Nothing       -> Nothing
 
-        let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
+        let maybe_old_linkable = findModuleLinkable_maybe oldUI this_mod
             source_unchanged   = isJust maybe_old_linkable
 
-           reachable_only = filter (/= mod_name) reachable_inc_me
-
-          -- In interactive mode, all home modules below us *must* have an
-          -- interface in the HPT.  We never demand-load home interfaces in
-          -- interactive mode.
-            hpt1_strictDC
-               = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
-                retainInTopLevelEnvs reachable_only hpt1
-           hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
-
             old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
 
            have_object 
               | Just l <- maybe_old_linkable, isObjectLinkable l = True
               | otherwise = False
 
-        compresult <- compile hsc_env_strictDC this_mod location 
+        compresult <- compile hsc_env this_mod location 
                        (ms_hs_date summary1) 
                        source_unchanged have_object mb_old_iface
 
@@ -964,65 +1052,53 @@ upsweep_mod hsc_env oldUI summary1 reachable_inc_me
            CompErrs -> return (Failed, hsc_env)
 
 -- Filter modules in the HPT
-retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
+retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
 retainInTopLevelEnvs keep_these hpt
-   = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
+   = mkModuleEnv [ (mod, fromJust mb_mod_info)
+                | mod <- keep_these
+                , let mb_mod_info = lookupModuleEnv hpt mod
+                , isJust mb_mod_info ]
+
+-----------------------------------------------------------------------------
+topological_sort :: Bool               -- Drop hi-boot nodes? (see below)
+                -> [ModSummary]
+                -> [SCC ModSummary]
+-- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
+--
+-- Drop hi-boot nodes (first boolean arg)? 
+--
+--   False:    treat the hi-boot summaries as nodes of the graph,
+--             so the graph must be acyclic
+--
+--   True:     eliminate the hi-boot nodes, and instead pretend
+--             the a source-import of Foo is an import of Foo
+--             The resulting graph has no hi-boot nodes, but can by cyclic
+
+topological_sort drop_hi_boot_nodes summaries
+   = stronglyConnComp nodes
    where
-     maybeLookupUFM ufm u  = case lookupUFM ufm u of 
-                               Nothing  -> []
-                               Just val -> [(u, val)] 
-
--- Needed to clean up HPT so that we don't get duplicates in inst env
-downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
-downwards_closure_of_module summaries root
-   = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
-         toEdge summ = (modSummaryName summ, 
-                       filter (`elem` all_mods) (ms_allimps summ))
-
-        all_mods = map modSummaryName summaries
-
-         res = simple_transitive_closure (map toEdge summaries) [root]
-     in
---         trace (showSDoc (text "DC of mod" <+> ppr root
---                          <+> text "=" <+> ppr res)) $
-         res
-
--- Calculate transitive closures from a set of roots given an adjacency list
-simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
-simple_transitive_closure graph set 
-   = let set2      = nub (concatMap dsts set ++ set)
-         dsts node = fromMaybe [] (lookup node graph)
-     in
-         if   length set == length set2
-         then set
-         else simple_transitive_closure graph set2
-
-
--- Calculate SCCs of the module graph, with or without taking into
--- account source imports.
-topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
-topological_sort include_source_imports summaries
-   = let 
-         toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
-         toEdge summ
-             = (summ, modSummaryName summ, 
-                      (if include_source_imports 
-                       then ms_srcimps summ else []) ++ ms_imps summ)
-        
-         mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
-         mash_edge (summ, m, m_imports)
-            = case lookup m key_map of
-                 Nothing -> panic "reverse_topological_sort"
-                 Just mk -> (summ, mk, 
-                                -- ignore imports not from the home package
-                             mapCatMaybes (flip lookup key_map) m_imports)
-
-         edges     = map toEdge summaries
-         key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
-         scc_input = map mash_edge edges
-         sccs      = stronglyConnComp scc_input
-     in
-         sccs
+       keep_hi_boot_nodes = not drop_hi_boot_nodes
+
+       -- We use integers as the keys for the SCC algorithm
+       nodes :: [(ModSummary, Int, [Int])]     
+       nodes = [(s, fromJust (lookup_key (ms_boot s) (ms_mod s)), 
+                    out_edge_keys keep_hi_boot_nodes (ms_srcimps s) ++
+                    out_edge_keys False              (ms_imps s)    )
+               | s <- summaries
+               , not (ms_boot s) || keep_hi_boot_nodes ]
+               -- Drop the hi-boot ones if told to do so
+
+       key_map :: NodeMap Int
+       key_map = listToFM ([(ms_mod s, ms_boot s) | s <- summaries]
+                          `zip` [1..])
+
+       lookup_key :: IsBootInterface -> Module -> Maybe Int
+       lookup_key hi_boot mod = lookupFM key_map (mod, hi_boot)
+
+       out_edge_keys :: IsBootInterface -> [Module] -> [Int]
+        out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
+               -- If we want keep_hi_boot_nodes, then we do lookup_key with
+               -- the IsBootInterface parameter True; else False
 
 
 -----------------------------------------------------------------------------
@@ -1036,31 +1112,28 @@ topological_sort include_source_imports summaries
 -- cache to avoid recalculating a module summary if the source is
 -- unchanged.
 
-downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
-downsweep roots old_summaries
+downsweep :: DynFlags -> [FilePath] -> [ModSummary] -> IO [ModSummary]
+downsweep dflags roots old_summaries
    = do rootSummaries <- mapM getRootSummary roots
        checkDuplicates rootSummaries
-        all_summaries
-           <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
-                                           (ms_imps m)) rootSummaries))
-               (mkModuleEnv [ (mod, s) | s <- rootSummaries, 
-                                         let mod = ms_mod s, isHomeModule mod 
-                            ])
-        return all_summaries
+        loop rootSummaries emptyNodeMap
      where
+       old_summary_map :: NodeMap ModSummary
+       old_summary_map = mkNodeMap [ (msKey s, s) | s <- old_summaries]
+
        getRootSummary :: FilePath -> IO ModSummary
        getRootSummary file
           | isHaskellSrcFilename file
           = do exists <- doesFileExist file
-               if exists then summariseFile file else do
+               if exists then summariseFile dflags file else do
                throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))    
           | otherwise
           = do exists <- doesFileExist hs_file
-               if exists then summariseFile hs_file else do
+               if exists then summariseFile dflags hs_file else do
                exists <- doesFileExist lhs_file
-               if exists then summariseFile lhs_file else do
-               let mod_name = mkModuleName file
-               maybe_summary <- getSummary (file, mod_name)
+               if exists then summariseFile dflags lhs_file else do
+               let mod_name = mkModule file
+               maybe_summary <- getSummary file False {- Not hi-boot -} mod_name
                case maybe_summary of
                   Nothing -> packageModErr mod_name
                   Just s  -> return s
@@ -1084,48 +1157,46 @@ downsweep roots old_summaries
                           [ fromJust (ml_hs_file (ms_location summ'))
                           | summ' <- summaries, ms_mod summ' == modl ]
 
-        getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
-        getSummary (currentMod,nm)
-           = do found <- findModule nm
+       loop :: [ModSummary]            -- Work list: process the imports of these modules
+            -> NodeMap ModSummary      -- Visited set
+            -> IO [ModSummary]         -- The result includes the worklist, except 
+                                       -- for those mentioned in the visited set
+       loop [] done      = return (nodeMapElts done)
+       loop (s:ss) done | key `elemFM` done = loop ss done
+                        | otherwise          = do { new_ss <- children s
+                                                  ; loop (new_ss ++ ss) (addToFM done key s) }
+                        where
+                           key = (ms_mod s, ms_boot s)
+
+       children :: ModSummary -> IO [ModSummary]
+       children s = do { mb_kids1 <- mapM (getSummary cur_path True)  (ms_srcimps s)
+                       ; mb_kids2 <- mapM (getSummary cur_path False) (ms_imps s)
+                       ; return (catMaybes mb_kids1 ++ catMaybes mb_kids2) }
+               -- The Nothings are the ones from other packages: ignore
+         where
+           cur_path = fromJust (ml_hs_file (ms_location s))
+
+        getSummary :: FilePath                 -- Import directive is in here [only used for err msg]
+                  -> IsBootInterface   -- Look for an hi-boot file?
+                  -> Module            -- Look for this module
+                  -> IO (Maybe ModSummary)
+        getSummary cur_mod is_boot wanted_mod
+           = do found <- findModule dflags wanted_mod True {-explicit-}
                case found of
-                  Right (mod, location) -> do
-                       let old_summary = findModInSummaries old_summaries mod
-                       summarise mod location old_summary
-
-                  Left files -> do
-                       dflags <- getDynFlags
-                       throwDyn (noModError dflags currentMod nm files)
-
-        -- loop invariant: env doesn't contain package modules
-        loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
-       loop [] env = return (moduleEnvElts env)
-        loop imps env
-           = do -- imports for modules we don't already have
-                let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
+                  Found location pkg 
+                       | isHomePackage pkg     -- Drop an external-package modules
+                       -> do   { let old_summary = lookupFM old_summary_map (wanted_mod, is_boot)
+                               ; summarise dflags wanted_mod is_boot location old_summary }
+                       | otherwise
+                       -> return Nothing       -- External package module
 
-               -- summarise them
-                needed_summaries <- mapM getSummary needed_imps
+                  err -> throwDyn (noModError dflags cur_mod wanted_mod err)
 
-               -- get just the "home" modules
-                let new_home_summaries = [ s | Just s <- needed_summaries ]
-
-               -- loop, checking the new imports
-               let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
-                                                      (ms_imps m)) new_home_summaries)
-                loop new_imps (extendModuleEnvList env 
-                               [ (ms_mod s, s) | s <- new_home_summaries ])
 
 -- ToDo: we don't have a proper line number for this error
-noModError dflags loc mod_nm files = ProgramError (showSDoc (
-  hang (text loc <> colon) 4 $
-    (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
-  ))
-  where
-   extra
-    | verbosity dflags < 3 =
-        text "(use -v to see a list of the files searched for)"
-    | otherwise =
-        hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
+noModError dflags loc mod_nm err
+  = ProgramError (showSDoc (hang (text loc <> colon) 4 $
+                               noIfaceErr dflags mod_nm err))
 
 -----------------------------------------------------------------------------
 -- Summarising modules
@@ -1140,62 +1211,76 @@ noModError dflags loc mod_nm files = ProgramError (showSDoc (
 --     a summary.  The finder is used to locate the file in which the module
 --     resides.
 
-summariseFile :: FilePath -> IO ModSummary
-summariseFile file
-   = do hspp_fn <- preprocess file
-        (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
+summariseFile :: DynFlags -> FilePath -> IO ModSummary
+summariseFile dflags file
+   = do hspp_fn <- preprocess dflags file
+
+       -- Read the file into a buffer.  We're going to cache
+       -- this buffer in the ModLocation (ml_hspp_buf) so that it
+       -- doesn't have to be slurped again when hscMain parses the
+       -- file later.
+       buf <- hGetStringBuffer hspp_fn
+        (srcimps,imps,mod) <- getImports dflags buf hspp_fn
 
         let -- GHC.Prim doesn't exist physically, so don't go looking for it.
-            the_imps = filter (/= gHC_PRIM_Name) imps
+            the_imps = filter (/= gHC_PRIM) imps
 
-       (mod, location) <- mkHomeModLocation mod_name file
+       location <- mkHomeModLocation mod file
 
         src_timestamp
            <- case ml_hs_file location of 
-                 Nothing     -> noHsFileErr mod_name
+                 Nothing     -> noHsFileErr mod
                  Just src_fn -> getModificationTime src_fn
 
-        return (ModSummary { ms_mod = mod, 
+        return (ModSummary { ms_mod = mod, ms_boot = False,
                              ms_location = location{ml_hspp_file=Just hspp_fn},
                              ms_srcimps = srcimps, ms_imps = the_imps,
                             ms_hs_date = src_timestamp })
 
 -- Summarise a module, and pick up source and timestamp.
-summarise :: Module -> ModLocation -> Maybe ModSummary
-        -> IO (Maybe ModSummary)
-summarise mod location old_summary
-   | not (isHomeModule mod) = return Nothing
-   | otherwise
-   = do let hs_fn = expectJust "summarise" (ml_hs_file location)
-
-        case ml_hs_file location of {
-           Nothing -> noHsFileErr mod;
-           Just src_fn -> do
-
-        src_timestamp <- getModificationTime src_fn
+summarise :: DynFlags 
+         -> Module             -- Guaranteed a home-package module
+         -> IsBootInterface 
+         -> ModLocation -> Maybe ModSummary
+         -> IO (Maybe ModSummary)
+summarise dflags mod is_boot location old_summary
+ = do  { -- Find the source file to summarise
+         src_fn <- if is_boot then
+                       hiBootFilePath location
+                   else
+                   case ml_hs_file location of
+                       Nothing     -> noHsFileErr mod
+                       Just src_fn -> return src_fn
+
+       -- Find its timestamp
+       ; src_timestamp <- getModificationTime src_fn
 
        -- return the cached summary if the source didn't change
-       case old_summary of {
-          Just s | ms_hs_date s == src_timestamp -> return (Just s);
-          _ -> do
+       ; case old_summary of {
+            Just s | ms_hs_date s == src_timestamp -> return (Just s);
+            _ -> do
+
+       -- For now, we never pre-process hi-boot files
+       { hspp_fn <- if is_boot then return src_fn
+                             else preprocess dflags src_fn
 
-        hspp_fn <- preprocess hs_fn
-        (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
-       let
+       ; buf <- hGetStringBuffer hspp_fn
+        ; (srcimps,imps,mod_name) <- getImports dflags buf hspp_fn
+       ; let
             -- GHC.Prim doesn't exist physically, so don't go looking for it.
-           the_imps = filter (/= gHC_PRIM_Name) imps
+             the_imps = filter (/= gHC_PRIM) imps
 
-       when (mod_name /= moduleName mod) $
+       ; when (mod_name /= mod) $
                throwDyn (ProgramError 
-                  (showSDoc (text hs_fn
+                  (showSDoc (text src_fn
                              <>  text ": file name does not match module name"
-                             <+> quotes (ppr (moduleName mod)))))
-
-        return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
-                                 srcimps the_imps src_timestamp))
-        }
-      }
+                             <+> quotes (ppr mod))))
 
+       ; let new_loc = location{ ml_hspp_file = Just hspp_fn,
+                                 ml_hspp_buf  = Just buf }
+       ; return (Just (ModSummary mod is_boot new_loc
+                                   srcimps the_imps src_timestamp))
+    }}}
 
 noHsFileErr mod
   = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
@@ -1213,47 +1298,3 @@ multiRootsErr mod files
 \end{code}
 
 
-%************************************************************************
-%*                                                                     *
-               The ModSummary Type
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
--- The ModLocation contains both the original source filename and the
--- filename of the cleaned-up source file after all preprocessing has been
--- done.  The point is that the summariser will have to cpp/unlit/whatever
--- all files anyway, and there's no point in doing this twice -- just 
--- park the result in a temp file, put the name of it in the location,
--- and let @compile@ read from that file on the way back up.
-
-
-type ModuleGraph = [ModSummary]  -- the module graph, topologically sorted
-
-emptyMG :: ModuleGraph
-emptyMG = []
-
-data ModSummary
-   = ModSummary {
-        ms_mod      :: Module,                 -- name, package
-        ms_location :: ModLocation,            -- location
-        ms_srcimps  :: [ModuleName],           -- source imports
-        ms_imps     :: [ModuleName],           -- non-source imports
-        ms_hs_date  :: ClockTime               -- timestamp of summarised file
-     }
-
-instance Outputable ModSummary where
-   ppr ms
-      = sep [text "ModSummary {",
-             nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
-                          text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
-                          text "ms_imps =" <+> ppr (ms_imps ms),
-                          text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
-             char '}'
-            ]
-
-ms_allimps ms = ms_srcimps ms ++ ms_imps ms
-
-modSummaryName :: ModSummary -> ModuleName
-modSummaryName = moduleName . ms_mod
-\end{code}