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