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