[project @ 2001-02-05 11:18:54 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 )
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    
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 -- Add the given (LM-form) Linkables to the UI, overwriting previous
476 -- versions if they exist.
477 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
478 add_to_ui ui lis
479    = filter (not_in lis) ui ++ lis
480      where
481         not_in :: [Linkable] -> Linkable -> Bool
482         not_in lis li
483            = all (\l -> modname_of_linkable l /= mod) lis
484            where mod = modname_of_linkable li
485                                   
486
487 data CmThreaded  -- stuff threaded through individual module compilations
488    = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
489
490
491 -- Compile multiple modules, stopping as soon as an error appears.
492 -- There better had not be any cyclic groups here -- we check for them.
493 upsweep_mods :: GhciMode
494              -> DynFlags
495              -> UnlinkedImage         -- valid linkables
496              -> (ModuleName -> [ModuleName])  -- to construct downward closures
497              -> CmThreaded            -- PCS & HST & HIT
498              -> [SCC ModSummary]      -- mods to do (the worklist)
499                                       -- ...... RETURNING ......
500              -> IO (Bool{-complete success?-},
501                     CmThreaded,
502                     [ModSummary],     -- mods which succeeded
503                     [Linkable])       -- new linkables
504
505 upsweep_mods ghci_mode dflags oldUI reachable_from threaded 
506      []
507    = return (True, threaded, [], [])
508
509 upsweep_mods ghci_mode dflags oldUI reachable_from threaded 
510      ((CyclicSCC ms):_)
511    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
512                           unwords (map (moduleNameUserString.name_of_summary) ms))
513         return (False, threaded, [], [])
514
515 upsweep_mods ghci_mode dflags oldUI reachable_from threaded 
516      ((AcyclicSCC mod):mods)
517    = do --case threaded of
518         --   CmThreaded pcsz hstz hitz
519         --      -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
520
521         (threaded1, maybe_linkable) 
522            <- upsweep_mod ghci_mode dflags oldUI threaded mod 
523                           (reachable_from (name_of_summary mod))
524         case maybe_linkable of
525            Just linkable 
526               -> -- No errors; do the rest
527                  do (restOK, threaded2, modOKs, linkables) 
528                        <- upsweep_mods ghci_mode dflags oldUI reachable_from 
529                                        threaded1 mods
530                     return (restOK, threaded2, mod:modOKs, linkable:linkables)
531            Nothing -- we got a compilation error; give up now
532               -> return (False, threaded1, [], [])
533
534
535 -- Compile a single module.  Always produce a Linkable for it if 
536 -- successful.  If no compilation happened, return the old Linkable.
537 upsweep_mod :: GhciMode 
538             -> DynFlags
539             -> UnlinkedImage
540             -> CmThreaded
541             -> ModSummary
542             -> [ModuleName]
543             -> IO (CmThreaded, Maybe Linkable)
544
545 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
546    = do 
547         let mod_name = name_of_summary summary1
548         let verb = verbosity dflags
549
550         when (verb == 1) $
551            if (ghci_mode == Batch)
552                 then hPutStr stderr (progName ++ ": module " 
553                         ++ moduleNameUserString mod_name
554                         ++ ": ")
555                 else hPutStr stderr ("Compiling "
556                         ++ moduleNameUserString mod_name
557                         ++ " ... ")
558
559         let (CmThreaded pcs1 hst1 hit1) = threaded1
560         let old_iface = lookupUFM hit1 mod_name
561
562         let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
563
564             source_unchanged = isJust maybe_old_linkable
565
566             (hst1_strictDC, hit1_strictDC)
567                = retainInTopLevelEnvs 
568                     (filter (/= (name_of_summary summary1)) reachable_from_here)
569                     (hst1,hit1)
570
571             old_linkable 
572                = unJust "upsweep_mod:old_linkable" maybe_old_linkable
573
574         compresult <- compile ghci_mode summary1 source_unchanged
575                          old_iface hst1_strictDC hit1_strictDC pcs1
576
577         case compresult of
578
579            -- Compilation "succeeded", but didn't return a new
580            -- linkable, meaning that compilation wasn't needed, and the
581            -- new details were manufactured from the old iface.
582            CompOK pcs2 new_details new_iface Nothing
583               -> do let hst2         = addToUFM hst1 mod_name new_details
584                         hit2         = addToUFM hit1 mod_name new_iface
585                         threaded2    = CmThreaded pcs2 hst2 hit2
586
587                     if ghci_mode == Interactive && verb >= 1 then
588                       -- if we're using an object file, tell the user
589                       case maybe_old_linkable of
590                         Just (LM _ _ objs@(DotO _:_))
591                            -> do hPutStr stderr (showSDoc (space <> 
592                                    parens (hsep (text "using": 
593                                         punctuate comma 
594                                           [ text o | DotO o <- objs ]))))
595                                  when (verb > 1) $ hPutStrLn stderr ""
596                         _ -> return ()
597                       else
598                         return ()
599
600                     return (threaded2, Just old_linkable)
601
602            -- Compilation really did happen, and succeeded.  A new
603            -- details, iface and linkable are returned.
604            CompOK pcs2 new_details new_iface (Just new_linkable)
605               -> do let hst2      = addToUFM hst1 mod_name new_details
606                         hit2      = addToUFM hit1 mod_name new_iface
607                         threaded2 = CmThreaded pcs2 hst2 hit2
608
609                     return (threaded2, Just new_linkable)
610
611            -- Compilation failed.  compile may still have updated
612            -- the PCS, tho.
613            CompErrs pcs2
614               -> do let threaded2 = CmThreaded pcs2 hst1 hit1
615                     return (threaded2, Nothing)
616
617 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
618 removeFromTopLevelEnvs :: [ModuleName]
619                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
620                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
621 removeFromTopLevelEnvs zap_these (hst, hit, ui)
622    = (delListFromUFM hst zap_these,
623       delListFromUFM hit zap_these,
624       filterModuleLinkables (`notElem` zap_these) ui
625      )
626
627 retainInTopLevelEnvs :: [ModuleName]
628                         -> (HomeSymbolTable, HomeIfaceTable)
629                         -> (HomeSymbolTable, HomeIfaceTable)
630 retainInTopLevelEnvs keep_these (hst, hit)
631    = (retainInUFM hst keep_these,
632       retainInUFM hit keep_these
633      )
634      where
635         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
636         retainInUFM ufm keys_to_keep
637            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
638         maybeLookupUFM ufm u 
639            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
640
641 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
642 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
643 downwards_closure_of_module summaries root
644    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
645          toEdge summ = (name_of_summary summ, ms_allimps summ)
646          res = simple_transitive_closure (map toEdge summaries) [root]             
647      in
648          --trace (showSDoc (text "DC of mod" <+> ppr root
649          --                 <+> text "=" <+> ppr res)) (
650          res
651          --)
652
653 -- Calculate transitive closures from a set of roots given an adjacency list
654 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
655 simple_transitive_closure graph set 
656    = let set2      = nub (concatMap dsts set ++ set)
657          dsts node = fromMaybe [] (lookup node graph)
658      in
659          if   length set == length set2
660          then set
661          else simple_transitive_closure graph set2
662
663
664 -- Calculate SCCs of the module graph, with or without taking into
665 -- account source imports.
666 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
667 topological_sort include_source_imports summaries
668    = let 
669          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
670          toEdge summ
671              = (summ, name_of_summary summ, 
672                       (if include_source_imports 
673                        then ms_srcimps summ else []) ++ ms_imps summ)
674         
675          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
676          mash_edge (summ, m, m_imports)
677             = case lookup m key_map of
678                  Nothing -> panic "reverse_topological_sort"
679                  Just mk -> (summ, mk, 
680                                 -- ignore imports not from the home package
681                                 catMaybes (map (flip lookup key_map) m_imports))
682
683          edges     = map toEdge summaries
684          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
685          scc_input = map mash_edge edges
686          sccs      = stronglyConnComp scc_input
687      in
688          sccs
689
690
691 -- Chase downwards from the specified root set, returning summaries
692 -- for all home modules encountered.  Only follow source-import
693 -- links.  Also returns a Bool to indicate whether any of the roots
694 -- are module Main.
695 downsweep :: [FilePath] -> IO ([ModSummary], Bool)
696 downsweep rootNm
697    = do rootSummaries <- mapM getRootSummary rootNm
698         let a_root_is_Main 
699                = any ((=="Main").moduleNameUserString.name_of_summary) 
700                      rootSummaries
701         all_summaries
702            <- loop (filter (isHomeModule.ms_mod) rootSummaries)
703         return (all_summaries, a_root_is_Main)
704      where
705         getRootSummary :: FilePath -> IO ModSummary
706         getRootSummary file
707            | haskellish_file file
708            = do exists <- doesFileExist file
709                 if exists then summariseFile file else do
710                 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))      
711            | otherwise
712            = do exists <- doesFileExist hs_file
713                 if exists then summariseFile hs_file else do
714                 exists <- doesFileExist lhs_file
715                 if exists then summariseFile lhs_file else do
716                 getSummary (mkModuleName file)
717            where 
718                  hs_file = file ++ ".hs"
719                  lhs_file = file ++ ".lhs"
720
721         getSummary :: ModuleName -> IO ModSummary
722         getSummary nm
723            -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
724            = do found <- findModule nm
725                 case found of
726                    -- Be sure not to use the mod and location passed in to 
727                    -- summarise for any other purpose -- summarise may change
728                    -- the module names in them if name of module /= name of file,
729                    -- and put the changed versions in the returned summary.
730                    -- These will then conflict with the passed-in versions.
731                    Just (mod, location) -> summarise mod location
732                    Nothing -> throwDyn (OtherError 
733                                    ("can't find module `" 
734                                      ++ showSDoc (ppr nm) ++ "'"))
735                                  
736         -- loop invariant: homeSummaries doesn't contain package modules
737         loop :: [ModSummary] -> IO [ModSummary]
738         loop homeSummaries
739            = do let allImps :: [ModuleName]
740                     allImps = (nub . concatMap ms_imps) homeSummaries
741                 let allHome   -- all modules currently in homeSummaries
742                        = map (moduleName.ms_mod) homeSummaries
743                 let neededImps
744                        = filter (`notElem` allHome) allImps
745                 neededSummaries
746                        <- mapM getSummary neededImps
747                 let newHomeSummaries
748                        = filter (isHomeModule.ms_mod) neededSummaries
749                 if null newHomeSummaries
750                  then return homeSummaries
751                  else loop (newHomeSummaries ++ homeSummaries)
752
753
754 -----------------------------------------------------------------------------
755 -- Summarising modules
756
757 -- We have two types of summarisation:
758 --
759 --    * Summarise a file.  This is used for the root module passed to
760 --      cmLoadModule.  The file is read, and used to determine the root
761 --      module name.  The module name may differ from the filename.
762 --
763 --    * Summarise a module.  We are given a module name, and must provide
764 --      a summary.  The finder is used to locate the file in which the module
765 --      resides.
766
767 summariseFile :: FilePath -> IO ModSummary
768 summariseFile file
769    = do hspp_fn <- preprocess file
770         modsrc <- readFile hspp_fn
771
772         let (srcimps,imps,mod_name) = getImports modsrc
773             (path, basename, ext) = splitFilename3 file
774
775         Just (mod, location)
776            <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
777            
778         maybe_src_timestamp
779            <- case ml_hs_file location of 
780                  Nothing     -> return Nothing
781                  Just src_fn -> maybe_getModificationTime src_fn
782
783         return (ModSummary mod
784                            location{ml_hspp_file=Just hspp_fn}
785                            srcimps imps
786                            maybe_src_timestamp)
787
788 -- Summarise a module, and pick up source and interface timestamps.
789 summarise :: Module -> ModuleLocation -> IO ModSummary
790 summarise mod location
791    | isHomeModule mod
792    = do let hs_fn = unJust "summarise" (ml_hs_file location)
793         hspp_fn <- preprocess hs_fn
794         modsrc <- readFile hspp_fn
795         let (srcimps,imps,mod_name) = getImports modsrc
796
797         maybe_src_timestamp
798            <- case ml_hs_file location of 
799                  Nothing     -> return Nothing
800                  Just src_fn -> maybe_getModificationTime src_fn
801
802         if mod_name == moduleName mod
803                 then return ()
804                 else throwDyn (OtherError 
805                         (showSDoc (text "file name does not match module name: "
806                            <+> ppr (moduleName mod) <+> text "vs" 
807                            <+> ppr mod_name)))
808
809         return (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
810                                srcimps imps
811                                maybe_src_timestamp)
812
813    | otherwise
814    = return (ModSummary mod location [] [] Nothing)
815
816 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
817 maybe_getModificationTime fn
818    = (do time <- getModificationTime fn
819          return (Just time)) 
820      `catch`
821      (\err -> return Nothing)
822 \end{code}