[project @ 2002-08-29 15:44:11 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 {-# OPTIONS -fvia-C #-}
8 module CompManager ( 
9     ModuleGraph, 
10
11     CmState, emptyCmState,  -- abstract
12
13     cmInit,        -- :: GhciMode -> IO CmState
14
15     cmDepAnal,     -- :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
16
17     cmLoadModules, -- :: CmState -> DynFlags -> ModuleGraph
18                    --    -> IO (CmState, Bool, [String])
19
20     cmUnload,      -- :: CmState -> DynFlags -> IO CmState
21
22 #ifdef GHCI
23     cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
24
25     cmSetContext,  -- :: CmState -> DynFlags -> [String] -> [String] -> IO CmState
26     cmGetContext,  -- :: CmState -> IO ([String],[String])
27
28     cmInfoThing,   -- :: CmState -> DynFlags -> String
29                    --   -> IO (CmState, [(TyThing,Fixity)])
30
31     cmBrowseModule, -- :: CmState -> IO [TyThing]
32
33     CmRunResult(..),
34     cmRunStmt,     -- :: CmState -> DynFlags -> String
35                    --    -> IO (CmState, CmRunResult)
36
37     cmTypeOfExpr,  -- :: CmState -> DynFlags -> String
38                    --   -> IO (CmState, Maybe String)
39
40     cmTypeOfName,  -- :: CmState -> Name -> IO (Maybe String)
41
42     HValue,
43     cmCompileExpr, -- :: CmState -> DynFlags -> String 
44                    --   -> IO (CmState, Maybe HValue)
45
46     cmGetModuleGraph,           -- :: CmState -> ModuleGraph
47     cmGetLinkables,             -- :: CmState -> [Linkable]
48
49     cmGetBindings,      -- :: CmState -> [TyThing]
50     cmGetPrintUnqual,   -- :: CmState -> PrintUnqualified
51 #endif
52
53     -- utils
54     showModMsg,         -- 
55   )
56 where
57
58 #include "HsVersions.h"
59
60 import CmLink
61 import CmTypes
62 import DriverPipeline
63 import DriverState      ( v_Output_file )
64 import DriverPhases
65 import DriverUtil
66 import Finder
67 #ifdef GHCI
68 import HscMain          ( initPersistentCompilerState, hscThing, 
69                           hscModuleContents )
70 #else
71 import HscMain          ( initPersistentCompilerState )
72 #endif
73 import HscTypes hiding ( moduleNameToModule )
74 import Name             ( Name, NamedThing(..), nameRdrName, nameModule,
75                           isHomePackageName, isExternalName )
76 import NameEnv
77 import PrelNames        ( gHC_PRIM_Name )
78 import Rename           ( mkGlobalContext )
79 import RdrName          ( emptyRdrEnv )
80 import Module
81 import GetImports
82 import UniqFM
83 import Unique           ( Uniquable )
84 import Digraph          ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
85 import ErrUtils         ( showPass )
86 import SysTools         ( cleanTempFilesExcept )
87 import Util
88 import Outputable
89 import Panic
90 import CmdLineOpts      ( DynFlags(..), getDynFlags )
91 import Maybes           ( expectJust )
92
93 import IOExts
94
95 #ifdef GHCI
96 import RdrName          ( lookupRdrEnv )
97 import Id               ( idType, idName )
98 import Type             ( tidyType )
99 import VarEnv           ( emptyTidyEnv )
100 import BasicTypes       ( Fixity, defaultFixity )
101 import Interpreter      ( HValue )
102 import HscMain          ( hscStmt )
103 import GlaExts          ( unsafeCoerce# )
104 import Foreign
105 import CForeign
106 import Exception        ( Exception, try )
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 \begin{code}
121 -- Persistent state for the entire system
122 data CmState
123    = CmState {
124         hst   :: HomeSymbolTable,    -- home symbol table
125         hit   :: HomeIfaceTable,     -- home interface table
126         ui    :: UnlinkedImage,      -- the unlinked images
127         mg    :: ModuleGraph,        -- the module graph
128         gmode :: GhciMode,           -- NEVER CHANGES
129         ic    :: InteractiveContext, -- command-line binding info
130
131         pcs    :: PersistentCompilerState, -- compile's persistent state
132         pls    :: PersistentLinkerState    -- link's persistent state
133      }
134
135 emptyCmState :: GhciMode -> IO CmState
136 emptyCmState gmode
137     = do pcs     <- initPersistentCompilerState
138          pls     <- emptyPLS
139          return (CmState { hst    = emptySymbolTable,
140                            hit    = emptyIfaceTable,
141                            ui     = emptyUI,
142                            mg     = emptyMG, 
143                            gmode  = gmode,
144                            ic     = emptyInteractiveContext,
145                            pcs    = pcs,
146                            pls    = pls })
147
148 emptyInteractiveContext
149   = InteractiveContext { ic_toplev_scope = [],
150                          ic_exports = [],
151                          ic_rn_gbl_env = emptyRdrEnv,
152                          ic_print_unqual = alwaysQualify,
153                          ic_rn_local_env = emptyRdrEnv,
154                          ic_type_env = emptyTypeEnv }
155
156 -- CM internal types
157 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
158 emptyUI :: UnlinkedImage
159 emptyUI = []
160
161 type ModuleGraph = [ModSummary]  -- the module graph, topologically sorted
162 emptyMG :: ModuleGraph
163 emptyMG = []
164
165 -----------------------------------------------------------------------------
166 -- Produce an initial CmState.
167
168 cmInit :: GhciMode -> IO CmState
169 cmInit mode = emptyCmState mode
170
171 -----------------------------------------------------------------------------
172 -- Grab information from the CmState
173
174 cmGetModuleGraph        = mg
175 cmGetLinkables          = ui
176
177 cmGetBindings cmstate = nameEnvElts (ic_type_env (ic cmstate))
178 cmGetPrintUnqual cmstate = ic_print_unqual (ic cmstate)
179
180 -----------------------------------------------------------------------------
181 -- Setting the context doesn't throw away any bindings; the bindings
182 -- we've built up in the InteractiveContext simply move to the new
183 -- module.  They always shadow anything in scope in the current context.
184
185 cmSetContext
186         :: CmState -> DynFlags
187         -> [String]             -- take the top-level scopes of these modules
188         -> [String]             -- and the just the exports from these
189         -> IO CmState
190 cmSetContext cmstate dflags toplevs exports = do 
191   let CmState{ hit=hit, hst=hst, pcs=pcs, ic=old_ic } = cmstate
192
193   toplev_mods <- mapM (getTopLevModule hit)    (map mkModuleName toplevs)
194   export_mods <- mapM (moduleNameToModule hit) (map mkModuleName exports)
195
196   (new_pcs, print_unqual, maybe_env)
197       <- mkGlobalContext dflags hit hst pcs toplev_mods export_mods
198
199   case maybe_env of 
200     Nothing -> return cmstate
201     Just env -> return cmstate{ pcs = new_pcs,
202                                 ic = old_ic{ ic_toplev_scope = toplev_mods,
203                                              ic_exports = export_mods,
204                                              ic_rn_gbl_env = env,
205                                              ic_print_unqual = print_unqual } }
206
207 getTopLevModule hit mn =
208   case lookupModuleEnvByName hit mn of
209     Just iface
210       | Just _ <- mi_globals iface -> return (mi_module iface)
211     _other -> throwDyn (CmdLineError (
212           "cannot enter the top-level scope of a compiled module (module `" ++
213            moduleNameUserString mn ++ "')"))
214
215 moduleNameToModule :: HomeIfaceTable -> ModuleName -> IO Module
216 moduleNameToModule hit mn = do
217   case lookupModuleEnvByName hit mn of
218     Just iface -> return (mi_module iface)
219     _not_a_home_module -> do
220           maybe_stuff <- findModule mn
221           case maybe_stuff of
222             Nothing -> throwDyn (CmdLineError ("can't find module `"
223                                     ++ moduleNameUserString mn ++ "'"))
224             Just (m,_) -> return m
225
226 cmGetContext :: CmState -> IO ([String],[String])
227 cmGetContext CmState{ic=ic} = 
228   return (map moduleUserString (ic_toplev_scope ic), 
229           map moduleUserString (ic_exports ic))
230
231 cmModuleIsInterpreted :: CmState -> String -> IO Bool
232 cmModuleIsInterpreted cmstate str 
233  = case lookupModuleEnvByName (hit cmstate) (mkModuleName str) of
234       Just iface         -> return (not (isNothing (mi_globals iface)))
235       _not_a_home_module -> return False
236
237 -----------------------------------------------------------------------------
238 -- cmInfoThing: convert a String to a TyThing
239
240 -- A string may refer to more than one TyThing (eg. a constructor,
241 -- and type constructor), so we return a list of all the possible TyThings.
242
243 #ifdef GHCI
244 cmInfoThing :: CmState -> DynFlags -> String -> IO (CmState, [(TyThing,Fixity)])
245 cmInfoThing cmstate dflags id
246    = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
247         let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
248         return (cmstate{ pcs=new_pcs }, pairs)
249    where
250      CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
251
252      getFixity :: PersistentCompilerState -> Name -> Fixity
253      getFixity pcs name
254         | isExternalName name,
255           Just iface  <- lookupModuleEnv iface_table (nameModule name),
256           Just fixity <- lookupNameEnv (mi_fixities iface) name
257           = fixity
258         | otherwise
259           = defaultFixity
260         where iface_table | isHomePackageName name = hit
261                           | otherwise              = pcs_PIT pcs
262 #endif
263
264 -- ---------------------------------------------------------------------------
265 -- cmBrowseModule: get all the TyThings defined in a module
266
267 #ifdef GHCI
268 cmBrowseModule :: CmState -> DynFlags -> String -> Bool 
269         -> IO (CmState, [TyThing])
270 cmBrowseModule cmstate dflags str exports_only = do
271   let mn = mkModuleName str
272   mod <- moduleNameToModule hit mn
273   (pcs1, maybe_ty_things) 
274         <- hscModuleContents dflags hst hit pcs mod exports_only
275   case maybe_ty_things of
276         Nothing -> return (cmstate{pcs=pcs1}, [])
277         Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
278   where
279      CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
280 #endif
281
282 -----------------------------------------------------------------------------
283 -- cmRunStmt:  Run a statement/expr.
284
285 #ifdef GHCI
286 data CmRunResult
287   = CmRunOk [Name]              -- names bound by this evaluation
288   | CmRunFailed 
289   | CmRunException Exception    -- statement raised an exception
290
291 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)         
292 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
293           dflags expr
294    = do 
295         let InteractiveContext { 
296                 ic_rn_local_env = rn_env, 
297                 ic_type_env     = type_env } = icontext
298
299         (new_pcs, maybe_stuff) 
300             <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
301
302         case maybe_stuff of
303            Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
304            Just (ids, _, bcos) -> do
305
306                 -- update the interactive context
307                 let 
308                     names = map idName ids
309
310                     -- these names have just been shadowed
311                     shadowed = [ n | r <- map nameRdrName names,
312                                      Just n <- [lookupRdrEnv rn_env r] ]
313                     
314                     new_rn_env   = extendLocalRdrEnv rn_env names
315
316                     -- remove any shadowed bindings from the type_env
317                     filtered_type_env = delListFromNameEnv type_env shadowed
318
319                     new_type_env = extendNameEnvList filtered_type_env  
320                                         [ (getName id, AnId id) | id <- ids]
321
322                     new_ic = icontext { ic_rn_local_env = new_rn_env, 
323                                         ic_type_env     = new_type_env }
324
325                 -- link it
326                 hval <- linkExpr pls bcos
327
328                 -- run it!
329                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
330                 either_hvals <- sandboxIO thing_to_run
331                 case either_hvals of
332                    Left err
333                         -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
334                               return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
335
336                    Right maybe_hvals ->
337                      case maybe_hvals of
338                         Left e -> 
339                             return ( cmstate{ pcs=new_pcs, ic=new_ic }, 
340                                      CmRunException e )
341                         Right hvals -> do
342                              -- Get the newly bound things, and bind them.  
343                              -- Don't forget to delete any shadowed bindings from the
344                              -- closure_env, lest we end up with a space leak.
345                              pls <- delListFromClosureEnv pls shadowed
346                              new_pls <- addListToClosureEnv pls (zip names hvals)
347              
348                              return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, 
349                                      CmRunOk names)
350
351
352 -- We run the statement in a "sandbox" to protect the rest of the
353 -- system from anything the expression might do.  For now, this
354 -- consists of just wrapping it in an exception handler, but see below
355 -- for another version.
356
357 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
358 sandboxIO thing = do
359   r <- Exception.try thing
360   return (Right r)
361
362 {-
363 -- This version of sandboxIO runs the expression in a completely new
364 -- RTS main thread.  It is disabled for now because ^C exceptions
365 -- won't be delivered to the new thread, instead they'll be delivered
366 -- to the (blocked) GHCi main thread.
367
368 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
369 sandboxIO thing = do
370   st_thing <- newStablePtr (Exception.try thing)
371   alloca $ \ p_st_result -> do
372     stat <- rts_evalStableIO st_thing p_st_result
373     freeStablePtr st_thing
374     if stat == 1
375         then do st_result <- peek p_st_result
376                 result <- deRefStablePtr st_result
377                 freeStablePtr st_result
378                 return (Right result)
379         else do
380                 return (Left (fromIntegral stat))
381
382 foreign import "rts_evalStableIO"  {- safe -}
383   rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
384   -- more informative than the C type!
385 -}
386 #endif
387
388 -----------------------------------------------------------------------------
389 -- cmTypeOfExpr: returns a string representing the type of an expression
390
391 #ifdef GHCI
392 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
393 cmTypeOfExpr cmstate dflags expr
394    = do (new_pcs, maybe_stuff) 
395           <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
396
397         let new_cmstate = cmstate{pcs = new_pcs}
398
399         case maybe_stuff of
400            Nothing -> return (new_cmstate, Nothing)
401            Just (_, ty, _) -> return (new_cmstate, Just str)
402              where 
403                 str = showSDocForUser unqual (ppr tidy_ty)
404                 unqual  = ic_print_unqual ic
405                 tidy_ty = tidyType emptyTidyEnv ty
406    where
407        CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
408 #endif
409
410 -----------------------------------------------------------------------------
411 -- cmTypeOfName: returns a string representing the type of a name.
412
413 #ifdef GHCI
414 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
415 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
416  = case lookupNameEnv (ic_type_env ic) name of
417         Nothing -> return Nothing
418         Just (AnId id) -> return (Just str)
419            where
420              unqual = ic_print_unqual ic
421              ty = tidyType emptyTidyEnv (idType id)
422              str = showSDocForUser unqual (ppr ty)
423
424         _ -> panic "cmTypeOfName"
425 #endif
426
427 -----------------------------------------------------------------------------
428 -- cmCompileExpr: compile an expression and deliver an HValue
429
430 #ifdef GHCI
431 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
432 cmCompileExpr cmstate dflags expr
433    = do 
434         let InteractiveContext { 
435                 ic_rn_local_env = rn_env, 
436                 ic_type_env     = type_env } = icontext
437
438         (new_pcs, maybe_stuff) 
439             <- hscStmt dflags hst hit pcs icontext 
440                   ("let __cmCompileExpr = "++expr) False{-stmt-}
441
442         case maybe_stuff of
443            Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
444            Just (ids, _, bcos) -> do
445
446                 -- link it
447                 hval <- linkExpr pls bcos
448
449                 -- run it!
450                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
451                 hvals <- thing_to_run
452
453                 case (ids,hvals) of
454                   ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
455                   _ -> panic "cmCompileExpr"
456
457    where
458        CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
459 #endif
460
461 -----------------------------------------------------------------------------
462 -- Unload the compilation manager's state: everything it knows about the
463 -- current collection of modules in the Home package.
464
465 cmUnload :: CmState -> DynFlags -> IO CmState
466 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
467  = do -- Throw away the old home dir cache
468       emptyHomeDirCache
469
470       -- Unload everything the linker knows about
471       new_pls <- CmLink.unload mode dflags [] pls 
472
473       -- Start with a fresh CmState, but keep the PersistentCompilerState
474       new_state <- cmInit mode
475       return new_state{ pcs=pcs, pls=new_pls }
476
477
478 -----------------------------------------------------------------------------
479 -- Trace dependency graph
480
481 -- This is a seperate pass so that the caller can back off and keep
482 -- the current state if the downsweep fails.
483
484 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
485 cmDepAnal cmstate dflags rootnames
486   = do showPass dflags "Chasing dependencies"
487        when (verbosity dflags >= 1 && gmode cmstate == Batch) $
488            hPutStrLn stderr (showSDoc (hcat [
489              text progName, text ": chasing modules from: ",
490              hcat (punctuate comma (map text rootnames))]))
491        downsweep rootnames (mg cmstate)
492
493 -----------------------------------------------------------------------------
494 -- The real business of the compilation manager: given a system state and
495 -- a module name, try and bring the module up to date, probably changing
496 -- the system state at the same time.
497
498 cmLoadModules :: CmState 
499              -> DynFlags
500              -> ModuleGraph
501              -> IO (CmState,            -- new state
502                     Bool,               -- was successful
503                     [String])           -- list of modules loaded
504
505 cmLoadModules cmstate1 dflags mg2unsorted
506    = do -- version 1's are the original, before downsweep
507         let pls1      = pls    cmstate1
508         let pcs1      = pcs    cmstate1
509         let hst1      = hst    cmstate1
510         let hit1      = hit    cmstate1
511         -- similarly, ui1 is the (complete) set of linkables from
512         -- the previous pass, if any.
513         let ui1       = ui     cmstate1
514
515         let ghci_mode = gmode cmstate1 -- this never changes
516
517         -- Do the downsweep to reestablish the module graph
518         let verb = verbosity dflags
519
520         -- Find out if we have a Main module
521         let a_root_is_Main 
522                = any ((=="Main").moduleNameUserString.modSummaryName) 
523                      mg2unsorted
524
525         let mg2unsorted_names = map modSummaryName mg2unsorted
526
527         -- reachable_from follows source as well as normal imports
528         let reachable_from :: ModuleName -> [ModuleName]
529             reachable_from = downwards_closure_of_module mg2unsorted
530  
531         -- should be cycle free; ignores 'import source's
532         let mg2 = topological_sort False mg2unsorted
533         -- ... whereas this takes them into account.  Used for
534         -- backing out partially complete cycles following a failed
535         -- upsweep, and for removing from hst/hit all the modules
536         -- not in strict downwards closure, during calls to compile.
537         let mg2_with_srcimps = topological_sort True mg2unsorted
538
539         -- Sort out which linkables we wish to keep in the unlinked image.
540         -- See getValidLinkables below for details.
541         (valid_old_linkables, new_linkables)
542             <- getValidLinkables ghci_mode ui1 
543                   mg2unsorted_names mg2_with_srcimps
544
545         -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
546
547                 -- uniq of ModuleName is the same as Module, fortunately...
548         let hit2 = delListFromUFM hit1 (map linkableModName new_linkables)
549
550         -- When (verb >= 2) $
551         --    putStrLn (showSDoc (text "Valid linkables:" 
552         --                       <+> ppr valid_linkables))
553
554         -- Figure out a stable set of modules which can be retained
555         -- the top level envs, to avoid upsweeping them.  Goes to a
556         -- bit of trouble to avoid upsweeping module cycles.
557         --
558         -- Construct a set S of stable modules like this:
559         -- Travel upwards, over the sccified graph.  For each scc
560         -- of modules ms, add ms to S only if:
561         -- 1.  All home imports of ms are either in ms or S
562         -- 2.  A valid old linkable exists for each module in ms
563
564         stable_mods <- preUpsweep valid_old_linkables
565                                   mg2unsorted_names [] mg2_with_srcimps
566
567         let stable_summaries
568                = concatMap (findInSummaries mg2unsorted) stable_mods
569
570             stable_linkables
571                = filter (\m -> linkableModName m `elem` stable_mods) 
572                     valid_old_linkables
573
574         when (verb >= 2) $
575            putStrLn (showSDoc (text "Stable modules:" 
576                                <+> sep (map (text.moduleNameUserString) stable_mods)))
577
578         -- unload any modules which are going to be re-linked this
579         -- time around.
580         pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
581
582         -- we can now glom together our linkable sets
583         let valid_linkables = valid_old_linkables ++ new_linkables
584
585         -- We could at this point detect cycles which aren't broken by
586         -- a source-import, and complain immediately, but it seems better
587         -- to let upsweep_mods do this, so at least some useful work gets
588         -- done before the upsweep is abandoned.
589         let upsweep_these
590                = filter (\scc -> any (`notElem` stable_mods) 
591                                      (map modSummaryName (flattenSCC scc)))
592                         mg2
593
594         --hPutStrLn stderr "after tsort:\n"
595         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
596
597         -- Because we don't take into account source imports when doing
598         -- the topological sort, there shouldn't be any cycles in mg2.
599         -- If there is, we complain and give up -- the user needs to
600         -- break the cycle using a boot file.
601
602         -- Now do the upsweep, calling compile for each module in
603         -- turn.  Final result is version 3 of everything.
604
605         let threaded2 = CmThreaded pcs1 hst1 hit2
606
607         -- clean up between compilations
608         let cleanup = cleanTempFilesExcept verb 
609                           (ppFilesFromSummaries (flattenSCCs mg2))
610
611         (upsweep_complete_success, threaded3, modsUpswept, newLis)
612            <- upsweep_mods ghci_mode dflags valid_linkables reachable_from 
613                            threaded2 cleanup upsweep_these
614
615         let ui3 = add_to_ui valid_linkables newLis
616         let (CmThreaded pcs3 hst3 hit3) = threaded3
617
618         -- At this point, modsUpswept and newLis should have the same
619         -- length, so there is one new (or old) linkable for each 
620         -- mod which was processed (passed to compile).
621
622         -- Make modsDone be the summaries for each home module now
623         -- available; this should equal the domains of hst3 and hit3.
624         -- (NOT STRICTLY TRUE if an interactive session was started
625         --  with some object on disk ???)
626         -- Get in in a roughly top .. bottom order (hence reverse).
627
628         let modsDone = reverse modsUpswept ++ stable_summaries
629
630         -- Try and do linking in some form, depending on whether the
631         -- upsweep was completely or only partially successful.
632
633         if upsweep_complete_success
634
635          then 
636            -- Easy; just relink it all.
637            do when (verb >= 2) $ 
638                  hPutStrLn stderr "Upsweep completely successful."
639
640               -- clean up after ourselves
641               cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
642
643               -- issue a warning for the confusing case where the user said '-o foo'
644               -- but we're not going to do any linking.
645               ofile <- readIORef v_Output_file
646               when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
647                      && verb > 0) $
648                  hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
649
650               -- link everything together
651               linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
652
653               cmLoadFinish True linkresult 
654                         hst3 hit3 ui3 modsDone ghci_mode pcs3
655
656          else 
657            -- Tricky.  We need to back out the effects of compiling any
658            -- half-done cycles, both so as to clean up the top level envs
659            -- and to avoid telling the interactive linker to link them.
660            do when (verb >= 2) $
661                 hPutStrLn stderr "Upsweep partially successful."
662
663               let modsDone_names
664                      = map modSummaryName modsDone
665               let mods_to_zap_names 
666                      = findPartiallyCompletedCycles modsDone_names 
667                           mg2_with_srcimps
668               let mods_to_keep
669                      = filter ((`notElem` mods_to_zap_names).modSummaryName) 
670                           modsDone
671
672               let (hst4, hit4, ui4)
673                      = retainInTopLevelEnvs (map modSummaryName mods_to_keep) 
674                                             (hst3,hit3,ui3)
675
676               -- clean up after ourselves
677               cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
678
679               -- link everything together
680               linkresult <- link ghci_mode dflags False ui4 pls2
681
682               cmLoadFinish False linkresult 
683                     hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
684
685
686 -- Finish up after a cmLoad.
687
688 -- If the link failed, unload everything and return.
689 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
690   dflags <- getDynFlags
691   new_pls <- CmLink.unload ghci_mode dflags [] pls 
692   new_state <- cmInit ghci_mode
693   return (new_state{ pcs=pcs, pls=new_pls }, False, [])
694
695 -- Empty the interactive context and set the module context to the topmost
696 -- newly loaded module, or the Prelude if none were loaded.
697 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
698   = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
699                                   gmode=ghci_mode, pcs=pcs, pls=pls,
700                                   ic = emptyInteractiveContext }
701            mods_loaded = map (moduleNameUserString.modSummaryName) mods
702
703        return (new_cmstate, ok, mods_loaded)
704
705 -- used to fish out the preprocess output files for the purposes
706 -- of cleaning up.
707 ppFilesFromSummaries summaries
708   = [ fn | Just fn <- map toPpFile summaries ]
709   where
710    toPpFile sum
711      | hspp /= ml_hs_file loc = hspp
712      | otherwise              = Nothing
713     where
714       loc  = ms_location sum
715       hspp = ml_hspp_file loc
716
717
718 -----------------------------------------------------------------------------
719 -- getValidLinkables
720
721 -- For each module (or SCC of modules), we take:
722 --
723 --      - an on-disk linkable, if this is the first time around and one
724 --        is available.
725 --
726 --      - the old linkable, otherwise (and if one is available).
727 --
728 -- and we throw away the linkable if it is older than the source file.
729 -- In interactive mode, we also ignore the on-disk linkables unless
730 -- all of the dependents of this SCC also have on-disk linkables (we
731 -- can't have dynamically loaded objects that depend on interpreted
732 -- modules in GHCi).
733 --
734 -- If a module has a valid linkable, then it may be STABLE (see below),
735 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
736 -- compile.
737 --
738 -- ToDo: this pass could be merged with the preUpsweep.
739
740 getValidLinkables
741         :: GhciMode
742         -> [Linkable]           -- old linkables
743         -> [ModuleName]         -- all home modules
744         -> [SCC ModSummary]     -- all modules in the program, dependency order
745         -> IO ( [Linkable],     -- still-valid linkables 
746                 [Linkable]      -- new linkables we just found
747               )
748
749 getValidLinkables mode old_linkables all_home_mods module_graph = do
750   ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods) 
751                 [] module_graph
752   return (partition_it ls [] [])
753  where
754   partition_it []         valid new = (valid,new)
755   partition_it ((l,b):ls) valid new 
756         | b         = partition_it ls valid (l:new)
757         | otherwise = partition_it ls (l:valid) new
758
759
760 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
761    = let 
762           scc             = flattenSCC scc0
763           scc_names       = map modSummaryName scc
764           home_module m   = m `elem` all_home_mods && m `notElem` scc_names
765           scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
766                 -- NB. ms_imps, not ms_allimps above.  We don't want to
767                 -- force a module's SOURCE imports to be already compiled for
768                 -- its object linkable to be valid.
769
770           has_object m = 
771                 case findModuleLinkable_maybe (map fst new_linkables) m of
772                     Nothing -> False
773                     Just l  -> isObjectLinkable l
774
775           objects_allowed = mode == Batch || all has_object scc_allhomeimps
776      in do
777
778      new_linkables'
779         <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
780
781         -- since an scc can contain only all objects or no objects at all,
782         -- we have to check whether we got all objects or not, and re-do
783         -- the linkable check if not.
784      new_linkables' <- 
785         if objects_allowed
786              && not (all isObjectLinkable (map fst new_linkables'))
787           then foldM (getValidLinkable old_linkables False) [] scc
788           else return new_linkables'
789
790      return (new_linkables ++ new_linkables')
791
792
793 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary 
794         -> IO [(Linkable,Bool)]
795         -- True <=> linkable is new
796 getValidLinkable old_linkables objects_allowed new_linkables summary 
797    = do let mod_name = modSummaryName summary
798
799         maybe_disk_linkable
800           <- if (not objects_allowed)
801                 then return Nothing
802
803                 else case ml_obj_file (ms_location summary) of
804                         Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
805                         Nothing     -> return Nothing
806
807         let old_linkable = findModuleLinkable_maybe old_linkables mod_name
808
809             new_linkables' = 
810              case (old_linkable, maybe_disk_linkable) of
811                 (Nothing, Nothing)                      -> []
812
813                 -- new object linkable just appeared
814                 (Nothing, Just l)                       -> up_to_date l True
815
816                 (Just l,  Nothing)
817                   | isObjectLinkable l                  -> []
818                     -- object linkable disappeared!  In case we need to
819                     -- relink the module, disregard the old linkable and
820                     -- just interpret the module from now on.
821                   | otherwise                           -> up_to_date l False
822                     -- old byte code linkable
823
824                 (Just l, Just l') 
825                   | not (isObjectLinkable l)            -> up_to_date l  False
826                     -- if the previous linkable was interpreted, then we
827                     -- ignore a newly compiled version, because the version
828                     -- numbers in the interface file will be out-of-sync with
829                     -- our internal ones.
830                   | linkableTime l' >  linkableTime l   -> up_to_date l' True
831                   | linkableTime l' == linkableTime l   -> up_to_date l  False
832                   | otherwise                           -> []
833                     -- on-disk linkable has been replaced by an older one!
834                     -- again, disregard the previous one.
835
836             up_to_date l b
837                 | linkableTime l < ms_hs_date summary = []
838                 | otherwise = [(l,b)]
839                 -- why '<' rather than '<=' above?  If the filesystem stores
840                 -- times to the nearset second, we may occasionally find that
841                 -- the object & source have the same modification time, 
842                 -- especially if the source was automatically generated
843                 -- and compiled.  Using >= is slightly unsafe, but it matches
844                 -- make's behaviour.
845
846         return (new_linkables' ++ new_linkables)
847
848
849 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
850 maybe_getFileLinkable mod obj_fn
851    = do obj_exist <- doesFileExist obj_fn
852         if not obj_exist 
853          then return Nothing 
854          else 
855          do let stub_fn = case splitFilename3 obj_fn of
856                              (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
857             stub_exist <- doesFileExist stub_fn
858             obj_time <- getModificationTime obj_fn
859             if stub_exist
860              then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
861              else return (Just (LM obj_time mod [DotO obj_fn]))
862
863
864 -----------------------------------------------------------------------------
865 -- Do a pre-upsweep without use of "compile", to establish a 
866 -- (downward-closed) set of stable modules for which we won't call compile.
867
868 -- a stable module:
869 --      * has a valid linkable (see getValidLinkables above)
870 --      * depends only on stable modules
871 --      * has an interface in the HIT (interactive mode only)
872
873 preUpsweep :: [Linkable]        -- new valid linkables
874            -> [ModuleName]      -- names of all mods encountered in downsweep
875            -> [ModuleName]      -- accumulating stable modules
876            -> [SCC ModSummary]  -- scc-ified mod graph, including src imps
877            -> IO [ModuleName]   -- stable modules
878
879 preUpsweep valid_lis all_home_mods stable []  = return stable
880 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
881    = do let scc = flattenSCC scc0
882             scc_allhomeimps :: [ModuleName]
883             scc_allhomeimps 
884                = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
885             all_imports_in_scc_or_stable
886                = all in_stable_or_scc scc_allhomeimps
887             scc_names
888                 = map modSummaryName scc
889             in_stable_or_scc m
890                = m `elem` scc_names || m `elem` stable
891
892             -- now we check for valid linkables: each module in the SCC must 
893             -- have a valid linkable (see getValidLinkables above).
894             has_valid_linkable new_summary
895               = isJust (findModuleLinkable_maybe valid_lis modname)
896                where modname = modSummaryName new_summary
897
898             scc_is_stable = all_imports_in_scc_or_stable
899                           && all has_valid_linkable scc
900
901         if scc_is_stable
902          then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
903          else preUpsweep valid_lis all_home_mods stable sccs
904
905
906 -- Helper for preUpsweep.  Assuming that new_summary's imports are all
907 -- stable (in the sense of preUpsweep), determine if new_summary is itself
908 -- stable, and, if so, in batch mode, return its linkable.
909 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
910 findInSummaries old_summaries mod_name
911    = [s | s <- old_summaries, modSummaryName s == mod_name]
912
913 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
914 findModInSummaries old_summaries mod
915    = case [s | s <- old_summaries, ms_mod s == mod] of
916          [] -> Nothing
917          (s:_) -> Just s
918
919 -- Return (names of) all those in modsDone who are part of a cycle
920 -- as defined by theGraph.
921 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
922 findPartiallyCompletedCycles modsDone theGraph
923    = chew theGraph
924      where
925         chew [] = []
926         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
927         chew ((CyclicSCC vs):rest)
928            = let names_in_this_cycle = nub (map modSummaryName vs)
929                  mods_in_this_cycle  
930                     = nub ([done | done <- modsDone, 
931                                    done `elem` names_in_this_cycle])
932                  chewed_rest = chew rest
933              in 
934              if   notNull mods_in_this_cycle
935                   && length mods_in_this_cycle < length names_in_this_cycle
936              then mods_in_this_cycle ++ chewed_rest
937              else chewed_rest
938
939
940 -- Add the given (LM-form) Linkables to the UI, overwriting previous
941 -- versions if they exist.
942 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
943 add_to_ui ui lis
944    = filter (not_in lis) ui ++ lis
945      where
946         not_in :: [Linkable] -> Linkable -> Bool
947         not_in lis li
948            = all (\l -> linkableModName l /= mod) lis
949            where mod = linkableModName li
950                                   
951
952 data CmThreaded  -- stuff threaded through individual module compilations
953    = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
954
955
956 -- Compile multiple modules, stopping as soon as an error appears.
957 -- There better had not be any cyclic groups here -- we check for them.
958 upsweep_mods :: GhciMode
959              -> DynFlags
960              -> UnlinkedImage         -- valid linkables
961              -> (ModuleName -> [ModuleName])  -- to construct downward closures
962              -> CmThreaded            -- PCS & HST & HIT
963              -> IO ()                 -- how to clean up unwanted tmp files
964              -> [SCC ModSummary]      -- mods to do (the worklist)
965                                       -- ...... RETURNING ......
966              -> IO (Bool{-complete success?-},
967                     CmThreaded,
968                     [ModSummary],     -- mods which succeeded
969                     [Linkable])       -- new linkables
970
971 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
972      []
973    = return (True, threaded, [], [])
974
975 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
976      ((CyclicSCC ms):_)
977    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
978                           unwords (map (moduleNameUserString.modSummaryName) ms))
979         return (False, threaded, [], [])
980
981 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
982      ((AcyclicSCC mod):mods)
983    = do --case threaded of
984         --   CmThreaded pcsz hstz hitz
985         --      -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
986
987         (threaded1, maybe_linkable) 
988            <- upsweep_mod ghci_mode dflags oldUI threaded mod 
989                           (reachable_from (modSummaryName mod))
990
991         -- remove unwanted tmp files between compilations
992         cleanup
993
994         case maybe_linkable of
995            Just linkable 
996               -> -- No errors; do the rest
997                  do (restOK, threaded2, modOKs, linkables) 
998                        <- upsweep_mods ghci_mode dflags oldUI reachable_from 
999                                        threaded1 cleanup mods
1000                     return (restOK, threaded2, mod:modOKs, linkable:linkables)
1001            Nothing -- we got a compilation error; give up now
1002               -> return (False, threaded1, [], [])
1003
1004
1005 -- Compile a single module.  Always produce a Linkable for it if 
1006 -- successful.  If no compilation happened, return the old Linkable.
1007 upsweep_mod :: GhciMode 
1008             -> DynFlags
1009             -> UnlinkedImage
1010             -> CmThreaded
1011             -> ModSummary
1012             -> [ModuleName]
1013             -> IO (CmThreaded, Maybe Linkable)
1014
1015 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1016    = do 
1017         let mod_name = modSummaryName summary1
1018
1019         let (CmThreaded pcs1 hst1 hit1) = threaded1
1020         let old_iface = lookupUFM hit1 mod_name
1021
1022         let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1023
1024             source_unchanged = isJust maybe_old_linkable
1025
1026             reachable_only = filter (/= (modSummaryName summary1)) 
1027                                 reachable_inc_me
1028
1029            -- in interactive mode, all home modules below us *must* have an
1030            -- interface in the HIT.  We never demand-load home interfaces in
1031            -- interactive mode.
1032             (hst1_strictDC, hit1_strictDC, [])
1033                = ASSERT(ghci_mode == Batch || 
1034                         all (`elemUFM` hit1) reachable_only)
1035                  retainInTopLevelEnvs reachable_only (hst1,hit1,[])
1036
1037             old_linkable 
1038                = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1039
1040             have_object 
1041                | Just l <- maybe_old_linkable, isObjectLinkable l = True
1042                | otherwise = False
1043
1044         compresult <- compile ghci_mode summary1 source_unchanged
1045                          have_object old_iface hst1_strictDC hit1_strictDC pcs1
1046
1047         case compresult of
1048
1049            -- Compilation "succeeded", and may or may not have returned a new
1050            -- linkable (depending on whether compilation was actually performed
1051            -- or not).
1052            CompOK pcs2 new_details new_iface maybe_new_linkable
1053               -> do let hst2      = addToUFM hst1 mod_name new_details
1054                         hit2      = addToUFM hit1 mod_name new_iface
1055                         threaded2 = CmThreaded pcs2 hst2 hit2
1056
1057                     return (threaded2, if isJust maybe_new_linkable
1058                                           then maybe_new_linkable
1059                                           else Just old_linkable)
1060
1061            -- Compilation failed.  compile may still have updated
1062            -- the PCS, tho.
1063            CompErrs pcs2
1064               -> do let threaded2 = CmThreaded pcs2 hst1 hit1
1065                     return (threaded2, Nothing)
1066
1067 -- Filter modules in the top level envs (HST, HIT, UI).
1068 retainInTopLevelEnvs :: [ModuleName]
1069                         -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1070                         -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1071 retainInTopLevelEnvs keep_these (hst, hit, ui)
1072    = (retainInUFM hst keep_these,
1073       retainInUFM hit keep_these,
1074       filterModuleLinkables (`elem` keep_these) ui
1075      )
1076      where
1077         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1078         retainInUFM ufm keys_to_keep
1079            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1080         maybeLookupUFM ufm u 
1081            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
1082
1083 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1084 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1085 downwards_closure_of_module summaries root
1086    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1087          toEdge summ = (modSummaryName summ, 
1088                         filter (`elem` all_mods) (ms_allimps summ))
1089
1090          all_mods = map modSummaryName summaries
1091
1092          res = simple_transitive_closure (map toEdge summaries) [root]
1093      in
1094 --         trace (showSDoc (text "DC of mod" <+> ppr root
1095 --                          <+> text "=" <+> ppr res)) $
1096          res
1097
1098 -- Calculate transitive closures from a set of roots given an adjacency list
1099 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1100 simple_transitive_closure graph set 
1101    = let set2      = nub (concatMap dsts set ++ set)
1102          dsts node = fromMaybe [] (lookup node graph)
1103      in
1104          if   length set == length set2
1105          then set
1106          else simple_transitive_closure graph set2
1107
1108
1109 -- Calculate SCCs of the module graph, with or without taking into
1110 -- account source imports.
1111 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1112 topological_sort include_source_imports summaries
1113    = let 
1114          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1115          toEdge summ
1116              = (summ, modSummaryName summ, 
1117                       (if include_source_imports 
1118                        then ms_srcimps summ else []) ++ ms_imps summ)
1119         
1120          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1121          mash_edge (summ, m, m_imports)
1122             = case lookup m key_map of
1123                  Nothing -> panic "reverse_topological_sort"
1124                  Just mk -> (summ, mk, 
1125                                 -- ignore imports not from the home package
1126                                 catMaybes (map (flip lookup key_map) m_imports))
1127
1128          edges     = map toEdge summaries
1129          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1130          scc_input = map mash_edge edges
1131          sccs      = stronglyConnComp scc_input
1132      in
1133          sccs
1134
1135
1136 -----------------------------------------------------------------------------
1137 -- Downsweep (dependency analysis)
1138
1139 -- Chase downwards from the specified root set, returning summaries
1140 -- for all home modules encountered.  Only follow source-import
1141 -- links.
1142
1143 -- We pass in the previous collection of summaries, which is used as a
1144 -- cache to avoid recalculating a module summary if the source is
1145 -- unchanged.
1146
1147 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1148 downsweep roots old_summaries
1149    = do rootSummaries <- mapM getRootSummary roots
1150         checkDuplicates rootSummaries
1151         all_summaries
1152            <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1153                                             (ms_imps m)) rootSummaries))
1154                 (mkModuleEnv [ (mod, s) | s <- rootSummaries, 
1155                                           let mod = ms_mod s, isHomeModule mod 
1156                              ])
1157         return all_summaries
1158      where
1159         getRootSummary :: FilePath -> IO ModSummary
1160         getRootSummary file
1161            | haskellish_src_file file
1162            = do exists <- doesFileExist file
1163                 if exists then summariseFile file else do
1164                 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))    
1165            | otherwise
1166            = do exists <- doesFileExist hs_file
1167                 if exists then summariseFile hs_file else do
1168                 exists <- doesFileExist lhs_file
1169                 if exists then summariseFile lhs_file else do
1170                 let mod_name = mkModuleName file
1171                 maybe_summary <- getSummary (file, mod_name)
1172                 case maybe_summary of
1173                    Nothing -> packageModErr mod_name
1174                    Just s  -> return s
1175            where 
1176                  hs_file = file ++ ".hs"
1177                  lhs_file = file ++ ".lhs"
1178
1179         -- In a root module, the filename is allowed to diverge from the module
1180         -- name, so we have to check that there aren't multiple root files
1181         -- defining the same module (otherwise the duplicates will be silently
1182         -- ignored, leading to confusing behaviour).
1183         checkDuplicates :: [ModSummary] -> IO ()
1184         checkDuplicates summaries = mapM_ check summaries
1185           where check summ = 
1186                   case dups of
1187                         []     -> return ()
1188                         [_one] -> return ()
1189                         many   -> multiRootsErr modl many
1190                    where modl = ms_mod summ
1191                          dups = 
1192                            [ fromJust (ml_hs_file (ms_location summ'))
1193                            | summ' <- summaries, ms_mod summ' == modl ]
1194
1195         getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1196         getSummary (currentMod,nm)
1197            = do found <- findModule nm
1198                 case found of
1199                    Just (mod, location) -> do
1200                         let old_summary = findModInSummaries old_summaries mod
1201                         summarise mod location old_summary
1202
1203                    Nothing -> 
1204                         throwDyn (CmdLineError 
1205                                    ("can't find module `" 
1206                                      ++ showSDoc (ppr nm) ++ "' (while processing " 
1207                                      ++ show currentMod ++ ")"))
1208
1209         -- loop invariant: env doesn't contain package modules
1210         loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1211         loop [] env = return (moduleEnvElts env)
1212         loop imps env
1213            = do -- imports for modules we don't already have
1214                 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1215
1216                 -- summarise them
1217                 needed_summaries <- mapM getSummary needed_imps
1218
1219                 -- get just the "home" modules
1220                 let new_home_summaries = [ s | Just s <- needed_summaries ]
1221
1222                 -- loop, checking the new imports
1223                 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1224                                                        (ms_imps m)) new_home_summaries)
1225                 loop new_imps (extendModuleEnvList env 
1226                                 [ (ms_mod s, s) | s <- new_home_summaries ])
1227
1228 -----------------------------------------------------------------------------
1229 -- Summarising modules
1230
1231 -- We have two types of summarisation:
1232 --
1233 --    * Summarise a file.  This is used for the root module(s) passed to
1234 --      cmLoadModules.  The file is read, and used to determine the root
1235 --      module name.  The module name may differ from the filename.
1236 --
1237 --    * Summarise a module.  We are given a module name, and must provide
1238 --      a summary.  The finder is used to locate the file in which the module
1239 --      resides.
1240
1241 summariseFile :: FilePath -> IO ModSummary
1242 summariseFile file
1243    = do hspp_fn <- preprocess file
1244         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1245
1246         let (path, basename, _ext) = splitFilename3 file
1247              -- GHC.Prim doesn't exist physically, so don't go looking for it.
1248             the_imps = filter (/= gHC_PRIM_Name) imps
1249
1250         (mod, location)
1251            <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1252
1253         src_timestamp
1254            <- case ml_hs_file location of 
1255                  Nothing     -> noHsFileErr mod_name
1256                  Just src_fn -> getModificationTime src_fn
1257
1258         return (ModSummary mod
1259                            location{ml_hspp_file=Just hspp_fn}
1260                            srcimps the_imps src_timestamp)
1261
1262 -- Summarise a module, and pick up source and timestamp.
1263 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1264          -> IO (Maybe ModSummary)
1265 summarise mod location old_summary
1266    | not (isHomeModule mod) = return Nothing
1267    | otherwise
1268    = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1269
1270         case ml_hs_file location of {
1271            Nothing -> noHsFileErr mod;
1272            Just src_fn -> do
1273
1274         src_timestamp <- getModificationTime src_fn
1275
1276         -- return the cached summary if the source didn't change
1277         case old_summary of {
1278            Just s | ms_hs_date s == src_timestamp -> return (Just s);
1279            _ -> do
1280
1281         hspp_fn <- preprocess hs_fn
1282         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1283         let
1284              -- GHC.Prim doesn't exist physically, so don't go looking for it.
1285            the_imps = filter (/= gHC_PRIM_Name) imps
1286
1287         when (mod_name /= moduleName mod) $
1288                 throwDyn (ProgramError 
1289                    (showSDoc (text hs_fn
1290                               <>  text ": file name does not match module name"
1291                               <+> quotes (ppr (moduleName mod)))))
1292
1293         return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
1294                                  srcimps the_imps src_timestamp))
1295         }
1296       }
1297
1298
1299 noHsFileErr mod
1300   = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1301
1302 packageModErr mod
1303   = throwDyn (CmdLineError (showSDoc (text "module" <+>
1304                                    quotes (ppr mod) <+>
1305                                    text "is a package module")))
1306
1307 multiRootsErr mod files
1308   = throwDyn (ProgramError (showSDoc (
1309         text "module" <+> quotes (ppr mod) <+> 
1310         text "is defined in multiple files:" <+>
1311         sep (map text files))))
1312 \end{code}