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