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