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