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