[project @ 2005-02-04 15:43:28 by simonpj]
[ghc-hetmet.git] / ghc / compiler / compMan / CompManager.lhs
1 %
2 % (c) The University of Glasgow, 2002
3 %
4 % The Compilation Manager
5 %
6 \begin{code}
7 module CompManager ( 
8     ModSummary,         -- Abstract
9     ModuleGraph,        -- All the modules from the home package
10
11     CmState,            -- Abstract
12
13     cmInit,        -- :: GhciMode -> IO CmState
14
15     cmDepAnal,     -- :: CmState -> [FilePath] -> IO ModuleGraph
16     cmDownsweep,   
17     cmTopSort,     -- :: Bool -> ModuleGraph -> [SCC ModSummary]
18     cyclicModuleErr,    -- :: [ModSummary] -> String    -- Used by DriverMkDepend
19
20     cmLoadModules, -- :: CmState -> ModuleGraph
21                    --    -> IO (CmState, Bool, [String])
22
23     cmUnload,      -- :: CmState -> IO CmState
24
25
26 #ifdef GHCI
27     cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
28
29     cmSetContext,  -- :: CmState -> [String] -> [String] -> IO CmState
30     cmGetContext,  -- :: CmState -> IO ([String],[String])
31
32     cmGetInfo,    -- :: CmState -> String -> IO (CmState, [(TyThing,Fixity)])
33     GetInfoResult,
34     cmBrowseModule, -- :: CmState -> IO [TyThing]
35     cmShowModule,
36
37     CmRunResult(..),
38     cmRunStmt,          -- :: CmState -> String -> IO (CmState, CmRunResult)
39
40     cmTypeOfExpr,       -- :: CmState -> String -> IO (CmState, Maybe String)
41     cmKindOfType,       -- :: CmState -> String -> IO (CmState, Maybe String)
42     cmTypeOfName,       -- :: CmState -> Name -> IO (Maybe String)
43
44     HValue,
45     cmCompileExpr,      -- :: CmState -> String -> IO (CmState, Maybe HValue)
46     cmGetModuleGraph,   -- :: CmState -> ModuleGraph
47     cmSetDFlags,
48     cmGetDFlags,
49
50     cmGetBindings,      -- :: CmState -> [TyThing]
51     cmGetPrintUnqual,   -- :: CmState -> PrintUnqualified
52 #endif
53   )
54 where
55
56 #include "HsVersions.h"
57
58 import Packages         ( isHomePackage )
59 import DriverPipeline   ( CompResult(..), preprocess, compile, link )
60 import HscMain          ( newHscEnv )
61 import DriverState      ( v_Output_file, v_NoHsMain, v_MainModIs )
62 import DriverPhases     ( HscSource(..), isHsBoot, hscSourceString, isHaskellSrcFilename )
63 import Finder           ( findModule, findLinkable, addHomeModuleToFinder, flushFinderCache, 
64                           mkHomeModLocation, FindResult(..), cantFindError )
65 import HscTypes         ( ModSummary(..), HomeModInfo(..), ModIface(..), msHsFilePath,
66                           HscEnv(..), GhciMode(..), 
67                           InteractiveContext(..), emptyInteractiveContext, 
68                           HomePackageTable, emptyHomePackageTable, IsBootInterface,
69                           Linkable(..), isObjectLinkable )
70 import Module           ( Module, mkModule, delModuleEnv, delModuleEnvList, mkModuleEnv,
71                           lookupModuleEnv, moduleEnvElts, extendModuleEnv, filterModuleEnv,
72                           moduleUserString, addBootSuffixLocn, 
73                           ModLocation(..) )
74 import GetImports       ( getImports )
75 import Digraph          ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
76 import ErrUtils         ( showPass )
77 import SysTools         ( cleanTempFilesExcept )
78 import BasicTypes       ( SuccessFlag(..), succeeded )
79 import StringBuffer     ( hGetStringBuffer )
80 import Util
81 import Outputable
82 import Panic
83 import CmdLineOpts      ( DynFlags(..) )
84 import Maybes           ( expectJust, orElse, mapCatMaybes )
85 import FiniteMap
86
87 import DATA_IOREF       ( readIORef )
88
89 #ifdef GHCI
90 import HscMain          ( hscGetInfo, GetInfoResult, hscStmt, hscTcExpr, hscKcType )
91 import HscTypes         ( TyThing(..), icPrintUnqual, showModMsg )
92 import TcRnDriver       ( mkExportEnv, getModuleContents )
93 import IfaceSyn         ( IfaceDecl )
94 import RdrName          ( GlobalRdrEnv, plusGlobalRdrEnv )
95 import Name             ( Name )
96 import NameEnv
97 import Id               ( idType )
98 import Type             ( tidyType )
99 import VarEnv           ( emptyTidyEnv )
100 import Linker           ( HValue, unload, extendLinkEnv )
101 import GHC.Exts         ( unsafeCoerce# )
102 import Foreign
103 import Control.Exception as Exception ( Exception, try )
104 import CmdLineOpts      ( DynFlag(..), dopt_unset )
105 #endif
106
107 import EXCEPTION        ( throwDyn )
108
109 -- std
110 import Directory        ( getModificationTime, doesFileExist )
111 import IO
112 import Monad
113 import List             ( nub )
114 import Maybe
115 \end{code}
116
117
118 %************************************************************************
119 %*                                                                      *
120                 The module dependency graph
121                 ModSummary, ModGraph, NodeKey, NodeMap
122 %*                                                                      *
123 %************************************************************************
124
125 The nodes of the module graph are
126         EITHER a regular Haskell source module
127         OR     a hi-boot source module
128
129 A ModuleGraph contains all the nodes from the home package (only).  
130 There will be a node for each source module, plus a node for each hi-boot
131 module.
132
133 \begin{code}
134 type ModuleGraph = [ModSummary]  -- The module graph, 
135                                  -- NOT NECESSARILY IN TOPOLOGICAL ORDER
136
137 emptyMG :: ModuleGraph
138 emptyMG = []
139
140 --------------------
141 ms_allimps :: ModSummary -> [Module]
142 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
143
144 --------------------
145 type NodeKey   = (Module, HscSource)      -- The nodes of the graph are 
146 type NodeMap a = FiniteMap NodeKey a      -- keyed by (mod, src_file_type) pairs
147
148 msKey :: ModSummary -> NodeKey
149 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
150
151 emptyNodeMap :: NodeMap a
152 emptyNodeMap = emptyFM
153
154 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
155 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
156         
157 nodeMapElts :: NodeMap a -> [a]
158 nodeMapElts = eltsFM
159 \end{code}
160
161
162 %************************************************************************
163 %*                                                                      *
164                 The compilation manager state
165 %*                                                                      *
166 %************************************************************************
167
168
169 \begin{code}
170 -- Persistent state for the entire system
171 data CmState
172    = CmState {
173         cm_hsc :: HscEnv,               -- Includes the home-package table
174         cm_mg  :: ModuleGraph,          -- The module graph
175         cm_ic  :: InteractiveContext    -- Command-line binding info
176      }
177
178 #ifdef GHCI
179 cmGetModuleGraph cmstate = cm_mg cmstate
180 cmGetBindings    cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
181 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
182 cmHPT            cmstate = hsc_HPT (cm_hsc cmstate)
183 #endif
184
185 cmInit :: GhciMode -> DynFlags -> IO CmState
186 cmInit ghci_mode dflags
187    = do { hsc_env <- newHscEnv ghci_mode dflags
188         ; return (CmState { cm_hsc = hsc_env,
189                             cm_mg  = emptyMG, 
190                             cm_ic  = emptyInteractiveContext })}
191
192 discardCMInfo :: CmState -> CmState
193 -- Forget the compilation manager's state, including the home package table
194 -- but retain the persistent info in HscEnv
195 discardCMInfo cm_state
196   = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
197                cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
198
199 -------------------------------------------------------------------
200 --                      The unlinked image
201 -- 
202 -- The compilation manager keeps a list of compiled, but as-yet unlinked
203 -- binaries (byte code or object code).  Even when it links bytecode
204 -- it keeps the unlinked version so it can re-link it later without
205 -- recompiling.
206
207 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
208
209 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
210 findModuleLinkable_maybe lis mod
211    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
212         []   -> Nothing
213         [li] -> Just li
214         many -> pprPanic "findModuleLinkable" (ppr mod)
215
216 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
217 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
218 \end{code}
219
220
221 %************************************************************************
222 %*                                                                      *
223         GHCI stuff
224 %*                                                                      *
225 %************************************************************************
226
227 \begin{code}
228 #ifdef GHCI
229 -----------------------------------------------------------------------------
230 -- Setting the context doesn't throw away any bindings; the bindings
231 -- we've built up in the InteractiveContext simply move to the new
232 -- module.  They always shadow anything in scope in the current context.
233
234 cmSetContext
235         :: CmState
236         -> [String]             -- take the top-level scopes of these modules
237         -> [String]             -- and the just the exports from these
238         -> IO CmState
239 cmSetContext cmstate toplevs exports = do 
240   let old_ic  = cm_ic cmstate
241       hsc_env = cm_hsc cmstate
242       hpt     = hsc_HPT hsc_env
243
244   export_env  <- mkExportEnv hsc_env (map mkModule exports)
245   toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
246
247   let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
248   return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
249                                    ic_exports      = exports,
250                                    ic_rn_gbl_env   = all_env } }
251
252 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
253 mkTopLevEnv hpt mod
254  = case lookupModuleEnv hpt (mkModule mod) of
255       Nothing      -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
256       Just details -> case hm_globals details of
257                         Nothing  -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
258                         Just env -> return env
259
260 cmGetContext :: CmState -> IO ([String],[String])
261 cmGetContext CmState{cm_ic=ic} = 
262   return (ic_toplev_scope ic, ic_exports ic)
263
264 cmModuleIsInterpreted :: CmState -> String -> IO Bool
265 cmModuleIsInterpreted cmstate str 
266  = case lookupModuleEnv (cmHPT cmstate) (mkModule str) of
267       Just details       -> return (isJust (hm_globals details))
268       _not_a_home_module -> return False
269
270 -----------------------------------------------------------------------------
271
272 cmSetDFlags :: CmState -> DynFlags -> CmState
273 cmSetDFlags cm_state dflags 
274   = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
275
276 cmGetDFlags :: CmState -> DynFlags
277 cmGetDFlags cm_state = hsc_dflags (cm_hsc cm_state)
278
279 -----------------------------------------------------------------------------
280 -- cmInfoThing: convert a String to a TyThing
281
282 -- A string may refer to more than one TyThing (eg. a constructor,
283 -- and type constructor), so we return a list of all the possible TyThings.
284
285 cmGetInfo :: CmState -> String -> IO [GetInfoResult]
286 cmGetInfo cmstate id = hscGetInfo (cm_hsc cmstate) (cm_ic cmstate) id
287
288 -- ---------------------------------------------------------------------------
289 -- cmBrowseModule: get all the TyThings defined in a module
290
291 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
292 cmBrowseModule cmstate str exports_only
293   = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate) 
294                                        (mkModule str) exports_only
295        ; case mb_decls of
296            Nothing -> return []         -- An error of some kind
297            Just ds -> return ds
298    }
299
300
301 -----------------------------------------------------------------------------
302 cmShowModule :: CmState -> ModSummary -> String
303 cmShowModule cmstate mod_summary
304   = case lookupModuleEnv hpt (ms_mod mod_summary) of
305         Nothing       -> panic "missing linkable"
306         Just mod_info -> showModMsg obj_linkable mod_summary
307                       where
308                          obj_linkable = isObjectLinkable (hm_linkable mod_info)
309   where
310     hpt  = hsc_HPT (cm_hsc cmstate)
311
312 -----------------------------------------------------------------------------
313 -- cmRunStmt:  Run a statement/expr.
314
315 data CmRunResult
316   = CmRunOk [Name]              -- names bound by this evaluation
317   | CmRunFailed 
318   | CmRunException Exception    -- statement raised an exception
319
320 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)             
321 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
322    = do 
323         -- Turn off -fwarn-unused-bindings when running a statement, to hide
324         -- warnings about the implicit bindings we introduce.
325         let dflags'  = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
326             hsc_env' = hsc_env{ hsc_dflags = dflags' }
327
328         maybe_stuff <- hscStmt hsc_env' icontext expr
329
330         case maybe_stuff of
331            Nothing -> return (cmstate, CmRunFailed)
332            Just (new_ic, names, hval) -> do
333
334                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
335                 either_hvals <- sandboxIO thing_to_run
336
337                 case either_hvals of
338                     Left e -> do
339                         -- on error, keep the *old* interactive context,
340                         -- so that 'it' is not bound to something
341                         -- that doesn't exist.
342                         return ( cmstate, CmRunException e )
343
344                     Right hvals -> do
345                         -- Get the newly bound things, and bind them.  
346                         -- Don't need to delete any shadowed bindings;
347                         -- the new ones override the old ones. 
348                         extendLinkEnv (zip names hvals)
349                         
350                         return (cmstate{ cm_ic=new_ic }, 
351                                 CmRunOk names)
352
353
354 -- We run the statement in a "sandbox" to protect the rest of the
355 -- system from anything the expression might do.  For now, this
356 -- consists of just wrapping it in an exception handler, but see below
357 -- for another version.
358
359 sandboxIO :: IO a -> IO (Either Exception a)
360 sandboxIO thing = Exception.try thing
361
362 {-
363 -- This version of sandboxIO runs the expression in a completely new
364 -- RTS main thread.  It is disabled for now because ^C exceptions
365 -- won't be delivered to the new thread, instead they'll be delivered
366 -- to the (blocked) GHCi main thread.
367
368 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
369
370 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
371 sandboxIO thing = do
372   st_thing <- newStablePtr (Exception.try thing)
373   alloca $ \ p_st_result -> do
374     stat <- rts_evalStableIO st_thing p_st_result
375     freeStablePtr st_thing
376     if stat == 1
377         then do st_result <- peek p_st_result
378                 result <- deRefStablePtr st_result
379                 freeStablePtr st_result
380                 return (Right result)
381         else do
382                 return (Left (fromIntegral stat))
383
384 foreign import "rts_evalStableIO"  {- safe -}
385   rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
386   -- more informative than the C type!
387 -}
388
389 -----------------------------------------------------------------------------
390 -- cmTypeOfExpr: returns a string representing the type of an expression
391
392 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
393 cmTypeOfExpr cmstate expr
394    = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
395
396         case maybe_stuff of
397            Nothing -> return Nothing
398            Just ty -> return (Just res_str)
399              where 
400                 res_str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
401                 unqual  = icPrintUnqual (cm_ic cmstate)
402                 tidy_ty = tidyType emptyTidyEnv ty
403
404
405 -----------------------------------------------------------------------------
406 -- cmKindOfType: returns a string representing the kind of a type
407
408 cmKindOfType :: CmState -> String -> IO (Maybe String)
409 cmKindOfType cmstate str
410    = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
411         case maybe_stuff of
412            Nothing -> return Nothing
413            Just kind -> return (Just res_str)
414              where 
415                 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
416                 unqual  = icPrintUnqual (cm_ic cmstate)
417
418 -----------------------------------------------------------------------------
419 -- cmTypeOfName: returns a string representing the type of a name.
420
421 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
422 cmTypeOfName CmState{ cm_ic=ic } name
423  = do 
424     hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
425     case lookupNameEnv (ic_type_env ic) name of
426         Nothing        -> return Nothing
427         Just (AnId id) -> return (Just str)
428            where
429              unqual = icPrintUnqual ic
430              ty = tidyType emptyTidyEnv (idType id)
431              str = showSDocForUser unqual (ppr ty)
432
433         _ -> panic "cmTypeOfName"
434
435 -----------------------------------------------------------------------------
436 -- cmCompileExpr: compile an expression and deliver an HValue
437
438 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
439 cmCompileExpr cmstate expr
440    = do 
441         maybe_stuff 
442             <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
443                        ("let __cmCompileExpr = "++expr)
444
445         case maybe_stuff of
446            Nothing -> return Nothing
447            Just (new_ic, names, hval) -> do
448
449                         -- Run it!
450                 hvals <- (unsafeCoerce# hval) :: IO [HValue]
451
452                 case (names,hvals) of
453                   ([n],[hv]) -> return (Just hv)
454                   _          -> panic "cmCompileExpr"
455
456 #endif /* GHCI */
457 \end{code}
458
459
460 %************************************************************************
461 %*                                                                      *
462         Loading and unloading
463 %*                                                                      *
464 %************************************************************************
465
466 \begin{code}
467 -----------------------------------------------------------------------------
468 -- Unload the compilation manager's state: everything it knows about the
469 -- current collection of modules in the Home package.
470
471 cmUnload :: CmState -> IO CmState
472 cmUnload state@CmState{ cm_hsc = hsc_env }
473  = do -- Throw away the old home dir cache
474       flushFinderCache
475
476       -- Unload everything the linker knows about
477       cm_unload hsc_env []
478
479       -- Start with a fresh CmState, but keep the PersistentCompilerState
480       return (discardCMInfo state)
481
482 cm_unload hsc_env stable_linkables      -- Unload everthing *except* 'stable_linkables'
483   = case hsc_mode hsc_env of
484         Batch -> return ()
485 #ifdef GHCI
486         Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
487 #else
488         Interactive -> panic "cm_unload: no interpreter"
489 #endif
490         other -> panic "cm_unload: strange mode"
491     
492
493 -----------------------------------------------------------------------------
494 -- Trace dependency graph
495
496 -- This is a seperate pass so that the caller can back off and keep
497 -- the current state if the downsweep fails.  Typically the caller
498 -- might go     cmDepAnal
499 --              cmUnload
500 --              cmLoadModules
501 -- He wants to do the dependency analysis before the unload, so that
502 -- if the former fails he can use the later
503
504 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
505 cmDepAnal cmstate rootnames
506   = do showPass dflags "Chasing dependencies"
507        when (verbosity dflags >= 1 && gmode == Batch) $
508            hPutStrLn stderr (showSDoc (hcat [
509              text "Chasing modules from: ",
510              hcat (punctuate comma (map text rootnames))]))
511        cmDownsweep dflags rootnames (cm_mg cmstate) []
512   where
513     hsc_env = cm_hsc cmstate
514     dflags  = hsc_dflags hsc_env
515     gmode   = hsc_mode hsc_env
516
517 -----------------------------------------------------------------------------
518 -- The real business of the compilation manager: given a system state and
519 -- a module name, try and bring the module up to date, probably changing
520 -- the system state at the same time.
521
522 cmLoadModules :: CmState                -- The HPT may not be as up to date
523               -> ModuleGraph            -- Bang up to date; but may contain hi-boot no
524               -> IO (CmState,           -- new state
525                      SuccessFlag,       -- was successful
526                      [String])          -- list of modules loaded
527
528 cmLoadModules cmstate1 mg2unsorted
529    = do -- version 1's are the original, before downsweep
530         let hsc_env   = cm_hsc cmstate1
531         let hpt1      = hsc_HPT hsc_env
532         let ghci_mode = hsc_mode   hsc_env -- this never changes
533         let dflags    = hsc_dflags hsc_env -- this never changes
534
535         -- Do the downsweep to reestablish the module graph
536         let verb = verbosity dflags
537
538         -- Find out if we have a Main module
539         mb_main_mod <- readIORef v_MainModIs
540         let 
541             main_mod = mb_main_mod `orElse` "Main"
542             a_root_is_Main 
543                = any ((==main_mod).moduleUserString.ms_mod) 
544                      mg2unsorted
545
546         let mg2unsorted_names = map ms_mod mg2unsorted
547
548         -- mg2 should be cycle free; but it includes hi-boot ModSummary nodes
549         let mg2 :: [SCC ModSummary]
550             mg2 = cmTopSort False mg2unsorted
551
552         -- mg2_with_srcimps drops the hi-boot nodes, returning a 
553         -- graph with cycles.  Among other things, it is used for
554         -- backing out partially complete cycles following a failed
555         -- upsweep, and for removing from hpt all the modules
556         -- not in strict downwards closure, during calls to compile.
557         let mg2_with_srcimps :: [SCC ModSummary]
558             mg2_with_srcimps = cmTopSort True mg2unsorted
559
560         -- Sort out which linkables we wish to keep in the unlinked image.
561         -- See getValidLinkables below for details.
562         (valid_old_linkables, new_linkables)
563             <- getValidLinkables ghci_mode (hptLinkables hpt1)
564                   mg2unsorted_names mg2_with_srcimps
565
566         -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
567
568         -- The new_linkables are .o files we found on the disk, presumably
569         -- as a result of a GHC run "on the side".  So we'd better forget
570         -- everything we know abouut those modules!
571         let old_hpt = delModuleEnvList hpt1 (map linkableModule new_linkables)
572
573         -- When (verb >= 2) $
574         --    putStrLn (showSDoc (text "Valid linkables:" 
575         --                       <+> ppr valid_linkables))
576
577         -- Figure out a stable set of modules which can be retained
578         -- the top level envs, to avoid upsweeping them.  Goes to a
579         -- bit of trouble to avoid upsweeping module cycles.
580         --
581         -- Construct a set S of stable modules like this:
582         -- Travel upwards, over the sccified graph.  For each scc
583         -- of modules ms, add ms to S only if:
584         -- 1.  All home imports of ms are either in ms or S
585         -- 2.  A valid old linkable exists for each module in ms
586
587         -- mg2_with_srcimps has no hi-boot nodes, 
588         -- and hence neither does stable_mods 
589         stable_summaries <- preUpsweep valid_old_linkables
590                                        mg2unsorted_names [] mg2_with_srcimps
591         let stable_mods      = map ms_mod stable_summaries
592             stable_linkables = filter (\m -> linkableModule m `elem` stable_mods) 
593                                       valid_old_linkables
594
595             stable_hpt = filterModuleEnv is_stable_hm hpt1
596             is_stable_hm hm_info = mi_module (hm_iface hm_info) `elem` stable_mods
597
598             upsweep_these
599                = filter (\scc -> any (`notElem` stable_mods) 
600                                      (map ms_mod (flattenSCC scc)))
601                         mg2
602
603         when (verb >= 2) $
604            hPutStrLn stderr (showSDoc (text "Stable modules:" 
605                                <+> sep (map (text.moduleUserString) stable_mods)))
606
607         -- Unload any modules which are going to be re-linked this time around.
608         cm_unload hsc_env stable_linkables
609
610         -- We can now glom together our linkable sets
611         let valid_linkables = valid_old_linkables ++ new_linkables
612
613         -- We could at this point detect cycles which aren't broken by
614         -- a source-import, and complain immediately, but it seems better
615         -- to let upsweep_mods do this, so at least some useful work gets
616         -- done before the upsweep is abandoned.
617         --hPutStrLn stderr "after tsort:\n"
618         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
619
620         -- Because we don't take into account source imports when doing
621         -- the topological sort, there shouldn't be any cycles in mg2.
622         -- If there is, we complain and give up -- the user needs to
623         -- break the cycle using a boot file.
624
625         -- Now do the upsweep, calling compile for each module in
626         -- turn.  Final result is version 3 of everything.
627
628         -- clean up between compilations
629         let cleanup = cleanTempFilesExcept dflags
630                           (ppFilesFromSummaries (flattenSCCs mg2))
631
632         (upsweep_ok, hsc_env3, modsUpswept)
633            <- upsweep_mods (hsc_env { hsc_HPT = stable_hpt })
634                            (old_hpt, valid_linkables)
635                            cleanup upsweep_these
636
637         -- At this point, modsUpswept and newLis should have the same
638         -- length, so there is one new (or old) linkable for each 
639         -- mod which was processed (passed to compile).
640
641         -- Make modsDone be the summaries for each home module now
642         -- available; this should equal the domain of hpt3.
643         -- (NOT STRICTLY TRUE if an interactive session was started
644         --  with some object on disk ???)
645         -- Get in in a roughly top .. bottom order (hence reverse).
646
647         let modsDone = reverse modsUpswept ++ stable_summaries
648
649         -- Try and do linking in some form, depending on whether the
650         -- upsweep was completely or only partially successful.
651
652         if succeeded upsweep_ok
653
654          then 
655            -- Easy; just relink it all.
656            do when (verb >= 2) $ 
657                  hPutStrLn stderr "Upsweep completely successful."
658
659               -- clean up after ourselves
660               cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
661
662               ofile <- readIORef v_Output_file
663               no_hs_main <- readIORef v_NoHsMain
664
665               -- Issue a warning for the confusing case where the user
666               -- said '-o foo' but we're not going to do any linking.
667               -- We attempt linking if either (a) one of the modules is
668               -- called Main, or (b) the user said -no-hs-main, indicating
669               -- that main() is going to come from somewhere else.
670               --
671               let do_linking = a_root_is_Main || no_hs_main
672               when (ghci_mode == Batch && isJust ofile && not do_linking
673                      && verb > 0) $
674                  hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
675
676               -- link everything together
677               linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
678
679               let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
680               cmLoadFinish Succeeded linkresult cmstate3
681
682          else 
683            -- Tricky.  We need to back out the effects of compiling any
684            -- half-done cycles, both so as to clean up the top level envs
685            -- and to avoid telling the interactive linker to link them.
686            do when (verb >= 2) $
687                 hPutStrLn stderr "Upsweep partially successful."
688
689               let modsDone_names
690                      = map ms_mod modsDone
691               let mods_to_zap_names 
692                      = findPartiallyCompletedCycles modsDone_names 
693                           mg2_with_srcimps
694               let mods_to_keep
695                      = filter ((`notElem` mods_to_zap_names).ms_mod) 
696                           modsDone
697
698               let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep) 
699                                               (hsc_HPT hsc_env3)
700
701               -- Clean up after ourselves
702               cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
703
704               -- Link everything together
705               linkresult <- link ghci_mode dflags False hpt4
706
707               let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
708                                         cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
709               cmLoadFinish Failed linkresult cmstate3
710
711
712 -- Finish up after a cmLoad.
713
714 -- If the link failed, unload everything and return.
715 cmLoadFinish ok Failed cmstate
716   = do cm_unload (cm_hsc cmstate) []
717        return (discardCMInfo cmstate, Failed, [])
718
719 -- Empty the interactive context and set the module context to the topmost
720 -- newly loaded module, or the Prelude if none were loaded.
721 cmLoadFinish ok Succeeded cmstate
722   = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
723            mods_loaded = map (moduleUserString.ms_mod) 
724                              (cm_mg cmstate)
725
726        return (new_cmstate, ok, mods_loaded)
727
728 -- used to fish out the preprocess output files for the purposes of
729 -- cleaning up.  The preprocessed file *might* be the same as the
730 -- source file, but that doesn't do any harm.
731 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
732
733 -----------------------------------------------------------------------------
734 -- getValidLinkables
735
736 -- For each module (or SCC of modules), we take:
737 --
738 --      - an on-disk linkable, if this is the first time around and one
739 --        is available.
740 --
741 --      - the old linkable, otherwise (and if one is available).
742 --
743 -- and we throw away the linkable if it is older than the source file.
744 -- In interactive mode, we also ignore the on-disk linkables unless
745 -- all of the dependents of this SCC also have on-disk linkables (we
746 -- can't have dynamically loaded objects that depend on interpreted
747 -- modules in GHCi).
748 --
749 -- If a module has a valid linkable, then it may be STABLE (see below),
750 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
751 -- compile.
752 --
753 -- ToDo: this pass could be merged with the preUpsweep.
754
755 getValidLinkables
756         :: GhciMode
757         -> [Linkable]           -- old linkables
758         -> [Module]             -- all home modules
759         -> [SCC ModSummary]     -- all modules in the program, dependency order
760         -> IO ( [Linkable],     -- still-valid linkables 
761                 [Linkable]      -- new linkables we just found on the disk
762                                 -- presumably generated by separate run of ghc
763               )
764
765 getValidLinkables mode old_linkables all_home_mods module_graph
766   = do  {       -- Process the SCCs in bottom-to-top order
767                 -- (foldM works left-to-right)
768           ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods) 
769                       [] module_graph
770         ; return (partition_it ls [] []) }
771  where
772   partition_it []         valid new = (valid,new)
773   partition_it ((l,b):ls) valid new 
774         | b         = partition_it ls valid (l:new)
775         | otherwise = partition_it ls (l:valid) new
776
777
778 getValidLinkablesSCC
779         :: GhciMode
780         -> [Linkable]           -- old linkables
781         -> [Module]             -- all home modules
782         -> [(Linkable,Bool)]
783         -> SCC ModSummary
784         -> IO [(Linkable,Bool)]
785
786 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
787    = let 
788           scc             = flattenSCC scc0
789           scc_names       = map ms_mod scc
790           home_module m   = m `elem` all_home_mods && m `notElem` scc_names
791           scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
792                 -- NB. ms_imps, not ms_allimps above.  We don't want to
793                 -- force a module's SOURCE imports to be already compiled for
794                 -- its object linkable to be valid.
795
796                 -- The new_linkables is only the *valid* linkables below here
797           has_object m = case findModuleLinkable_maybe (map fst new_linkables) m of
798                             Nothing -> False
799                             Just l  -> isObjectLinkable l
800
801           objects_allowed = mode == Batch || all has_object scc_allhomeimps
802      in do
803
804      new_linkables'
805         <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
806
807         -- since an scc can contain only all objects or no objects at all,
808         -- we have to check whether we got all objects or not, and re-do
809         -- the linkable check if not.
810      new_linkables' <- 
811         if objects_allowed
812              && not (all isObjectLinkable (map fst new_linkables'))
813           then foldM (getValidLinkable old_linkables False) [] scc
814           else return new_linkables'
815
816      return (new_linkables ++ new_linkables')
817
818
819 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary 
820         -> IO [(Linkable,Bool)]
821         -- True <=> linkable is new; i.e. freshly discovered on the disk
822         --                                presumably generated 'on the side'
823         --                                by a separate GHC run
824 getValidLinkable old_linkables objects_allowed new_linkables summary 
825         -- 'objects_allowed' says whether we permit this module to
826         -- have a .o-file linkable.  We only permit it if all the
827         -- modules it depends on also have .o files; a .o file can't
828         -- link to a bytecode module
829    = do let mod_name = ms_mod summary
830
831         maybe_disk_linkable
832           <- if (not objects_allowed)
833                 then return Nothing
834
835                 else findLinkable mod_name (ms_location summary)
836
837         let old_linkable = findModuleLinkable_maybe old_linkables mod_name
838
839             new_linkables' = 
840              case (old_linkable, maybe_disk_linkable) of
841                 (Nothing, Nothing)                      -> []
842
843                 -- new object linkable just appeared
844                 (Nothing, Just l)                       -> up_to_date l True
845
846                 (Just l,  Nothing)
847                   | isObjectLinkable l                  -> []
848                     -- object linkable disappeared!  In case we need to
849                     -- relink the module, disregard the old linkable and
850                     -- just interpret the module from now on.
851                   | otherwise                           -> up_to_date l False
852                     -- old byte code linkable
853
854                 (Just l, Just l') 
855                   | not (isObjectLinkable l)            -> up_to_date l  False
856                     -- if the previous linkable was interpreted, then we
857                     -- ignore a newly compiled version, because the version
858                     -- numbers in the interface file will be out-of-sync with
859                     -- our internal ones.
860                   | linkableTime l' >  linkableTime l   -> up_to_date l' True
861                   | linkableTime l' == linkableTime l   -> up_to_date l  False
862                   | otherwise                           -> []
863                     -- on-disk linkable has been replaced by an older one!
864                     -- again, disregard the previous one.
865
866             up_to_date l b
867                 | linkableTime l < ms_hs_date summary = []
868                 | otherwise = [(l,b)]
869                 -- why '<' rather than '<=' above?  If the filesystem stores
870                 -- times to the nearset second, we may occasionally find that
871                 -- the object & source have the same modification time, 
872                 -- especially if the source was automatically generated
873                 -- and compiled.  Using >= is slightly unsafe, but it matches
874                 -- make's behaviour.
875
876         return (new_linkables' ++ new_linkables)
877
878
879 hptLinkables :: HomePackageTable -> [Linkable]
880 -- Get all the linkables from the home package table, one for each module
881 -- Once the HPT is up to date, these are the ones we should link
882 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
883
884
885 -----------------------------------------------------------------------------
886 -- Do a pre-upsweep without use of "compile", to establish a 
887 -- (downward-closed) set of stable modules for which we won't call compile.
888
889 -- a stable module:
890 --      * has a valid linkable (see getValidLinkables above)
891 --      * depends only on stable modules
892 --      * has an interface in the HPT (interactive mode only)
893
894 preUpsweep :: [Linkable]        -- new valid linkables
895            -> [Module]          -- names of all mods encountered in downsweep
896            -> [ModSummary]      -- accumulating stable modules
897            -> [SCC ModSummary]  -- scc-ified mod graph, including src imps
898            -> IO [ModSummary]   -- stable modules
899
900 preUpsweep valid_lis all_home_mods stable []  = return stable
901 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
902    = do let scc = flattenSCC scc0
903             scc_allhomeimps :: [Module]
904             scc_allhomeimps 
905                = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
906             all_imports_in_scc_or_stable
907                = all in_stable_or_scc scc_allhomeimps
908             scc_mods     = map ms_mod scc
909             stable_names = scc_mods ++ map ms_mod stable
910             in_stable_or_scc m = m `elem` stable_names
911
912             -- now we check for valid linkables: each module in the SCC must 
913             -- have a valid linkable (see getValidLinkables above).
914             has_valid_linkable scc_mod
915               = isJust (findModuleLinkable_maybe valid_lis scc_mod)
916
917             scc_is_stable = all_imports_in_scc_or_stable
918                           && all has_valid_linkable scc_mods
919
920         if scc_is_stable
921          then preUpsweep valid_lis all_home_mods (scc ++ stable) sccs
922          else preUpsweep valid_lis all_home_mods stable          sccs
923
924
925 -- Return (names of) all those in modsDone who are part of a cycle
926 -- as defined by theGraph.
927 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
928 findPartiallyCompletedCycles modsDone theGraph
929    = chew theGraph
930      where
931         chew [] = []
932         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
933         chew ((CyclicSCC vs):rest)
934            = let names_in_this_cycle = nub (map ms_mod vs)
935                  mods_in_this_cycle  
936                     = nub ([done | done <- modsDone, 
937                                    done `elem` names_in_this_cycle])
938                  chewed_rest = chew rest
939              in 
940              if   notNull mods_in_this_cycle
941                   && length mods_in_this_cycle < length names_in_this_cycle
942              then mods_in_this_cycle ++ chewed_rest
943              else chewed_rest
944
945
946 -- Compile multiple modules, stopping as soon as an error appears.
947 -- There better had not be any cyclic groups here -- we check for them.
948 upsweep_mods :: HscEnv                          -- Includes initially-empty HPT
949              -> (HomePackageTable, [Linkable])  -- HPT and valid linkables from last time round
950              -> IO ()                           -- How to clean up unwanted tmp files
951              -> [SCC ModSummary]                -- Mods to do (the worklist)
952              -> IO (SuccessFlag,
953                     HscEnv,             -- With an updated HPT
954                     [ModSummary])       -- Mods which succeeded
955
956 upsweep_mods hsc_env oldUI cleanup
957      []
958    = return (Succeeded, hsc_env, [])
959
960 upsweep_mods hsc_env oldUI cleanup
961      (CyclicSCC ms:_)
962    = do hPutStrLn stderr (showSDoc (cyclicModuleErr ms))
963         return (Failed, hsc_env, [])
964
965 upsweep_mods hsc_env oldUI@(old_hpt, old_linkables) cleanup
966      (AcyclicSCC mod:mods)
967    = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
968         --           show (map (moduleUserString.moduleName.mi_module.hm_iface) 
969         --                     (moduleEnvElts (hsc_HPT hsc_env)))
970
971         mb_mod_info <- upsweep_mod hsc_env oldUI mod 
972
973         cleanup         -- Remove unwanted tmp files between compilations
974
975         case mb_mod_info of
976             Nothing -> return (Failed, hsc_env, [])
977             Just mod_info -> do 
978                 { let this_mod = ms_mod mod
979
980                         -- Add new info to hsc_env
981                       hpt1     = extendModuleEnv (hsc_HPT hsc_env) this_mod mod_info
982                       hsc_env1 = hsc_env { hsc_HPT = hpt1 }
983
984                         -- Space-saving: delete the old HPT entry and linkable for mod
985                         -- BUT if mod is a hs-boot node, don't delete it
986                         -- For the linkable this is dead right: the linkable relates only
987                         -- to the main Haskell source file. 
988                         -- For the interface, the HPT entry is probaby for the main Haskell
989                         -- source file.  Deleting it would force 
990                       oldUI1 | isHsBoot (ms_hsc_src mod) = oldUI
991                              | otherwise
992                              = (delModuleEnv old_hpt this_mod, 
993                                   delModuleLinkable old_linkables this_mod)
994
995                 ; (restOK, hsc_env2, modOKs) <- upsweep_mods hsc_env1 oldUI1 cleanup mods
996                 ; return (restOK, hsc_env2, mod:modOKs) }
997
998
999 -- Compile a single module.  Always produce a Linkable for it if 
1000 -- successful.  If no compilation happened, return the old Linkable.
1001 upsweep_mod :: HscEnv
1002             -> (HomePackageTable, UnlinkedImage)
1003             -> ModSummary
1004             -> IO (Maybe HomeModInfo)   -- Nothing => Failed
1005
1006 upsweep_mod hsc_env (old_hpt, old_linkables) summary
1007    = do 
1008         let this_mod = ms_mod summary
1009
1010         -- The old interface is ok if it's in the old HPT 
1011         --      a) we're compiling a source file, and the old HPT entry is for a source file
1012         --      b) we're compiling a hs-boot file
1013         -- Case (b) allows an hs-boot file to get the interface of its real source file
1014         -- on the second iteration of the compilation manager, but that does no harm.
1015         -- Otherwise the hs-boot file will always be recompiled
1016             mb_old_iface 
1017                 = case lookupModuleEnv old_hpt this_mod of
1018                      Nothing                                      -> Nothing
1019                      Just hm_info | isHsBoot (ms_hsc_src summary) -> Just iface
1020                                   | not (mi_boot iface)           -> Just iface
1021                                   | otherwise                     -> Nothing
1022                                    where 
1023                                      iface = hm_iface hm_info
1024
1025             maybe_old_linkable = findModuleLinkable_maybe old_linkables this_mod
1026             source_unchanged   = isJust maybe_old_linkable
1027
1028             old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1029
1030             have_object 
1031                | Just l <- maybe_old_linkable, isObjectLinkable l = True
1032                | otherwise = False
1033
1034         compresult <- compile hsc_env summary source_unchanged have_object mb_old_iface
1035
1036         case compresult of
1037
1038            -- Compilation "succeeded", and may or may not have returned a new
1039            -- linkable (depending on whether compilation was actually performed
1040            -- or not).
1041            CompOK new_details new_globals new_iface maybe_new_linkable
1042               -> do let 
1043                         new_linkable = maybe_new_linkable `orElse` old_linkable
1044                         new_info = HomeModInfo { hm_iface = new_iface,
1045                                                  hm_globals = new_globals,
1046                                                  hm_details = new_details,
1047                                                  hm_linkable = new_linkable }
1048                     return (Just new_info)
1049
1050            -- Compilation failed.  Compile may still have updated the PCS, tho.
1051            CompErrs -> return Nothing
1052
1053 -- Filter modules in the HPT
1054 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1055 retainInTopLevelEnvs keep_these hpt
1056    = mkModuleEnv [ (mod, fromJust mb_mod_info)
1057                  | mod <- keep_these
1058                  , let mb_mod_info = lookupModuleEnv hpt mod
1059                  , isJust mb_mod_info ]
1060
1061 -----------------------------------------------------------------------------
1062 cmTopSort :: Bool               -- Drop hi-boot nodes? (see below)
1063           -> [ModSummary]
1064           -> [SCC ModSummary]
1065 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1066 --
1067 -- Drop hi-boot nodes (first boolean arg)? 
1068 --
1069 --   False:     treat the hi-boot summaries as nodes of the graph,
1070 --              so the graph must be acyclic
1071 --
1072 --   True:      eliminate the hi-boot nodes, and instead pretend
1073 --              the a source-import of Foo is an import of Foo
1074 --              The resulting graph has no hi-boot nodes, but can by cyclic
1075
1076 cmTopSort drop_hs_boot_nodes summaries
1077    = stronglyConnComp nodes
1078    where
1079         -- Drop hs-boot nodes by using HsSrcFile as the key
1080         hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1081                     | otherwise          = HsBootFile   
1082
1083         -- We use integers as the keys for the SCC algorithm
1084         nodes :: [(ModSummary, Int, [Int])]     
1085         nodes = [(s, fromJust (lookup_key (ms_hsc_src s) (ms_mod s)), 
1086                      out_edge_keys hs_boot_key (ms_srcimps s) ++
1087                      out_edge_keys HsSrcFile   (ms_imps s)    )
1088                 | s <- summaries
1089                 , not (ms_hsc_src s == HsBootFile && drop_hs_boot_nodes) ]
1090                 -- Drop the hi-boot ones if told to do so
1091
1092         key_map :: NodeMap Int
1093         key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1094                            `zip` [1..])
1095
1096         lookup_key :: HscSource -> Module -> Maybe Int
1097         lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1098
1099         out_edge_keys :: HscSource -> [Module] -> [Int]
1100         out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1101                 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1102                 -- the IsBootInterface parameter True; else False
1103
1104
1105 -----------------------------------------------------------------------------
1106 -- Downsweep (dependency analysis)
1107
1108 -- Chase downwards from the specified root set, returning summaries
1109 -- for all home modules encountered.  Only follow source-import
1110 -- links.
1111
1112 -- We pass in the previous collection of summaries, which is used as a
1113 -- cache to avoid recalculating a module summary if the source is
1114 -- unchanged.
1115 --
1116 -- The returned list of [ModSummary] nodes has one node for each home-package
1117 -- module.  The imports of these nodes are all there, including the imports
1118 -- of non-home-package modules.
1119
1120 cmDownsweep :: DynFlags
1121             -> [FilePath]       -- Roots
1122             -> [ModSummary]     -- Old summaries
1123             -> [Module]         -- Ignore dependencies on these; treat them as
1124                                 -- if they were package modules
1125             -> IO [ModSummary]
1126 cmDownsweep dflags roots old_summaries excl_mods
1127    = do rootSummaries <- mapM getRootSummary roots
1128         checkDuplicates rootSummaries
1129         loop (concatMap msImports rootSummaries) 
1130              (mkNodeMap rootSummaries)
1131      where
1132         old_summary_map :: NodeMap ModSummary
1133         old_summary_map = mkNodeMap old_summaries
1134
1135         getRootSummary :: FilePath -> IO ModSummary
1136         getRootSummary file
1137            | isHaskellSrcFilename file
1138            = do exists <- doesFileExist file
1139                 if exists then summariseFile dflags file else do
1140                 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))    
1141            | otherwise
1142            = do exists <- doesFileExist hs_file
1143                 if exists then summariseFile dflags hs_file else do
1144                 exists <- doesFileExist lhs_file
1145                 if exists then summariseFile dflags lhs_file else do
1146                 let mod_name = mkModule file
1147                 maybe_summary <- summarise dflags emptyNodeMap Nothing False 
1148                                            mod_name excl_mods
1149                 case maybe_summary of
1150                    Nothing -> packageModErr mod_name
1151                    Just s  -> return s
1152            where 
1153                  hs_file = file ++ ".hs"
1154                  lhs_file = file ++ ".lhs"
1155
1156         -- In a root module, the filename is allowed to diverge from the module
1157         -- name, so we have to check that there aren't multiple root files
1158         -- defining the same module (otherwise the duplicates will be silently
1159         -- ignored, leading to confusing behaviour).
1160         checkDuplicates :: [ModSummary] -> IO ()
1161         checkDuplicates summaries = mapM_ check summaries
1162           where check summ = 
1163                   case dups of
1164                         []     -> return ()
1165                         [_one] -> return ()
1166                         many   -> multiRootsErr modl many
1167                    where modl = ms_mod summ
1168                          dups = 
1169                            [ fromJust (ml_hs_file (ms_location summ'))
1170                            | summ' <- summaries, ms_mod summ' == modl ]
1171
1172         loop :: [(FilePath,Module,IsBootInterface)]     -- Work list: process these modules
1173              -> NodeMap ModSummary      -- Visited set
1174              -> IO [ModSummary]         -- The result includes the worklist, except 
1175                                         -- for those mentioned in the visited set
1176         loop [] done      = return (nodeMapElts done)
1177         loop ((cur_path, wanted_mod, is_boot) : ss) done 
1178           | key `elemFM` done = loop ss done
1179           | otherwise         = do { mb_s <- summarise dflags old_summary_map 
1180                                                  (Just cur_path) is_boot 
1181                                                  wanted_mod excl_mods
1182                                    ; case mb_s of
1183                                         Nothing -> loop ss done
1184                                         Just s  -> loop (msImports s ++ ss) 
1185                                                         (addToFM done key s) }
1186           where
1187             key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1188
1189 msImports :: ModSummary -> [(FilePath,          -- Importing module
1190                              Module,            -- Imported module
1191                              IsBootInterface)]   -- {-# SOURCE #-} import or not
1192 msImports s =  [(f, m,True)  | m <- ms_srcimps s] 
1193             ++ [(f, m,False) | m <- ms_imps    s] 
1194         where
1195           f = msHsFilePath s    -- Keep the importing module for error reporting
1196
1197
1198 -----------------------------------------------------------------------------
1199 -- Summarising modules
1200
1201 -- We have two types of summarisation:
1202 --
1203 --    * Summarise a file.  This is used for the root module(s) passed to
1204 --      cmLoadModules.  The file is read, and used to determine the root
1205 --      module name.  The module name may differ from the filename.
1206 --
1207 --    * Summarise a module.  We are given a module name, and must provide
1208 --      a summary.  The finder is used to locate the file in which the module
1209 --      resides.
1210
1211 summariseFile :: DynFlags -> FilePath -> IO ModSummary
1212 -- Used for Haskell source only, I think
1213 -- We know the file name, and we know it exists,
1214 -- but we don't necessarily know the module name (might differ)
1215 summariseFile dflags file
1216    = do (dflags', hspp_fn) <- preprocess dflags file
1217                 -- The dflags' contains the OPTIONS pragmas
1218
1219         -- Read the file into a buffer.  We're going to cache
1220         -- this buffer in the ModLocation (ml_hspp_buf) so that it
1221         -- doesn't have to be slurped again when hscMain parses the
1222         -- file later.
1223         buf <- hGetStringBuffer hspp_fn
1224         (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1225
1226         -- Make a ModLocation for this file
1227         location <- mkHomeModLocation mod file
1228
1229         -- Tell the Finder cache where it is, so that subsequent calls
1230         -- to findModule will find it, even if it's not on any search path
1231         addHomeModuleToFinder mod location
1232
1233         src_timestamp <- getModificationTime file
1234         return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1235                              ms_location = location,
1236                              ms_hspp_file = Just hspp_fn,
1237                              ms_hspp_buf  = Just buf,
1238                              ms_srcimps = srcimps, ms_imps = the_imps,
1239                              ms_hs_date = src_timestamp })
1240
1241 -- Summarise a module, and pick up source and timestamp.
1242 summarise :: DynFlags 
1243           -> NodeMap ModSummary -- Map of old summaries
1244           -> Maybe FilePath     -- Importing module (for error messages)
1245           -> IsBootInterface    -- True <=> a {-# SOURCE #-} import
1246           -> Module             -- Imported module to be summarised
1247           -> [Module]           -- Modules to exclude
1248           -> IO (Maybe ModSummary)      -- Its new summary
1249
1250 summarise dflags old_summary_map cur_mod is_boot wanted_mod excl_mods
1251   | wanted_mod `elem` excl_mods
1252   = return Nothing
1253
1254   | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1255   = do  {       -- Find its new timestamp; all the 
1256                 -- ModSummaries in the old map have valid ml_hs_files
1257            let location = ms_location old_summary
1258                src_fn = fromJust (ml_hs_file location)
1259
1260         ;  src_timestamp <- getModificationTime src_fn
1261
1262                 -- return the cached summary if the source didn't change
1263         ; if ms_hs_date old_summary == src_timestamp 
1264           then return (Just old_summary)
1265           else new_summary location
1266         }
1267
1268   | otherwise
1269   = do  { found <- findModule dflags wanted_mod True {-explicit-}
1270         ; case found of
1271              Found location pkg 
1272                 | not (isHomePackage pkg)      -> return Nothing        -- Drop external-pkg
1273                 | isJust (ml_hs_file location) -> new_summary location  -- Home package
1274              err        -> noModError dflags cur_mod wanted_mod err     -- Not found
1275         }
1276   where
1277     hsc_src = if is_boot then HsBootFile else HsSrcFile
1278
1279     new_summary location
1280       = do {    -- Adjust location to point to the hs-boot source file, 
1281                 -- hi file, object file, when is_boot says so
1282           let location' | is_boot   = addBootSuffixLocn location
1283                         | otherwise = location
1284               src_fn = fromJust (ml_hs_file location')
1285
1286                 -- Check that it exists
1287                 -- It might have been deleted since the Finder last found it
1288         ; exists <- doesFileExist src_fn
1289         ; if exists then return () else noHsFileErr cur_mod src_fn
1290
1291         -- Preprocess the source file and get its imports
1292         -- The dflags' contains the OPTIONS pragmas
1293         ; (dflags', hspp_fn) <- preprocess dflags src_fn
1294         ; buf <- hGetStringBuffer hspp_fn
1295         ; (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1296
1297         ; when (mod_name /= wanted_mod) $
1298                 throwDyn (ProgramError 
1299                    (showSDoc (text src_fn
1300                               <>  text ": file name does not match module name"
1301                               <+> quotes (ppr mod_name))))
1302
1303                 -- Find its timestamp, and return the summary
1304         ; src_timestamp <- getModificationTime src_fn
1305         ; return (Just ( ModSummary { ms_mod       = wanted_mod, 
1306                                       ms_hsc_src   = hsc_src,
1307                                       ms_location  = location',
1308                                       ms_hspp_file = Just hspp_fn,
1309                                       ms_hspp_buf  = Just buf,
1310                                       ms_srcimps   = srcimps,
1311                                       ms_imps      = the_imps,
1312                                       ms_hs_date   = src_timestamp }))
1313         }
1314
1315
1316 -----------------------------------------------------------------------------
1317 --                      Error messages
1318 -----------------------------------------------------------------------------
1319
1320 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1321 -- ToDo: we don't have a proper line number for this error
1322 noModError dflags cur_mod wanted_mod err
1323   = throwDyn $ ProgramError $ showSDoc $
1324     vcat [cantFindError dflags wanted_mod err,
1325           nest 2 (parens (pp_where cur_mod))]
1326                                 
1327 noHsFileErr cur_mod path
1328   = throwDyn $ CmdLineError $ showSDoc $
1329     vcat [text "Can't find" <+> text path,
1330           nest 2 (parens (pp_where cur_mod))]
1331  
1332 pp_where Nothing  = text "one of the roots of the dependency analysis"
1333 pp_where (Just p) = text "imported from" <+> text p
1334
1335 packageModErr mod
1336   = throwDyn (CmdLineError (showSDoc (text "module" <+>
1337                                    quotes (ppr mod) <+>
1338                                    text "is a package module")))
1339
1340 multiRootsErr mod files
1341   = throwDyn (ProgramError (showSDoc (
1342         text "module" <+> quotes (ppr mod) <+> 
1343         text "is defined in multiple files:" <+>
1344         sep (map text files))))
1345
1346 cyclicModuleErr :: [ModSummary] -> SDoc
1347 cyclicModuleErr ms
1348   = hang (ptext SLIT("Module imports form a cycle for modules:"))
1349        2 (vcat (map show_one ms))
1350   where
1351     show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1352                         nest 2 $ ptext SLIT("imports:") <+> 
1353                                    (pp_imps HsBootFile (ms_srcimps ms)
1354                                    $$ pp_imps HsSrcFile  (ms_imps ms))]
1355     show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1356     pp_imps src mods = fsep (map (show_mod src) mods)
1357 \end{code}
1358