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