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