[project @ 2001-02-07 16:23:28 by simonmar]
[ghc-hetmet.git] / ghc / compiler / compMan / CompManager.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section[CompManager]{The Compilation Manager}
5
6 \begin{code}
7 module CompManager ( cmInit, cmLoadModule, cmUnload,
8 #ifdef GHCI
9                      cmGetExpr, cmRunExpr,
10 #endif
11                      CmState, emptyCmState  -- abstract
12                    )
13 where
14
15 #include "HsVersions.h"
16
17 import CmLink
18 import CmTypes
19 import HscTypes
20 import Module           ( Module, ModuleName, moduleName, isHomeModule,
21                           mkModuleName, moduleNameUserString )
22 import CmStaticInfo     ( GhciMode(..) )
23 import DriverPipeline
24 import GetImports
25 import HscTypes         ( HomeSymbolTable, HomeIfaceTable, 
26                           PersistentCompilerState, ModDetails(..) )
27 import HscMain          ( initPersistentCompilerState )
28 import Finder
29 import UniqFM           ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
30                           UniqFM, listToUFM )
31 import Unique           ( Uniquable )
32 import Digraph          ( SCC(..), stronglyConnComp, flattenSCC )
33 import DriverFlags      ( getDynFlags )
34 import DriverPhases
35 import DriverUtil       ( splitFilename3 )
36 import ErrUtils         ( showPass )
37 import Util
38 import DriverUtil
39 import Outputable
40 import Panic
41 import CmdLineOpts      ( DynFlags(..) )
42 import IOExts
43
44 #ifdef GHCI
45 import Interpreter      ( HValue )
46 import HscMain          ( hscExpr )
47 import Type             ( Type )
48 import PrelGHC          ( unsafeCoerce# )
49 #endif
50
51 -- lang
52 import Exception        ( throwDyn )
53
54 -- std
55 import Time             ( ClockTime )
56 import Directory        ( getModificationTime, doesFileExist )
57 import IO
58 import Monad
59 import List             ( nub )
60 import Maybe            ( catMaybes, fromMaybe, isJust, fromJust )
61 \end{code}
62
63
64 \begin{code}
65 cmInit :: GhciMode -> IO CmState
66 cmInit gmode
67    = emptyCmState gmode
68
69 #ifdef GHCI
70 cmGetExpr :: CmState
71           -> DynFlags
72           -> Bool       -- True <=> wrap in 'print' to get an IO-typed result
73           -> Module
74           -> String
75           -> IO (CmState, Maybe (HValue, PrintUnqualified, Type))
76 cmGetExpr cmstate dflags wrap_io mod expr
77    = do (new_pcs, maybe_stuff) <- 
78            hscExpr dflags wrap_io hst hit pcs mod expr
79         case maybe_stuff of
80            Nothing     -> return (cmstate{ pcs=new_pcs }, Nothing)
81            Just (bcos, print_unqual, ty) -> do
82                 hValue <- linkExpr pls bcos
83                 return (cmstate{ pcs=new_pcs }, 
84                         Just (hValue, print_unqual, ty))
85
86    -- ToDo: check that the module we passed in is sane/exists?
87    where
88        CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls } = cmstate
89
90 -- The HValue should represent a value of type IO () (Perhaps IO a?)
91 cmRunExpr :: HValue -> IO ()
92 cmRunExpr hval
93    = do unsafeCoerce# hval :: IO ()
94         -- putStrLn "done."
95 #endif
96
97 emptyHIT :: HomeIfaceTable
98 emptyHIT = emptyUFM
99 emptyHST :: HomeSymbolTable
100 emptyHST = emptyUFM
101
102 -- Persistent state for the entire system
103 data CmState
104    = CmState {
105         hst   :: HomeSymbolTable,    -- home symbol table
106         hit   :: HomeIfaceTable,     -- home interface table
107         ui    :: UnlinkedImage,      -- the unlinked images
108         mg    :: ModuleGraph,        -- the module graph
109         gmode :: GhciMode,           -- NEVER CHANGES
110
111         pcs    :: PersistentCompilerState, -- compile's persistent state
112         pls    :: PersistentLinkerState    -- link's persistent state
113      }
114
115 emptyCmState :: GhciMode -> IO CmState
116 emptyCmState gmode
117     = do pcs     <- initPersistentCompilerState
118          pls     <- emptyPLS
119          return (CmState { hst = emptyHST,
120                            hit = emptyHIT,
121                            ui  = emptyUI,
122                            mg  = emptyMG, 
123                            gmode = gmode,
124                            pcs    = pcs,
125                            pls    = pls })
126
127 -- CM internal types
128 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
129 emptyUI :: UnlinkedImage
130 emptyUI = []
131
132 type ModuleGraph = [ModSummary]  -- the module graph, topologically sorted
133 emptyMG :: ModuleGraph
134 emptyMG = []
135
136 \end{code}
137
138 Unload the compilation manager's state: everything it knows about the
139 current collection of modules in the Home package.
140
141 \begin{code}
142 cmUnload :: CmState -> IO CmState
143 cmUnload state 
144  = do -- Throw away the old home dir cache
145       emptyHomeDirCache
146       -- Throw away the HIT and the HST
147       return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
148    where
149      CmState{ hst=hst, hit=hit } = state
150      (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
151 \end{code}
152
153 The real business of the compilation manager: given a system state and
154 a module name, try and bring the module up to date, probably changing
155 the system state at the same time.
156
157 \begin{code}
158 cmLoadModule :: CmState 
159              -> FilePath
160              -> IO (CmState,            -- new state
161                     Bool,               -- was successful
162                     [Module])           -- list of modules loaded
163
164 cmLoadModule cmstate1 rootname
165    = do -- version 1's are the original, before downsweep
166         let pls1      = pls    cmstate1
167         let pcs1      = pcs    cmstate1
168         let hst1      = hst    cmstate1
169         let hit1      = hit    cmstate1
170         -- similarly, ui1 is the (complete) set of linkables from
171         -- the previous pass, if any.
172         let ui1       = ui     cmstate1
173         let mg1       = mg     cmstate1
174
175         let ghci_mode = gmode cmstate1 -- this never changes
176
177         -- Do the downsweep to reestablish the module graph
178         -- then generate version 2's by retaining in HIT,HST,UI a
179         -- stable set S of modules, as defined below.
180
181         dflags <- getDynFlags
182         let verb = verbosity dflags
183
184         showPass dflags "Chasing dependencies"
185         when (verb >= 1 && ghci_mode == Batch) $
186            hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
187
188         (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
189         let mg2unsorted_names = map name_of_summary mg2unsorted
190
191         -- reachable_from follows source as well as normal imports
192         let reachable_from :: ModuleName -> [ModuleName]
193             reachable_from = downwards_closure_of_module mg2unsorted
194  
195         -- should be cycle free; ignores 'import source's
196         let mg2 = topological_sort False mg2unsorted
197         -- ... whereas this takes them into account.  Used for
198         -- backing out partially complete cycles following a failed
199         -- upsweep, and for removing from hst/hit all the modules
200         -- not in strict downwards closure, during calls to compile.
201         let mg2_with_srcimps = topological_sort True mg2unsorted
202
203         -- Sort out which linkables we wish to keep in the unlinked image.
204         -- See getValidLinkables below for details.
205         valid_linkables <- getValidLinkables ui1 mg2unsorted_names 
206                                 mg2_with_srcimps
207         pprTrace "valid_linkables" (ppr valid_linkables) $ do
208
209         -- Figure out a stable set of modules which can be retained
210         -- the top level envs, to avoid upsweeping them.  Goes to a
211         -- bit of trouble to avoid upsweeping module cycles.
212         --
213         -- Construct a set S of stable modules like this:
214         -- Travel upwards, over the sccified graph.  For each scc
215         -- of modules ms, add ms to S only if:
216         -- 1.  All home imports of ms are either in ms or S
217         -- 2.  A valid linkable exists for each module in ms
218
219         stable_mods
220            <- preUpsweep valid_linkables ui1 mg2unsorted_names
221                  [] mg2_with_srcimps
222
223         let stable_summaries
224                = concatMap (findInSummaries mg2unsorted) stable_mods
225
226             stable_linkables
227                = filter (\m -> linkableModName m `elem` stable_mods) 
228                     valid_linkables
229
230         when (verb >= 2) $
231            putStrLn (showSDoc (text "STABLE MODULES:" 
232                                <+> sep (map (text.moduleNameUserString) stable_mods)))
233
234         -- unload any modules which aren't going to be re-linked this
235         -- time around.
236         pls2 <- unload ghci_mode dflags stable_linkables pls1
237
238         -- We could at this point detect cycles which aren't broken by
239         -- a source-import, and complain immediately, but it seems better
240         -- to let upsweep_mods do this, so at least some useful work gets
241         -- done before the upsweep is abandoned.
242         let upsweep_these
243                = filter (\scc -> any (`notElem` stable_mods) 
244                                      (map name_of_summary (flattenSCC scc)))
245                         mg2
246
247         --hPutStrLn stderr "after tsort:\n"
248         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
249
250         -- Because we don't take into account source imports when doing
251         -- the topological sort, there shouldn't be any cycles in mg2.
252         -- If there is, we complain and give up -- the user needs to
253         -- break the cycle using a boot file.
254
255         -- Now do the upsweep, calling compile for each module in
256         -- turn.  Final result is version 3 of everything.
257
258         let threaded2 = CmThreaded pcs1 hst1 hit1
259
260         (upsweep_complete_success, threaded3, modsUpswept, newLis)
261            <- upsweep_mods ghci_mode dflags valid_linkables reachable_from 
262                            threaded2 upsweep_these
263
264         let ui3 = add_to_ui valid_linkables newLis
265         let (CmThreaded pcs3 hst3 hit3) = threaded3
266
267         -- At this point, modsUpswept and newLis should have the same
268         -- length, so there is one new (or old) linkable for each 
269         -- mod which was processed (passed to compile).
270
271         -- Make modsDone be the summaries for each home module now
272         -- available; this should equal the domains of hst3 and hit3.
273         -- (NOT STRICTLY TRUE if an interactive session was started
274         --  with some object on disk ???)
275         -- Get in in a roughly top .. bottom order (hence reverse).
276
277         let modsDone = reverse modsUpswept ++ stable_summaries
278
279         -- Try and do linking in some form, depending on whether the
280         -- upsweep was completely or only partially successful.
281
282         if upsweep_complete_success
283
284          then 
285            -- Easy; just relink it all.
286            do when (verb >= 2) $ 
287                  hPutStrLn stderr "Upsweep completely successful."
288               linkresult 
289                  <- link ghci_mode dflags a_root_is_Main ui3 pls2
290               case linkresult of
291                  LinkErrs _ _
292                     -> panic "cmLoadModule: link failed (1)"
293                  LinkOK pls3 
294                     -> do let cmstate3 
295                                  = CmState { hst=hst3, hit=hit3, 
296                                              ui=ui3, mg=modsDone, 
297                                              gmode=ghci_mode,
298                                              pcs=pcs3, pls=pls3 }
299                           return (cmstate3, True, 
300                                   map ms_mod modsDone)
301
302          else 
303            -- Tricky.  We need to back out the effects of compiling any
304            -- half-done cycles, both so as to clean up the top level envs
305            -- and to avoid telling the interactive linker to link them.
306            do when (verb >= 2) $
307                 hPutStrLn stderr "Upsweep partially successful."
308
309               let modsDone_names
310                      = map name_of_summary modsDone
311               let mods_to_zap_names 
312                      = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
313               let (hst4, hit4, ui4) 
314                      = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
315               let mods_to_keep
316                      = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
317               let mods_to_keep_names 
318                      = map name_of_summary mods_to_keep
319               -- we could get the relevant linkables by filtering newLis, but
320               -- it seems easier to drag them out of the updated, cleaned-up UI
321               let linkables_to_link 
322                      = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
323                            mods_to_keep_names
324
325               linkresult <- link ghci_mode dflags False linkables_to_link pls2
326               case linkresult of
327                  LinkErrs _ _
328                     -> panic "cmLoadModule: link failed (2)"
329                  LinkOK pls3
330                     -> do let cmstate4 
331                                  = CmState { hst=hst4, hit=hit4, 
332                                              ui=ui4, mg=mods_to_keep,
333                                              gmode=ghci_mode, pcs=pcs3, pls=pls3 }
334                           return (cmstate4, False, 
335                                   map ms_mod mods_to_keep)
336
337
338 -----------------------------------------------------------------------------
339 -- getValidLinkables
340
341 -- For each module (or SCC of modules), we take:
342 --
343 --      - the old in-core linkable, if available
344 --      - an on-disk linkable, if available
345 --
346 -- and we take the youngest of these, provided it is younger than the
347 -- source file.  We ignore the on-disk linkables unless all of the
348 -- dependents of this SCC also have on-disk linkables.
349 --
350 -- If a module has a valid linkable, then it may be STABLE (see below),
351 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
352 -- compile.
353 --
354 -- ToDo: this pass could be merged with the preUpsweep.
355
356 getValidLinkables
357         :: [Linkable]           -- old linkables
358         -> [ModuleName]         -- all home modules
359         -> [SCC ModSummary]     -- all modules in the program, dependency order
360         -> IO [Linkable]        -- still-valid linkables 
361
362 getValidLinkables old_linkables all_home_mods module_graph
363   = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
364
365 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
366    = let 
367           scc             = flattenSCC scc0
368           scc_names       = map name_of_summary scc
369           home_module m   = m `elem` all_home_mods && m `notElem` scc_names
370           scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
371
372           has_object m = case findModuleLinkable_maybe new_linkables m of
373                             Nothing -> False
374                             Just l  -> isObjectLinkable l
375
376           objects_allowed = all has_object scc_allhomeimps
377      in do
378
379      these_linkables 
380         <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
381
382         -- since an scc can contain only all objects or no objects at all,
383         -- we have to check whether we got all objects or not, and re-do
384         -- the linkable check if not.
385      adjusted_linkables 
386         <- if objects_allowed && not (all isObjectLinkable these_linkables)
387               then foldM (getValidLinkable old_linkables False) [] scc
388               else return these_linkables
389
390      return (adjusted_linkables ++ new_linkables)
391
392
393 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary 
394         -> IO [Linkable]
395 getValidLinkable old_linkables objects_allowed new_linkables summary 
396    = do 
397         let mod_name = name_of_summary summary
398
399         maybe_disk_linkable
400            <- if (not objects_allowed)
401                 then return Nothing
402                 else case ml_obj_file (ms_location summary) of
403                         Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
404                         Nothing -> return Nothing
405
406          -- find an old in-core linkable if we have one. (forget about
407          -- on-disk linkables for now, we'll check again whether there's
408          -- one here below, just in case a new one has popped up recently).
409         let old_linkable = findModuleLinkable_maybe old_linkables mod_name
410             maybe_old_linkable =
411                 case old_linkable of
412                     Just (LM _ _ ls) | all isInterpretable ls -> old_linkable
413                     _ -> Nothing
414
415         -- The most recent of the old UI linkable or whatever we could
416         -- find on disk is returned as the linkable if compile
417         -- doesn't think we need to recompile.        
418         let linkable_list
419                = case (maybe_old_linkable, maybe_disk_linkable) of
420                     (Nothing, Nothing) -> []
421                     (Nothing, Just di) -> [di]
422                     (Just ui, Nothing) -> [ui]
423                     (Just ui, Just di)
424                        | linkableTime ui >= linkableTime di -> [ui]
425                        | otherwise                          -> [di]
426
427         -- only linkables newer than the source code are valid
428         let maybe_src_date = ms_hs_date summary
429
430             valid_linkable_list
431               = case maybe_src_date of
432                   Nothing -> panic "valid_linkable_list"
433                   Just src_date 
434                      -> filter (\li -> linkableTime li > src_date) linkable_list
435
436         return (valid_linkable_list ++ new_linkables)
437
438
439 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
440 maybe_getFileLinkable mod_name obj_fn
441    = do obj_exist <- doesFileExist obj_fn
442         if not obj_exist 
443          then return Nothing 
444          else 
445          do let stub_fn = case splitFilename3 obj_fn of
446                              (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
447             stub_exist <- doesFileExist stub_fn
448             obj_time <- getModificationTime obj_fn
449             if stub_exist
450              then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
451              else return (Just (LM obj_time mod_name [DotO obj_fn]))
452
453
454 -----------------------------------------------------------------------------
455 -- Do a pre-upsweep without use of "compile", to establish a 
456 -- (downward-closed) set of stable modules for which we won't call compile.
457
458 preUpsweep :: [Linkable]        -- new valid linkables
459            -> [Linkable]        -- old linkables
460            -> [ModuleName]      -- names of all mods encountered in downsweep
461            -> [ModuleName]      -- accumulating stable modules
462            -> [SCC ModSummary]  -- scc-ified mod graph, including src imps
463            -> IO [ModuleName]   -- stable modules
464
465 preUpsweep valid_lis old_lis all_home_mods stable [] 
466    = return stable
467 preUpsweep valid_lis old_lis all_home_mods stable (scc0:sccs)
468    = do let scc = flattenSCC scc0
469             scc_allhomeimps :: [ModuleName]
470             scc_allhomeimps 
471                = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
472             all_imports_in_scc_or_stable
473                = all in_stable_or_scc scc_allhomeimps
474             scc_names
475                = map name_of_summary scc
476             in_stable_or_scc m
477                = m `elem` scc_names || m `elem` stable
478
479             -- now we check for valid linkables: each module in the SCC must 
480             -- have a valid linkable (see getValidLinkables above), and the
481             -- newest linkable must be the same as the previous linkable for
482             -- this module (if one exists).
483             has_valid_linkable new_summary
484               = case findModuleLinkable_maybe valid_lis modname of
485                    Nothing -> False
486                    Just l  -> case findModuleLinkable_maybe old_lis modname of
487                                 Nothing -> True
488                                 Just m  -> linkableTime l == linkableTime m
489                where modname = name_of_summary new_summary
490
491             scc_is_stable = all_imports_in_scc_or_stable
492                           && all has_valid_linkable scc
493
494         if scc_is_stable
495          then preUpsweep valid_lis old_lis all_home_mods 
496                 (scc_names++stable) sccs
497          else preUpsweep valid_lis old_lis all_home_mods 
498                 stable sccs
499
500    where 
501
502
503 -- Helper for preUpsweep.  Assuming that new_summary's imports are all
504 -- stable (in the sense of preUpsweep), determine if new_summary is itself
505 -- stable, and, if so, in batch mode, return its linkable.
506 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
507 findInSummaries old_summaries mod_name
508    = [s | s <- old_summaries, name_of_summary s == mod_name]
509
510 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
511 findModInSummaries old_summaries mod
512    = case [s | s <- old_summaries, ms_mod s == mod] of
513          [] -> Nothing
514          (s:_) -> Just s
515
516 -- Return (names of) all those in modsDone who are part of a cycle
517 -- as defined by theGraph.
518 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
519 findPartiallyCompletedCycles modsDone theGraph
520    = chew theGraph
521      where
522         chew [] = []
523         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
524         chew ((CyclicSCC vs):rest)
525            = let names_in_this_cycle = nub (map name_of_summary vs)
526                  mods_in_this_cycle  
527                     = nub ([done | done <- modsDone, 
528                                    done `elem` names_in_this_cycle])
529                  chewed_rest = chew rest
530              in 
531              if   not (null mods_in_this_cycle) 
532                   && length mods_in_this_cycle < length names_in_this_cycle
533              then mods_in_this_cycle ++ chewed_rest
534              else chewed_rest
535
536
537 -- Add the given (LM-form) Linkables to the UI, overwriting previous
538 -- versions if they exist.
539 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
540 add_to_ui ui lis
541    = filter (not_in lis) ui ++ lis
542      where
543         not_in :: [Linkable] -> Linkable -> Bool
544         not_in lis li
545            = all (\l -> linkableModName l /= mod) lis
546            where mod = linkableModName li
547                                   
548
549 data CmThreaded  -- stuff threaded through individual module compilations
550    = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
551
552
553 -- Compile multiple modules, stopping as soon as an error appears.
554 -- There better had not be any cyclic groups here -- we check for them.
555 upsweep_mods :: GhciMode
556              -> DynFlags
557              -> UnlinkedImage         -- valid linkables
558              -> (ModuleName -> [ModuleName])  -- to construct downward closures
559              -> CmThreaded            -- PCS & HST & HIT
560              -> [SCC ModSummary]      -- mods to do (the worklist)
561                                       -- ...... RETURNING ......
562              -> IO (Bool{-complete success?-},
563                     CmThreaded,
564                     [ModSummary],     -- mods which succeeded
565                     [Linkable])       -- new linkables
566
567 upsweep_mods ghci_mode dflags oldUI reachable_from threaded 
568      []
569    = return (True, threaded, [], [])
570
571 upsweep_mods ghci_mode dflags oldUI reachable_from threaded 
572      ((CyclicSCC ms):_)
573    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
574                           unwords (map (moduleNameUserString.name_of_summary) ms))
575         return (False, threaded, [], [])
576
577 upsweep_mods ghci_mode dflags oldUI reachable_from threaded 
578      ((AcyclicSCC mod):mods)
579    = do --case threaded of
580         --   CmThreaded pcsz hstz hitz
581         --      -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
582
583         (threaded1, maybe_linkable) 
584            <- upsweep_mod ghci_mode dflags oldUI threaded mod 
585                           (reachable_from (name_of_summary mod))
586         case maybe_linkable of
587            Just linkable 
588               -> -- No errors; do the rest
589                  do (restOK, threaded2, modOKs, linkables) 
590                        <- upsweep_mods ghci_mode dflags oldUI reachable_from 
591                                        threaded1 mods
592                     return (restOK, threaded2, mod:modOKs, linkable:linkables)
593            Nothing -- we got a compilation error; give up now
594               -> return (False, threaded1, [], [])
595
596
597 -- Compile a single module.  Always produce a Linkable for it if 
598 -- successful.  If no compilation happened, return the old Linkable.
599 upsweep_mod :: GhciMode 
600             -> DynFlags
601             -> UnlinkedImage
602             -> CmThreaded
603             -> ModSummary
604             -> [ModuleName]
605             -> IO (CmThreaded, Maybe Linkable)
606
607 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
608    = do 
609         let mod_name = name_of_summary summary1
610         let verb = verbosity dflags
611
612         when (verb == 1) $
613            if (ghci_mode == Batch)
614                 then hPutStr stderr (progName ++ ": module " 
615                         ++ moduleNameUserString mod_name
616                         ++ ": ")
617                 else hPutStr stderr ("Compiling "
618                         ++ moduleNameUserString mod_name
619                         ++ " ... ")
620
621         let (CmThreaded pcs1 hst1 hit1) = threaded1
622         let old_iface = lookupUFM hit1 mod_name
623
624         let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
625
626             source_unchanged = isJust maybe_old_linkable
627
628             (hst1_strictDC, hit1_strictDC)
629                = retainInTopLevelEnvs 
630                     (filter (/= (name_of_summary summary1)) reachable_from_here)
631                     (hst1,hit1)
632
633             old_linkable 
634                = unJust "upsweep_mod:old_linkable" maybe_old_linkable
635
636         compresult <- compile ghci_mode summary1 source_unchanged
637                          old_iface hst1_strictDC hit1_strictDC pcs1
638
639         case compresult of
640
641            -- Compilation "succeeded", but didn't return a new
642            -- linkable, meaning that compilation wasn't needed, and the
643            -- new details were manufactured from the old iface.
644            CompOK pcs2 new_details new_iface Nothing
645               -> do let hst2         = addToUFM hst1 mod_name new_details
646                         hit2         = addToUFM hit1 mod_name new_iface
647                         threaded2    = CmThreaded pcs2 hst2 hit2
648
649                     if ghci_mode == Interactive && verb >= 1 then
650                       -- if we're using an object file, tell the user
651                       case old_linkable of
652                         (LM _ _ objs@(DotO _:_))
653                            -> do hPutStrLn stderr (showSDoc (space <> 
654                                    parens (hsep (text "using": 
655                                         punctuate comma 
656                                           [ text o | DotO o <- objs ]))))
657                         _ -> return ()
658                       else
659                         return ()
660
661                     return (threaded2, Just old_linkable)
662
663            -- Compilation really did happen, and succeeded.  A new
664            -- details, iface and linkable are returned.
665            CompOK pcs2 new_details new_iface (Just new_linkable)
666               -> do let hst2      = addToUFM hst1 mod_name new_details
667                         hit2      = addToUFM hit1 mod_name new_iface
668                         threaded2 = CmThreaded pcs2 hst2 hit2
669
670                     return (threaded2, Just new_linkable)
671
672            -- Compilation failed.  compile may still have updated
673            -- the PCS, tho.
674            CompErrs pcs2
675               -> do let threaded2 = CmThreaded pcs2 hst1 hit1
676                     return (threaded2, Nothing)
677
678 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
679 removeFromTopLevelEnvs :: [ModuleName]
680                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
681                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
682 removeFromTopLevelEnvs zap_these (hst, hit, ui)
683    = (delListFromUFM hst zap_these,
684       delListFromUFM hit zap_these,
685       filterModuleLinkables (`notElem` zap_these) ui
686      )
687
688 retainInTopLevelEnvs :: [ModuleName]
689                         -> (HomeSymbolTable, HomeIfaceTable)
690                         -> (HomeSymbolTable, HomeIfaceTable)
691 retainInTopLevelEnvs keep_these (hst, hit)
692    = (retainInUFM hst keep_these,
693       retainInUFM hit keep_these
694      )
695      where
696         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
697         retainInUFM ufm keys_to_keep
698            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
699         maybeLookupUFM ufm u 
700            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
701
702 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
703 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
704 downwards_closure_of_module summaries root
705    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
706          toEdge summ = (name_of_summary summ, ms_allimps summ)
707          res = simple_transitive_closure (map toEdge summaries) [root]             
708      in
709          --trace (showSDoc (text "DC of mod" <+> ppr root
710          --                 <+> text "=" <+> ppr res)) (
711          res
712          --)
713
714 -- Calculate transitive closures from a set of roots given an adjacency list
715 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
716 simple_transitive_closure graph set 
717    = let set2      = nub (concatMap dsts set ++ set)
718          dsts node = fromMaybe [] (lookup node graph)
719      in
720          if   length set == length set2
721          then set
722          else simple_transitive_closure graph set2
723
724
725 -- Calculate SCCs of the module graph, with or without taking into
726 -- account source imports.
727 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
728 topological_sort include_source_imports summaries
729    = let 
730          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
731          toEdge summ
732              = (summ, name_of_summary summ, 
733                       (if include_source_imports 
734                        then ms_srcimps summ else []) ++ ms_imps summ)
735         
736          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
737          mash_edge (summ, m, m_imports)
738             = case lookup m key_map of
739                  Nothing -> panic "reverse_topological_sort"
740                  Just mk -> (summ, mk, 
741                                 -- ignore imports not from the home package
742                                 catMaybes (map (flip lookup key_map) m_imports))
743
744          edges     = map toEdge summaries
745          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
746          scc_input = map mash_edge edges
747          sccs      = stronglyConnComp scc_input
748      in
749          sccs
750
751
752 -- Chase downwards from the specified root set, returning summaries
753 -- for all home modules encountered.  Only follow source-import
754 -- links.  Also returns a Bool to indicate whether any of the roots
755 -- are module Main.
756 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
757 downsweep rootNm old_summaries
758    = do rootSummaries <- mapM getRootSummary rootNm
759         let a_root_is_Main 
760                = any ((=="Main").moduleNameUserString.name_of_summary) 
761                      rootSummaries
762         all_summaries
763            <- loop (concat (map ms_imps rootSummaries))
764                 (filter (isHomeModule.ms_mod) rootSummaries)
765         return (all_summaries, a_root_is_Main)
766      where
767         getRootSummary :: FilePath -> IO ModSummary
768         getRootSummary file
769            | haskellish_file file
770            = do exists <- doesFileExist file
771                 if exists then summariseFile file else do
772                 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))      
773            | otherwise
774            = do exists <- doesFileExist hs_file
775                 if exists then summariseFile hs_file else do
776                 exists <- doesFileExist lhs_file
777                 if exists then summariseFile lhs_file else do
778                 getSummary (mkModuleName file)
779            where 
780                  hs_file = file ++ ".hs"
781                  lhs_file = file ++ ".lhs"
782
783         getSummary :: ModuleName -> IO ModSummary
784         getSummary nm
785            = do found <- findModule nm
786                 case found of
787                    Just (mod, location) -> do
788                         let old_summary = findModInSummaries old_summaries mod
789                         new_summary <- summarise mod location old_summary
790                         case new_summary of
791                            Nothing -> return (fromJust old_summary)
792                            Just s  -> return s
793
794                    Nothing -> throwDyn (OtherError 
795                                    ("can't find module `" 
796                                      ++ showSDoc (ppr nm) ++ "'"))
797                                  
798         -- loop invariant: home_summaries doesn't contain package modules
799         loop :: [ModuleName] -> [ModSummary] -> IO [ModSummary]
800         loop [] home_summaries = return home_summaries
801         loop imps home_summaries
802            = do -- all modules currently in homeSummaries
803                 let all_home = map (moduleName.ms_mod) home_summaries
804
805                 -- imports for modules we don't already have
806                 let needed_imps = nub (filter (`notElem` all_home) imps)
807
808                 -- summarise them
809                 needed_summaries <- mapM getSummary needed_imps
810
811                 -- get just the "home" modules
812                 let new_home_summaries
813                        = filter (isHomeModule.ms_mod) needed_summaries
814
815                 -- loop, checking the new imports
816                 let new_imps = concat (map ms_imps new_home_summaries)
817                 loop new_imps (new_home_summaries ++ home_summaries)
818
819 -----------------------------------------------------------------------------
820 -- Summarising modules
821
822 -- We have two types of summarisation:
823 --
824 --    * Summarise a file.  This is used for the root module passed to
825 --      cmLoadModule.  The file is read, and used to determine the root
826 --      module name.  The module name may differ from the filename.
827 --
828 --    * Summarise a module.  We are given a module name, and must provide
829 --      a summary.  The finder is used to locate the file in which the module
830 --      resides.
831
832 summariseFile :: FilePath -> IO ModSummary
833 summariseFile file
834    = do hspp_fn <- preprocess file
835         modsrc <- readFile hspp_fn
836
837         let (srcimps,imps,mod_name) = getImports modsrc
838             (path, basename, ext) = splitFilename3 file
839
840         Just (mod, location)
841            <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
842            
843         maybe_src_timestamp
844            <- case ml_hs_file location of 
845                  Nothing     -> return Nothing
846                  Just src_fn -> maybe_getModificationTime src_fn
847
848         return (ModSummary mod
849                            location{ml_hspp_file=Just hspp_fn}
850                            srcimps imps
851                            maybe_src_timestamp)
852
853 -- Summarise a module, and pick up source and timestamp.
854 summarise :: Module -> ModuleLocation -> Maybe ModSummary 
855     -> IO (Maybe ModSummary)
856 summarise mod location old_summary
857    | isHomeModule mod
858    = do let hs_fn = unJust "summarise" (ml_hs_file location)
859
860         maybe_src_timestamp
861            <- case ml_hs_file location of 
862                  Nothing     -> return Nothing
863                  Just src_fn -> maybe_getModificationTime src_fn
864
865         -- return the cached summary if the source didn't change
866         case old_summary of {
867            Just s | ms_hs_date s == maybe_src_timestamp -> return Nothing;
868            _ -> do
869
870         hspp_fn <- preprocess hs_fn
871         modsrc <- readFile hspp_fn
872         let (srcimps,imps,mod_name) = getImports modsrc
873
874         maybe_src_timestamp
875            <- case ml_hs_file location of 
876                  Nothing     -> return Nothing
877                  Just src_fn -> maybe_getModificationTime src_fn
878
879         when (mod_name /= moduleName mod) $
880                 throwDyn (OtherError 
881                    (showSDoc (text "file name does not match module name: "
882                               <+> ppr (moduleName mod) <+> text "vs" 
883                               <+> ppr mod_name)))
884
885         return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
886                                  srcimps imps
887                                  maybe_src_timestamp))
888         }
889
890    | otherwise
891    = return (Just (ModSummary mod location [] [] Nothing))
892
893 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
894 maybe_getModificationTime fn
895    = (do time <- getModificationTime fn
896          return (Just time)) 
897      `catch`
898      (\err -> return Nothing)
899 \end{code}