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