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