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