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