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