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