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